upxo.pxtal.fm_steel_3d package

Subpackages

Submodules

Module contents

fm_steel_3d: Complete 3D ferrite-martensite steel microstructure generation framework.

This package provides a chainable, stateful pipeline for generating realistic FM steel microstructures from labeled grain images (LFI), with full hierarchical decomposition into PAGs, packets, and blocks, plus Kurdjumov-Sachs orientation assignment and comprehensive visualization.

Main Classes (Pipeline Chain)

  • FMSteel3DBase: Foundation grain structure from LFI

  • FMSteel3DWithPAGs: Base + PAG partitioning

  • FMSteel3DWithBlocks: PAGs + martensitic blocks

  • FMSteel3DWithOrientations: Blocks + BCC orientations

  • FMSteel3DWithSubBlocks: Sub-blocks (laths) + per-sub-block orientation spread (complete)

Worker Classes (Stateless Utilities)

  • BlockGenerator3D: Block slicing logic

  • SubBlockGenerator3D: Sub-block slicing logic

  • OrientationAssigner3D: KS variant assignment + sub-block orientation spread

  • MeshExporter3D: Abaqus mesh generation (C3D8/C3D4/C3D20/C3D10; see mesh_exporter_3d.py)

Visualization Classes (Viz Workers)

  • GrainStructureViz3D: Grain and block PyVista plots

  • OrientationViz3D: IPF maps, pole figures, KS verification

  • DataViz3D: Statistical distributions (matplotlib)

Usage Example

>>> from upxo.pxtal.fm_steel_3d import FMSteel3DBase
>>> lfi = np.random.randint(1, 100, (50, 50, 50))
>>> fm = FMSteel3DBase.from_lfi(lfi, physical_dimensions=(100, 100, 100))
>>>
>>> # Generate PAGs
>>> fm_pag = fm.generate_pag_clusters(
...     pag_size_distribution={'sizes': [3, 4, 6], 'probs': [0.25, 0.5, 0.25]},
...     pag_grain_fraction=0.8,
...     random_seed=42
... )
>>>
>>> # Assign PAG orientations then generate blocks
>>> fm_pag.assign_pag_orientations(pag_ori_mode='random', random_seed=42)
>>> fm_blk = fm_pag.generate_blocks(block_thickness_range=(2.0, 5.0), random_seed=42)
>>>
>>> # Assign KS block orientations
>>> fm_ori = fm_blk.assign_orientations(ks_variant_selection='random_per_block', random_seed=42)
>>>
>>> # Visualize
>>> fm_ori.visualize_block_ipf_map()
>>> fm_ori.plot_pag_map_pyvista()
class upxo.pxtal.fm_steel_3d.FMSteel3DBase(lgi: ndarray, physical_dimensions: PhysicalDimensions, voxel_size: float, units: str = 'microns', connectivity: int = 6, grain_locs: Dict[int, ndarray] | None = None, n_grains: int = 0, neigh_gid: Dict[int, List[int]] | None = None, min_grain_nvoxels: int = -1, random_seed: int | None = None, verbosity: int = 0, log_sink=None)[source]

Bases: object

Foundation FM steel grain structure from labeled grain image (LFI).

Entry point to the pipeline. Detects grains, builds neighbor graph, optionally cleans small grains, then enables PAG clustering.

lgi
physical_dimensions
voxel_size
units
connectivity
grain_locs
n_grains
neigh_gid
min_grain_nvoxels
classmethod from_lfi(lfi: ndarray, physical_dimensions: Tuple[float, float, float], voxel_size: float = 1.0, units: str = 'microns', connectivity: int = 6, min_grain_nvoxels: int = -1, grain_cleanup_max_passes: int = 100, random_seed: int | None = None, verbosity: int = 0, log_sink=None) → FMSteel3DBase[source]

Create FMSteel3DBase instance from a labeled grain image.

This is the primary factory method. It initializes grain locations, computes neighbor relationships, and optionally performs cleanup (dissolution of small grains) if min_grain_nvoxels >= 0.

Parameters:
  • lfi (np.ndarray) – 3D labeled grain image. Shape (nx, ny, nz). Values are grain IDs (1, 2, …, n_grains).

  • physical_dimensions (tuple[float, float, float]) – Physical domain size as (Lx, Ly, Lz).

  • voxel_size (float, optional) – Size of each voxel. Default 1.0. Must be positive.

  • connectivity (int, optional) – Grain connectivity (6, 18, or 26). Default 6 (face connectivity only). Values: 6 = face, 18 = face+edge, 26 = face+edge+corner.

  • min_grain_nvoxels (int, optional) – Minimum grain size in voxels. If >= 0, triggers cleanup via clean_gs_GMD_by_source_erosion_v1. Grains below threshold are dissolved into neighboring larger grains. Default -1 (no cleanup).

  • random_seed (int, optional) – Random seed for reproducibility. If provided, numpy random state is set at initialization.

Returns:

Fully initialized grain structure instance.

Return type:

FMSteel3DBase

Raises:

ValueError – If lfi is not 3D, connectivity is invalid, or physical_dimensions are invalid.

Examples

>>> lfi = np.random.randint(1, 100, size=(50, 50, 50))
>>> fm = FMSteel3DBase.from_lfi(lfi, physical_dimensions=(100.0, 100.0, 100.0))
>>> print(fm.n_grains)
compute_grain_locations() → Dict[int, ndarray][source]

Compute voxel coordinates for each grain from LGI.

Single sort-and-split pass over all non-background voxels — O(N log N) in voxel count, independent of grain count. Replaces an earlier per-grain np.argwhere(lgi == gid) loop that rescanned the full array once per grain (O(n_grains * N)); on a 100^3 domain with ~3000 grains that loop took ~7s vs ~0.08s here (verified equivalent output on randomized structures before replacing).

Returns:

Maps grain_id → (n_voxels, 3) array of voxel coordinates.

Return type:

dict[int, np.ndarray]

Notes

Results are cached in self.grain_locs after first call.

compute_neighbor_network(connectivity: int | None = None) → Dict[int, List[int]][source]

Compute grain neighbor relationships using cc3d.region_graph.

Parameters:

connectivity (int, optional) – Connectivity type (6, 18, 26). If None, uses self.connectivity.

Returns:

Maps grain_id → list of neighbor grain_ids.

Return type:

dict[int, list[int]]

Notes

Results are cached in self.neigh_gid after first call. Uses cc3d.region_graph for efficient neighbor detection.

clean_small_grains(threshold: int, parameter_metric: str = 'mean', max_passes: int = 100) → FMSteel3DBase[source]

Dissolve grains smaller than threshold into larger neighbors.

Reimplements clean_gs_GMD_by_source_erosion_v1 from mcgs3_temporal_slice.py to work independently. Iteratively merges small grains with their largest neighboring grains until all remaining grains are >= threshold voxels.

Does NOT modify self – returns a new FMSteel3DBase instance with the cleaned grain structure. Callers must use the return value, e.g. fm = fm.clean_small_grains(threshold=10).

Parameters:
  • threshold (int) – Minimum grain size (voxels). Grains with fewer voxels are dissolved.

  • parameter_metric (str, optional) – Reserved for future sink-selection strategies (‘mean’, ‘max’, etc., matching the original clean_gs_GMD_by_source_erosion_v1 API). Currently unused: this reimplementation always merges into the largest neighboring grain regardless of the value passed.

Returns:

New instance with the cleaned grain structure.

Return type:

FMSteel3DBase

Notes

This is called automatically by from_lfi if min_grain_nvoxels >= 0.

Each pass is fully vectorized: grain sizes come from a single np.bincount, and neighbour-label detection for ALL small grains in the pass is done via whole-array shifted-slice comparisons (one pair of slices per connectivity offset, not per grain/voxel), followed by a single array-wide relabel. This replaced an earlier per-grain, per-voxel, per-offset Python loop; verified to produce identical grain-size distributions on randomized test structures (including a deliberately chained small-into-small-into-large merge case), while running roughly 500-650x faster on a 100^3 / ~3000-grain domain. A pass’s merge decisions are all computed from that pass’s start-of- pass snapshot and applied together, rather than the previous implementation’s incidental order-dependence (where a grain processed later in the same pass could see an earlier grain’s already-applied merge) — final converged results are equivalent, occasionally reaching convergence in a different number of passes.

remove_spikes()[source]

Remove spike voxels (face-connected same-grain neighbour count <= 1).

Each spike voxel is reassigned to whichever neighbouring grain has the most face-touching voxels. Single vectorised detection pass, small Python loop only over the (typically very few) spike voxels. Adapted from StructureCleaner3D._fast_clean_spikes in the twinned_simple_3d pipeline.

Returns:

(new_instance, spike_count)

Return type:

tuple[FMSteel3DBase, int]

get_grain_statistics() → Dict[str, any][source]

Compute basic statistics on grain structure.

Returns:

Keys: ‘n_grains’, ‘min_voxels’, ‘max_voxels’, ‘mean_voxels’, ‘median_voxels’, ‘total_voxels’, ‘domain_voxels’.

Return type:

dict

generate_pag_clusters(pag_size_distribution: Dict, pag_grain_fraction: float = 1.0, use_non_neigh_pag: bool = False, isolated_grain_strategy: str = 'auto', isolated_size_tol: float = 0.25, random_seed: int | None = None) → FMSteel3DWithPAGs[source]

Partition grains into PAGs (Prior Austenite Grains) via neighbour clustering.

Uses stochastic breadth-first-search on the grain neighbour graph to form PAGs. Returns a new FMSteel3DWithPAGs instance.

Parameters:
  • pag_size_distribution (dict) –

    Dict with keys ‘sizes’ (list of target cluster sizes) and ‘probs’ (list of corresponding probabilities, must sum to ~1.0).

    Example: {‘sizes’: [3, 4, 5, 6, 7],

    ’probs’: [0.10, 0.30, 0.40, 0.15, 0.05]}

  • pag_grain_fraction (float, optional) – Volume fraction of the grain structure that participates in PAG clustering (0.0–1.0, measured in voxels). The remaining volume becomes isolated grains. Default 1.0 (all grains participate).

  • use_non_neigh_pag (bool, optional) – If True, each new PAG seed is chosen from grains that do not yet neighbour any formed PAG, keeping PAGs spatially separated. As pag_grain_fraction increases this becomes impossible; once no non-neighbour candidates remain the algorithm falls back to a random seed from any remaining unclustered grain. Default False (original random-seed behaviour).

  • isolated_grain_strategy (str, optional) –

    Strategy for selecting which grains become isolated. Ignored when pag_grain_fraction >= 1.0. Options:

    ’auto’ — BFS runs until the volume target is met; remaining

    grains become isolated (original behaviour).

    ’random’ — random independent set (no two isolated grains touch). ‘smallest’ — smallest-first independent set. ‘largest’ — largest-first independent set. ‘boundary’ — domain-boundary grains preferred in the independent set. ‘near_mean’ — grains closest to mean grain size preferred (primary:

    within isolated_size_tol of mean; fallback: by distance).

    Default ‘auto’.

  • isolated_size_tol (float, optional) – Fractional tolerance around the mean grain size for the ‘near_mean’ strategy. E.g. 0.25 accepts grains within ±25% of the mean voxel count as primary candidates before falling back. Default 0.25.

  • random_seed (int, optional) – Random seed for reproducibility.

Returns:

New instance with computed PAG hierarchy.

Return type:

FMSteel3DWithPAGs

class upxo.pxtal.fm_steel_3d.FMSteel3DWithPAGs(parent, clusters_dict: Dict[int, List[int]], neigh_clid: Dict[int, List[int]], pag_orientations: Dict[int, Tuple[float, float, float]] | None = None, isolated_grains: set | None = None, retained_austenite_pag_ids: set | None = None, target_pag_grain_fraction: float | None = None, retained_austenite_selection_info: Dict | None = None, random_seed: int | None = None, verbosity: int | None = None, log_sink=None)[source]

Bases: object

FM steel grain structure with PAG (Prior Austenite Grain) hierarchy.

Holds the base grain structure plus the computed PAG clustering. PAGs are groups of grains that will be further subdivided into packets and then blocks.

This is an intermediate state in the pipeline. It is created by calling generate_pag_clusters() on a FMSteel3DBase instance, and transitions to FMSteel3DWithBlocks by calling generate_blocks().

_parent

Reference to parent grain structure (read-only base state).

Type:

FMSteel3DBase

clusters_dict

Maps PAG ID → list of grain IDs contained in that PAG.

Type:

dict[int, list[int]]

neigh_clid

Maps PAG ID → list of neighboring PAG IDs.

Type:

dict[int, list[int]]

pag_orientations

Will store parent FCC (austenite) orientations for each PAG. Filled by assign_pag_orientations() or by downstream methods. Format: {pag_id: (phi1_deg, Phi_deg, phi2_deg)}.

Type:

dict[int, tuple[float, float, float]]

isolated_grains

Grain IDs that do NOT participate in PAG clustering (controlled by pag_grain_fraction parameter). Kept for backward compatibility – for PAGs produced via pag_technique_selector_3d. generate_pags(), this is now just the flattened grain membership of retained_austenite_pag_ids; the PAGs themselves are NOT removed from clusters_dict (see retained_austenite_pag_ids).

Type:

set[int]

retained_austenite_pag_ids

PAG IDs (present in clusters_dict) that were selected to remain untransformed retained austenite rather than proceed to block generation. Populated by pag_technique_selector_3d.generate_pags(); empty for PAGs produced via the legacy FMSteel3DBase. generate_pag_clusters() pre-filter path (which excludes grains before clustering ever assigns them a PAG identity to preserve). A retained-austenite PAG still gets an orientation from assign_pag_orientations() like any other PAG; generate_blocks() skips these PAG IDs when slicing blocks.

Type:

set[int]

isolated_grain_orientations

FCC Bunge Euler orientations (degrees) for each isolated grain. Empty until assign_isolated_grain_orientations() is called. Format: {grain_id: (phi1_deg, Phi_deg, phi2_deg)}. Only meaningful for the legacy flat-isolated-grain case (grains in isolated_grains but not covered by retained_austenite_pag_ids); grains covered by a tracked retained-austenite PAG already have a correct, group-consistent orientation via pag_orientations and should not be re-assigned here.

Type:

dict[int, tuple[float, float, float]]

hagb_fallback_count

Number of PAGs for which assign_pag_orientations(pag_ori_mode= ‘hagb_constrained’, …) (or ‘textured’ with hagb_constraint=True) could not satisfy the HAGB threshold within max_attempts and fell back to the best candidate seen – the same count the method’s RuntimeWarning reports, kept here so it can be inspected without parsing warnings. None if that mode was never used.

Type:

int or None

grain_to_pag_id

Reverse lookup: grain_id -> pag_id. Derived from clusters_dict at construction time.

Type:

dict[int, int]

grain_to_local_pkt_idx

Maps grain_id -> 1-based ordinal of that grain within its PAG’s grain list (i.e. its local packet index). Ordinal follows the insertion order of clusters_dict[pag_id], which is determined by the clustering algorithm and is stable across the pipeline. Used to construct canonical elset names es.pck.{pag}.{pkt}.

Type:

dict[int, int]

_random_seed

Random seed used for this PAG generation.

Type:

int

clusters_dict
neigh_clid
isolated_grains
retained_austenite_pag_ids
pag_orientations
isolated_grain_orientations: Dict[int, Tuple[float, float, float]]
hagb_fallback_count: int | None
grain_to_pag_id: Dict[int, int]
grain_to_local_pkt_idx: Dict[int, int]
property lgi: ndarray

Labeled grain image from parent.

property grain_locs: Dict[int, ndarray]

Grain voxel coordinates from parent.

property neigh_gid: Dict[int, List[int]]

Grain neighbor relationships from parent.

property n_grains: int

Total grains in parent structure.

property physical_dimensions

Physical domain size from parent.

property voxel_size: float

Voxel size from parent.

property units: str

Physical unit string (‘microns’, ‘mm’, ‘m’) from base grain structure.

get_pag_phase(pag_id: int) → int[source]

Phase id (see phases_3d.py) for a given PAG.

Returns PHASE_RETAINED_AUSTENITE if pag_id is in retained_austenite_pag_ids, else PHASE_MARTENSITE. Does not validate that pag_id actually exists in clusters_dict.

property n_retained_austenite_pags: int

Number of PAGs tagged as retained austenite (still counted in n_pags/clusters_dict – these just never proceed to block generation).

property n_transformed_pags: int

Number of PAGs that will proceed to block generation (i.e. not retained austenite).

assign_pag_orientations(pag_ori_mode: str = 'random', pag_ori_params: Dict | None = None, random_seed: int | None = None) → None[source]

Assign FCC Bunge Euler orientations to PAGs in-place.

Parameters:
  • pag_ori_mode (str) – 'random' — uniform SO(3) (Phi sampled via arccos so the area element is correct). 'hagb_constrained' — random SO(3) with minimum HAGB constraint between neighbouring PAGs; pass hagb_threshold (float, deg), max_attempts (int), and optionally orientation_pool (list of (phi1,Phi,phi2) tuples) in pag_ori_params. 'textured' — sample PAG orientations from a synthetic FCC texture defined by named texture components; pass tc_info (dict of component → [volume_fraction, [phi1,Phi,phi2]]) and optionally N (pool size, default 5000) and hagb_constraint (bool, default False; if True, the texture pool is passed to the HAGB-constrained assigner). 'fixed' — all PAGs receive the same orientation; pass euler_angles=(phi1,Phi,phi2) in pag_ori_params.

  • pag_ori_params (dict, optional) – Extra parameters for the chosen mode (see above).

  • random_seed (int, optional) – RNG seed for reproducibility.

Returns:

Results stored in self.pag_orientations. For 'hagb_constrained', and for 'textured' with hagb_constraint=True, self.hagb_fallback_count is also set to the number of PAGs that could not meet the threshold.

Return type:

None

generate_blocks(block_thickness_range: Tuple[float, float] = (2.0, 5.0), random_seed: int | None = None, block_slab_connectivity: int = 26) → FMSteel3DWithBlocks[source]

Slice each PAG into martensitic blocks.

PAG orientations must be assigned before calling this method (via assign_pag_orientations). If self.pag_orientations is empty a RuntimeWarning is issued and random SO(3) orientations are used as a fallback so the pipeline can still complete.

Parameters:
  • block_thickness_range (tuple of (float, float), optional) – (lower, upper) bounds for block thickness in physical units. Each packet independently draws its thickness uniformly from this range. Default (2.0, 5.0).

  • random_seed (int, optional) – Random seed for block slicing.

  • block_slab_connectivity (int, optional) – CC3D connectivity for within-slab connected-component labelling (6, 18, or 26). Default 26.

Returns:

New instance with computed block hierarchy.

Return type:

FMSteel3DWithBlocks

Notes

Does not modify self; returns a new instance.

assign_isolated_grain_orientations(mode: str = 'random', hagb_threshold: float = 15.0, max_attempts: int = 1000, orientation_pool: List[Tuple[float, float, float]] | None = None, random_seed: int | None = None) → None[source]

Assign FCC Bunge Euler orientations to isolated (unclustered) grains.

Isolated grains are those excluded from PAG clustering (see isolated_grains attribute). Because they were never part of a PAG they carry no crystallographic orientation after generate_blocks; this method assigns one, ensuring HAGB compatibility with all already- assigned neighbours (both PAGs and other isolated grains).

Only processes grains in isolated_grains that are NOT covered by a tracked retained_austenite_pag_ids entry – those already have a correct, group-consistent orientation from assign_pag_orientations (every grain in a retained-austenite PAG shares that PAG’s single orientation, the same as a transformed PAG’s grains do) and must not be overwritten with a separately-drawn one here. This method exists for the legacy case: grains excluded before clustering ever assigned them a PAG identity (FMSteel3DBase.generate_pag_clusters’s pre-filter path), which have no orientation to inherit at all.

Parameters:
  • mode (str) – 'random' — draw candidate orientations from uniform SO(3). 'textured' — draw candidates from orientation_pool (which must be supplied; typically built from FCCTexture.generate_euler).

  • hagb_threshold (float) – Minimum cubic disorientation (degrees) required between this grain and each already-assigned neighbour. Default 15.0°.

  • max_attempts (int) – Maximum candidate draws per grain. If the threshold is never met, the best-seen orientation (largest minimum misorientation with neighbours) is used and a RuntimeWarning is issued. Default 1000.

  • orientation_pool (list of (phi1, Phi, phi2), optional) – Pre-generated pool of Bunge Euler angles (degrees) for textured mode. Ignored when mode=’random’. Must be non-empty.

  • random_seed (int or None) – RNG seed for reproducibility.

Returns:

Results stored in self.isolated_grain_orientations.

Return type:

None

Raises:

ValueError – If mode=’textured’ and orientation_pool is None or empty.

ensure_isolated_grain_orientations(random_seed: int | None = None) → None[source]

Guarantee every isolated grain has a resolvable crystallographic orientation – non-negotiable: no feature other than voids may go unassigned.

Most isolated grains already satisfy this automatically: a retained-austenite PAG produced by generate_pags() gets its orientation the same way any PAG does, via assign_pag_orientations() (see FMSteel3DWithPAGs class docstring). The only grains that can ever be missing one are legacy leftover isolated grains (from FMSteel3DBase.generate_pag_clusters()’s pre-filter path, which never gave them a PAG identity to inherit from) that nobody has yet run assign_isolated_grain_orientations() for.

This method closes that gap automatically: if any isolated grain is found with no orientation available from either source, it auto-assigns via assign_isolated_grain_orientations(‘random’, …) for the uncovered ones, with a warning, rather than silently leaving a real microstructural feature unoriented. Idempotent and cheap to call repeatedly – a no-op once every isolated grain is covered, and never re-draws an orientation that already exists.

Called automatically by MeshExporter3D and by the phase-aware IPF query before either one reads isolated_grain_orientations, so this rarely needs to be called directly.

get_isolated_grain_orientation(gid: int) → Tuple[float, float, float] | None[source]

Resolve one isolated grain’s FCC orientation from whichever source actually has it: its retained-austenite PAG’s orientation (grain_to_pag_id -> pag_orientations) if tracked, else isolated_grain_orientations for the legacy leftover case. Returns None if neither source has an entry (call ensure_isolated_grain_orientations() first to guarantee that never happens).

get_pag_statistics(histogram_cap: int = 10, compute_morphology: bool = False) → Dict[source]

Compute statistics on PAG structure.

Parameters:
  • histogram_cap (int, optional) – Grain-count histogram is broken out per-count from 1 up to and including this value; any PAG with more grains than this is bucketed into a single “{cap+1}+” key. Default 10.

  • compute_morphology (bool, optional) – Also compute per-PAG aspect ratio and solidity (a convex hull per PAG – not free, so opt-in). Default False.

Notes

Histogram keys are strings (e.g. “1”, “2”, …, “11+”), not ints — this dict is persisted verbatim into shared_state/session JSON, and JSON object keys are always strings; using string keys natively avoids an int-vs-str mismatch after a save/reload round trip.

property n_pags: int

Number of PAGs.

class upxo.pxtal.fm_steel_3d.FMSteel3DWithBlocks(parent, all_blocks: Dict[str, ndarray], grain_to_blocks_map: Dict[int, List[str]], grain_to_plane_idx: Dict[int, int] | None = None, block_slicing_normals: Dict[str, ndarray] | None = None, slicing_planes: Dict | None = None, random_seed: int | None = None, verbosity: int | None = None, log_sink=None)[source]

Bases: object

FM steel grain structure with block hierarchy.

Holds the PAG structure plus computed martensitic blocks within each PAG. Blocks represent the smallest scale of microstructural organization in this model (below blocks are grains, above blocks are PAGs).

This is an intermediate state in the pipeline. It is created by calling generate_blocks() on a FMSteel3DWithPAGs instance, and transitions to FMSteel3DWithOrientations by calling assign_orientations().

_parent

Reference to parent PAG structure (read-only intermediate state).

Type:

FMSteel3DWithPAGs

all_blocks

Maps block_id (str) → (n_voxels, 3) array of voxel coordinates. Block naming convention: ‘B_{pag_id}_{grain_id}_{local_id}’.

Type:

dict[str, np.ndarray]

grain_to_blocks_map

Maps grain_id (= packet identifier, global integer) → list of block_ids produced from that packet. Keys are grain_ids, NOT local packet ordinals. Use parent.grain_to_local_pkt_idx to convert grain_id to a local ordinal.

Type:

dict[int, list[str]]

slicing_planes

Stores the Plane objects used for slicing (for visualization/debugging).

Type:

dict

_random_seed

Random seed used for block generation.

Type:

int

all_blocks
grain_to_blocks_map
grain_to_plane_idx
block_slicing_normals
slicing_planes
property lgi: ndarray

Labeled grain image from base parent.

property grain_locs: Dict[int, ndarray]

Grain voxel coordinates from base parent.

property clusters_dict: Dict[int, List[int]]

PAG clustering from parent.

property neigh_clid: Dict[int, List[int]]

PAG adjacency from parent.

property pag_orientations: Dict[int, Tuple[float, float, float]]

PAG orientations from parent.

property grain_to_pag_id: Dict[int, int]

Reverse lookup grain_id -> pag_id, derived from parent clusters_dict.

property grain_to_local_pkt_idx: Dict[int, int]

grain_id -> local_idx.

Type:

1-based local packet ordinal within each PAG

property n_grains: int

Total grains in base structure.

property physical_dimensions

Physical domain size.

property n_pags: int

Number of PAGs.

property n_blocks: int

Number of blocks.

property voxel_size: float

Voxel size.

property units: str

Physical unit string (‘microns’, ‘mm’, ‘m’).

property isolated_grains

Isolated grains from parent PAG level.

property isolated_grain_orientations

Isolated-grain orientations from parent PAG level (see FMSteel3DWithPAGs docstring).

property retained_austenite_pag_ids

Retained-austenite PAG IDs from parent PAG level (see FMSteel3DWithPAGs docstring). These PAG IDs were skipped by generate_blocks(), so they never appear in all_blocks/ grain_to_blocks_map.

property neigh_gid: Dict[int, List[int]]

Grain-level neighbour graph from base level.

property n_retained_austenite_pags: int

Number of retained-austenite PAGs from parent PAG level.

property n_transformed_pags: int

Number of transformed (martensite-forming) PAGs from parent PAG level.

ensure_isolated_grain_orientations(random_seed: int | None = None) → None[source]

See FMSteel3DWithPAGs.ensure_isolated_grain_orientations.

get_isolated_grain_orientation(gid: int) → Tuple[float, float, float] | None[source]

See FMSteel3DWithPAGs.get_isolated_grain_orientation.

assign_orientations(ks_variant_selection: str = 'random_per_block', random_seed: int | None = None) → FMSteel3DWithOrientations[source]

Assign BCC crystal orientations to blocks via the Kurdjumov-Sachs relationship.

PAG orientations must already be set (via assign_pag_orientations on the parent FMSteel3DWithPAGs). Each block receives one of the 24 KS variants from the physically appropriate packet for its habit plane.

Parameters:
  • ks_variant_selection (str, optional) – 'random_per_block' — adjacency-aware greedy graph-colouring: adjacent blocks within a packet receive different KS variants where possible, with a random choice among the free variants. 'deterministic' — always assigns KS variant index 0 from the packet; reproducible for geometry verification. Default 'random_per_block'.

  • random_seed (int, optional) – Random seed for reproducibility.

Returns:

New instance with computed orientations; does not modify self.

Return type:

FMSteel3DWithOrientations

assign_custom_block_orientations(euler_dict: Dict[str, Tuple[float, float, float]], random_seed: int | None = None) → FMSteel3DWithOrientations[source]

Bypass KS variant assignment with a user-supplied block orientation dict.

Use this as injection point C: apply any arbitrary orientation distribution to the existing block morphology without re-running the KS pipeline.

Parameters:
  • euler_dict (dict) – {block_id: (phi1, Phi, phi2)} — Bunge ZXZ Euler angles in degrees. Extra keys not in all_blocks are ignored (warning issued). Missing blocks will have no orientation in the returned object.

  • random_seed (int, optional) – Stored in the returned FMSteel3DWithOrientations for reproducibility.

Return type:

FMSteel3DWithOrientations

get_block_statistics() → Dict[source]

Compute statistics on block structure.

class upxo.pxtal.fm_steel_3d.FMSteel3DWithOrientations(parent, grain_orientations: Dict[int, Tuple[float, float, float]], block_orientations: Dict[str, Tuple[float, float, float]], pag_orientations: Dict[int, Tuple[float, float, float]] | None = None, block_to_variant_idx: Dict[str, int] | None = None, random_seed: int | None = None, verbosity: int | None = None, log_sink=None)[source]

Bases: object

Complete 3D FM steel microstructure with full hierarchy and orientations.

This is the final state in the FM steel generation pipeline. It contains: - Base grain structure - PAG partitioning - Block hierarchy within each PAG - BCC crystal orientations assigned to blocks

This state is ready for mesh generation, visualization, or export.

_parent

Reference to parent block structure (read-only complete structure).

Type:

FMSteel3DWithBlocks

grain_orientations

Maps grain ID → BCC Euler angles. Format: {grain_id: (phi1_deg, Phi_deg, phi2_deg)}.

Type:

dict[int, tuple[float, float, float]]

block_orientations

Maps block_id → BCC Euler angles. Format: {block_id: (phi1_deg, Phi_deg, phi2_deg)}.

Type:

dict[str, tuple[float, float, float]]

pag_orientations

Maps PAG ID → FCC (parent austenite) Euler angles. Format: {pag_id: (phi1_deg, Phi_deg, phi2_deg)}.

Type:

dict[int, tuple[float, float, float]]

_random_seed

Random seed used for orientation assignment.

Type:

int

grain_orientations
block_orientations
block_to_variant_idx
pag_orientations
property lgi: ndarray

Labeled grain image from base.

property grain_locs: Dict[int, ndarray]

Grain voxel coordinates from base.

property clusters_dict: Dict[int, List[int]]

PAG clustering.

property all_blocks: Dict[str, ndarray]

Block voxel data.

property grain_to_blocks_map: Dict[int, List[str]]

grain_id -> [block_id, …] mapping (keys are grain_ids = packet ids).

property grain_to_pag_id: Dict[int, int]

Reverse lookup grain_id -> pag_id.

property grain_to_local_pkt_idx: Dict[int, int]

grain_id -> local_idx.

Type:

1-based local packet ordinal within each PAG

property grain_to_plane_idx: Dict[int, int]

grain_id -> {111}FCC habit-plane index (0-3) from parent block level.

property block_slicing_normals: Dict[str, ndarray]

block_id -> unit normal of the {111}FCC habit plane used to slice it, from parent block level (see FMSteel3DWithBlocks docstring).

property n_grains: int

Total grains.

property n_blocks: int

Total blocks.

property n_pags: int

Total PAGs.

property physical_dimensions

Physical domain size.

property voxel_size: float

Voxel size.

property units: str

Physical unit string (‘microns’, ‘mm’, ‘m’).

property isolated_grains

Isolated grains from parent PAG level.

property retained_austenite_pag_ids

Retained-austenite PAG IDs from parent PAG level (see FMSteel3DWithPAGs docstring).

ensure_isolated_grain_orientations(random_seed: int | None = None) → None[source]

See FMSteel3DWithPAGs.ensure_isolated_grain_orientations.

get_isolated_grain_orientation(gid: int) → Tuple[float, float, float] | None[source]

See FMSteel3DWithPAGs.get_isolated_grain_orientation.

get_full_hierarchy_statistics() → Dict[str, any][source]

Compute comprehensive statistics across all hierarchy levels.

Returns:

Keys include: - n_grains, grain_voxel_stats - n_pags, pags_grains_stats - n_blocks, block_voxel_stats - n_isolated_grains - total_voxels_in_fm_structure

Return type:

dict

compute_misorientation_distribution(n_sample_pairs: int = 5000, random_seed: int | None = None) → Dict[str, ndarray][source]

Compute cubic-symmetry-reduced misorientation angles between block pairs.

Samples n_sample_pairs pairs in each category (within-PAG and across-PAG) and returns the disorientation angle (minimum over all 24 cubic symmetry operators).

Within-PAG distribution should show peaks at the KS-predicted angles (~10.5°, ~14.9°, ~20.6°, ~47.1°, ~60°). Across-PAG distribution should be roughly uniform (no preferred angle).

Parameters:
  • n_sample_pairs (int, optional) – Target number of sampled pairs per category. Default 5000.

  • random_seed (int, optional) – Random seed for reproducibility.

Returns:

‘within_pag’ : ndarray of disorientation angles in degrees ‘across_pag’ : ndarray of disorientation angles in degrees

Return type:

dict

get_ks_variant_statistics() → Dict[source]

How evenly the 6 KS variants within each packet were actually used.

For every (pag_id, plane_idx) packet with 2+ blocks, tallies how many blocks received each variant index that was actually assigned, then summarises that per-packet distribution with the same size_balance_metrics (cv, min_max_ratio, gini) used elsewhere for packet_size_balance – perfectly even usage across whichever variants were used gives cv=0, min_max_ratio=1, gini=0; a packet where every block ended up sharing one variant (the worst case the adjacency- aware graph-colouring in assign_orientations_to_all_blocks tries to avoid) sits at the opposite extreme.

Requires block_to_variant_idx, which is only populated when orientations were assigned via assign_orientations_to_all_blocks (i.e. FMSteel3DWithBlocks.assign_orientations()) – empty if custom block orientations were injected instead.

available_phases() → List[int][source]

Phase ids actually present in this structure, for populating a phase selector (e.g. for the block-level IPF map).

PHASE_MARTENSITE is present whenever any blocks exist; PHASE_ RETAINED_AUSTENITE is present whenever isolated_grains is non-empty (the flattened view covering both PAG-covered and leftover-isolated retained-austenite grains – see FMSteel3DWithPAGs docstring).

get_phase_voxels_and_orientations(phase_id: int) → Tuple[Dict, Dict[int, Tuple[float, float, float]]][source]

Feature voxels + orientations for one phase, for phase-filtered IPF maps (see viz/orientation_viz_3d.py).

PHASE_MARTENSITE -> block granularity: (all_blocks, block_orientations), exactly what the existing Block-Level IPF Map already renders (blocks only ever exist for transformed PAGs, so no filtering is needed).

PHASE_RETAINED_AUSTENITE -> grain granularity (retained austenite is never split into packets/blocks): every retained-austenite grain keyed by grain_id, orientation from either its retained PAG or its own isolated_grain_orientations entry.

Returns:

(features, orientations) – features: {feature_id: (n_voxels, 3) voxel coordinate array} orientations: {feature_id: (phi1, Phi, phi2) Bunge-Euler degrees}

Return type:

(dict, dict)

get_misorientation_statistics() → Dict[str, any][source]

Sample block-block misorientation statistics.

Draws up to 10 random pairs of blocks (not neighbours – any two blocks in the structure) via np.random.choice and computes their cubic misorientation with cubic_misorientation_old1.

Returns:

Empty if fewer than 2 blocks have an assigned orientation. Otherwise: ‘n_block_pairs_sampled’, ‘mean_block_misorientation_deg’, ‘std_block_misorientation_deg’, ‘block_misorientations’ (the raw per-pair angles, degrees).

Return type:

dict

build_euler_angle_3d_maps(level: str = 'block') → Tuple[ndarray, ndarray, ndarray][source]

Build dense 3D Euler angle maps (phi1, Phi, phi2) over the full RVE.

Each voxel receives the Bunge ZXZ Euler angles (degrees) of its parent block. Voxels not covered by any block (PAG boundaries, isolated grains) retain the zero initialisation.

Parameters:

level (str, optional) – Hierarchy level to draw orientations from. Currently only 'block' is supported. Default 'block'.

Returns:

Three float32 arrays, each shaped like self.lgi. Angles are in degrees (Bunge ZXZ convention).

Return type:

tuple of (phi1_3d, Phi_3d, phi2_3d)

plot_gs_pvvox(alpha: float = 1.0, title: str = 'FM Steel 3D', **kwargs)[source]

Visualize grain structure (PyVista voxels).

plot_pag_map_pyvista(gids_to_plot=None, **kwargs)[source]

Visualize PAG map.

plot_ipf_map_pyvista_v2(gids_to_plot=None, **kwargs)[source]

Visualize IPF map.

visualize_block_morphology(**kwargs)[source]

Visualize all blocks with random colors.

visualize_block_morphology_v1(**kwargs)[source]

Visualize all blocks with color bar.

visualize_block_ipf_map(**kwargs)[source]

Visualize blocks colored by IPF.

plot_pag_ks_verification_v1(pag_id: int, **kwargs)[source]

Verify KS relationship for a PAG.

plot_distribution(data: ndarray, title: str, xlabel: str, **kwargs)[source]

Plot histogram.

generate_subblocks(subblock_thickness_range_um: Tuple[float, float] = (0.5, 1.5), intrablock_ori_spread_deg: float = 2.0, thin_block_strategy: str = 'skip', random_seed: int | None = None, subblock_slab_connectivity: int = 26) → FMSteel3DWithSubBlocks[source]

Subdivide every block into sub-blocks (laths) with per-sub-block orientations.

Sub-block slicing reuses each block’s inherited slicing normal, so laths are parallel to the parent block’s habit plane. Orientations are the parent block orientation plus a small random axis-angle perturbation within ±intrablock_ori_spread_deg.

Parameters:
  • subblock_thickness_range_um (tuple of (float, float)) – (min, max) sub-block thickness in the same physical units as LX/LY/LZ (typically µm). Converted to voxels using the stored voxel_size.

  • intrablock_ori_spread_deg (float, optional) – Half-width of orientation spread around parent block (degrees). Default 2.0.

  • thin_block_strategy (str, optional) – Policy for blocks too thin to subdivide: ‘skip’ keeps the block whole. Default ‘skip’.

  • random_seed (int, optional) – Seed for reproducibility.

Return type:

FMSteel3DWithSubBlocks

to_dict() → Dict[source]

Serialize full hierarchy to dict.

class upxo.pxtal.fm_steel_3d.FMSteel3DWithSubBlocks(parent, all_subblocks: Dict[str, ndarray], block_to_subblocks_map: Dict[str, List[str]], subblock_orientations: Dict[str, Tuple[float, float, float]], subblock_slicing_normals: Dict[str, ndarray] | None = None, random_seed: int | None = None, verbosity: int | None = None, log_sink=None)[source]

Bases: object

Complete 3D FM steel microstructure with sub-block (lath) hierarchy.

Hierarchy: grains -> PAGs -> packets -> blocks -> sub-blocks

_parent

Parent orientation state (full block hierarchy with orientations).

Type:

FMSteel3DWithOrientations

all_subblocks

{subblock_id: (n_voxels, 3) voxel coordinate array}. Sub-block naming: ‘SB_{block_id}_{local}’ where block_id follows the ‘B_{pag_id}_{packet_id}_{local}’ convention.

Type:

dict[str, np.ndarray]

block_to_subblocks_map

{block_id: [subblock_id, …]} — maps every block to its sub-blocks.

Type:

dict[str, list[str]]

subblock_orientations

{subblock_id: (phi1, Phi, phi2)} in degrees — parent block orientation plus a small intra-block spread perturbation.

Type:

dict[str, tuple]

subblock_slicing_normals

{subblock_id: unit_normal (3,)} — inherited from parent block.

Type:

dict[str, np.ndarray]

_random_seed
Type:

int or None

all_subblocks
block_to_subblocks_map
subblock_orientations
subblock_slicing_normals
property lgi: ndarray
property grain_locs: Dict[int, ndarray]
property clusters_dict: Dict[int, List[int]]
property all_blocks: Dict[str, ndarray]
property block_orientations: Dict[str, Tuple[float, float, float]]
property pag_orientations: Dict[int, Tuple[float, float, float]]
property grain_to_blocks_map: Dict[int, List[str]]

grain_id -> [block_id, …] (keys are grain_ids = packet ids).

property grain_to_pag_id: Dict[int, int]

Reverse lookup grain_id -> pag_id.

property grain_to_local_pkt_idx: Dict[int, int]

grain_id -> local_idx.

Type:

1-based local packet ordinal within each PAG

property grain_to_plane_idx: Dict[int, int]

grain_id -> {111}FCC habit-plane index (0-3) from parent block level.

property grain_orientations: Dict[int, Tuple[float, float, float]]

Grain-level BCC orientations from parent orientations level.

property block_slicing_normals: Dict[str, ndarray]

block_id -> unit normal of the {111}FCC habit plane used to slice it, from parent block level (see FMSteel3DWithBlocks docstring).

property block_to_variant_idx: Dict[str, int]

block_id -> KS variant index (0-5) within its packet, from parent orientations level (see FMSteel3DWithOrientations docstring).

property physical_dimensions
property voxel_size: float
property units: str

Physical unit string (‘microns’, ‘mm’, ‘m’).

property isolated_grains

Isolated grains from parent PAG level.

property retained_austenite_pag_ids

Retained-austenite PAG IDs from parent PAG level (see FMSteel3DWithPAGs docstring).

ensure_isolated_grain_orientations(random_seed: int | None = None) → None[source]

See FMSteel3DWithPAGs.ensure_isolated_grain_orientations.

get_isolated_grain_orientation(gid: int) → Tuple[float, float, float] | None[source]

See FMSteel3DWithPAGs.get_isolated_grain_orientation.

available_phases() → List[int][source]

See FMSteel3DWithOrientations.available_phases.

get_phase_voxels_and_orientations(phase_id: int) → Tuple[Dict, Dict[int, Tuple[float, float, float]]][source]

See FMSteel3DWithOrientations.get_phase_voxels_and_orientations.

PHASE_MARTENSITE here is sub-block granularity (all_subblocks, subblock_orientations) – the finer level this class adds; retained austenite has no sub-block subdivision, so it stays grain granularity exactly as at the block level.

property n_grains: int
property n_pags: int
property n_blocks: int
property n_subblocks: int
reassign_subblock_orientations(intrablock_ori_spread_deg: float = 2.0, random_seed: int | None = None) → None[source]

Re-assign sub-block orientations in-place with a new spread value.

get_subblock_statistics() → Dict[source]

Return basic statistics on the sub-block structure.

class upxo.pxtal.fm_steel_3d.PhysicalDimensions(Lx: float, Ly: float, Lz: float)[source]

Bases: object

Container for physical domain dimensions (Lx, Ly, Lz).

Lx: float
Ly: float
Lz: float
classmethod from_tuple(dims_tuple: Tuple[float, float, float])[source]

Create from (Lx, Ly, Lz) tuple.

as_array() → ndarray[source]

Return as (Lx, Ly, Lz) array.

class upxo.pxtal.fm_steel_3d.BlockGenerator3D(verbosity: int = 0, default_voxel_size: float = 1.0)[source]

Bases: object

Worker class for generating martensitic blocks within PAGs.

This is a stateless utility class. It receives PAG voxel data and orientation information, and returns partitioned blocks. Multiple calls produce different results based on random seeds (stochastic slicing plane selection).

All methods are instance methods (not static) to allow storing session config (default parameters, verbosity, etc.) in future.

generate_blocks_for_all_pags(clusters_dict: Dict[int, List[int]], grain_locs: Dict[int, ndarray], pag_orientations: Dict[int, Tuple[float, float, float]], block_thickness_range: Tuple[float, float] = (2.0, 5.0), random_seed: int | None = None, slab_connectivity: int = 26) → Tuple[Dict[str, ndarray], Dict[int, List[str]], Dict[int, int], Dict[str, ndarray]][source]

Generate blocks for all PAGs.

Parameters:
  • clusters_dict (dict) – {pag_id: [grain_id, …]}.

  • grain_locs (dict) – {grain_id: (n_voxels, 3) array}.

  • pag_orientations (dict) – {pag_id: (phi1, Phi, phi2)}.

  • block_thickness_range (tuple of (float, float), optional) – (lower, upper) bounds for block thickness in physical units. Each packet draws its own thickness uniformly from this range, producing natural thickness variation across the microstructure. Default (2.0, 5.0).

  • random_seed (int, optional) – Random seed for reproducibility.

Returns:

(all_blocks, grain_to_blocks_map, grain_to_plane_idx, block_slicing_normals). grain_to_blocks_map keys are grain_ids (= packet identifiers); values are the list of block_ids created from that packet. block_slicing_normals maps each block_id to the unit normal of the slicing plane used to create it — required by SubBlockGenerator3D.

Return type:

tuple

get_slicing_planes_for_packet(pag_id: int, pag_orientations: Dict[int, Tuple[float, float, float]]) → List[Plane][source]

Return the four crystallographic slicing-plane candidates for a PAG.

The four {111}FCC plane normals (habit planes for martensite packets) are defined in the PAG crystal frame and rotated into the sample frame using the PAG’s Bunge Euler angles. If no orientation is stored for the PAG the four normals are returned in the reference (lab) frame as a fallback.

Parameters:
  • pag_id (int) – PAG identifier.

  • pag_orientations (dict) – {pag_id: (phi1, Phi, phi2)} in degrees (Bunge ZXZ convention).

Returns:

Four Plane objects with point=[0,0,0] (templates — point is set to the PAG centroid by the caller before slicing).

Return type:

list of Plane

slice_packet_into_blocks(packet_gid: int, cluster_id: int, voxel_coords: ndarray, block_thickness: float, slicing_plane: Plane, slab_connectivity: int = 26) → Dict[str, ndarray][source]

Slice a PAG/packet into contiguous blocks using plane-normal projection.

Algorithm: 1. Project all voxels onto the slicing-plane unit normal via signed distance. 2. Divide the projection range into parallel slabs of width block_thickness. 3. Within each slab, rasterise voxels into a local 3D boolean grid and run

connected-component labeling (cc3d, connectivity=slab_connectivity, default 26) to find spatially contiguous blocks.

  1. Return each component as a named block with its global voxel coordinates.

Parameters:
  • packet_gid (int) – Grain/packet identifier (used in block names).

  • cluster_id (int) – Parent cluster (PAG) identifier (used in block names).

  • voxel_coords (np.ndarray) – (n_voxels, 3) integer voxel coordinates.

  • block_thickness (float) – Desired slab thickness along the slicing-plane normal.

  • slicing_plane (Plane) – Plane whose unit_normal defines the slicing direction and whose point is the projection origin (typically the PAG centroid).

Returns:

newly_created_blocks – {block_name: (n_voxels, 3) array of global voxel coordinates}. Names are already globally unique (cluster_id + packet_gid + a local per-packet counter), so no separate global id is needed.

Return type:

dict

class upxo.pxtal.fm_steel_3d.SubBlockGenerator3D(verbosity: int = 0)[source]

Bases: object

Worker class for slicing martensitic blocks into sub-blocks (laths).

Sub-blocks within a block share the same slicing direction as their parent block and carry a small orientation spread around the parent block orientation.

Thin blocks whose projected thickness along the slicing normal is less than the minimum requested sub-block thickness are handled via thin_block_strategy:

‘skip’ — treat the entire block as a single sub-block (no subdivision). ‘upscale’ — caller must rescale the grid before calling; treated as ‘skip’

here if the block is still too thin after rescaling.

All voxels in every block are exhausted: the final slab of each block absorbs any remainder so no voxels are left unassigned.

generate_subblocks_for_all_blocks(all_blocks: Dict[str, ndarray], block_slicing_normals: Dict[str, ndarray], subblock_thickness_range: Tuple[float, float] = (1.0, 2.0), thin_block_strategy: str = 'skip', random_seed: int | None = None, slab_connectivity: int = 26) → Tuple[Dict[str, ndarray], Dict[str, List[str]], Dict[str, ndarray]][source]

Generate sub-blocks for every block in all_blocks.

Parameters:
  • all_blocks (dict) – {block_id: (n_voxels, 3) integer voxel coordinate array}.

  • block_slicing_normals (dict) – {block_id: unit_normal (3,)} — inherited from FMSteel3DWithBlocks.

  • subblock_thickness_range (tuple of (float, float)) – (min, max) sub-block thickness in voxels. Each block draws its own thickness uniformly from this range.

  • thin_block_strategy (str) –

    Policy for blocks whose projected thickness < min thickness: ‘skip’ — the whole block becomes one sub-block. ‘upscale’ — same as ‘skip’ at this stage; the caller should have

    already rescaled the grid before calling.

  • random_seed (int, optional) – Seed for reproducibility.

Returns:

  • all_subblocks (dict) – {subblock_id: (n_voxels, 3) array}.

  • block_to_subblocks_map (dict) – {block_id: [subblock_id, …]}.

  • subblock_slicing_normals (dict) – {subblock_id: unit_normal (3,)} — same normal as parent block, available for any further subdivision level.

class upxo.pxtal.fm_steel_3d.OrientationAssigner3D(verbosity: int = 0, log_sink=None)[source]

Bases: object

Worker class for assigning crystal orientations to blocks via KS relationship.

This is a stateless utility class. It receives PAG orientations and block data, and returns BCC orientations for each block following the Kurdjumov-Sachs relationship (24 variants grouped into 4 packets).

All methods are instance methods to allow storing session config.

last_hagb_fallback_count: int | None
static get_ks_rotations() → ndarray[source]

Return the 24 Kurdjumov-Sachs rotation matrices.

One canonical KS variant is constructed from the physical relationship {111}FCC || {110}BCC, <110>FCC || <111>BCC, then the complete set of variants is generated by right-multiplying by all 24 cubic symmetry operators (varying the parent’s equivalent crystallographic labeling, the group action that actually produces the standard 24-member KS family – verified against MTEX’s own KurdjumovSachs()/variants() reference implementation to 1e-6 deg).

Returns:

Shape (24, 3, 3) array of rotation matrices.

Return type:

np.ndarray

assign_orientations_to_all_blocks(all_blocks: Dict[str, ndarray], clusters_dict: Dict[int, List[int]], pag_orientations: Dict[int, Tuple[float, float, float]], grain_to_plane_idx: Dict[int, int], ks_variant_selection: str = 'random_per_block', random_seed: int | None = None) → Tuple[Dict[str, Tuple[float, float, float]], Dict[str, int]][source]

Assign BCC orientations to all blocks using the KS orientation relationship.

Block name format: ‘B_{pag_id}_{grain_id}_{local_counter}’. Each grain within a PAG is one packet, identified by grain_id (parts[2]). grain_to_plane_idx records which of the four {111}FCC habit planes (0-3) was assigned to each grain during block generation. That index maps directly to the packet index returned by group_ks_variants_into_packets, so each block draws its KS variant from the physically correct set of 6 variants.

Parameters:
  • all_blocks (dict) – {block_id: voxel_coords_array}.

  • clusters_dict (dict) – {pag_id: [grain_id, …]}.

  • pag_orientations (dict) – {pag_id: (phi1_deg, Phi_deg, phi2_deg)}.

  • grain_to_plane_idx (dict) – {grain_id: plane_index (0-3)} — produced by generate_blocks_for_all_pags.

  • ks_variant_selection (str, optional) –

    How to pick a KS variant for each block within its packet.

    • 'random_per_block' (default) — adjacency-aware greedy graph-colouring: adjacent blocks within the same packet are assigned different KS variants wherever possible, with a random choice among the free variants.

    • 'deterministic' — always assign KS variant index 0 from the packet, ignoring adjacency. Produces a fully reproducible, spatially uniform variant map useful for debugging and analytical checks of the KS geometry.

  • random_seed (int, optional) – Random seed for reproducibility.

Returns:

block_orientationsdict

{block_id: (phi1_deg, Phi_deg, phi2_deg)}.

block_to_variant_idxdict

{block_id: variant_index (0-5)} — which of the 6 KS variants within its packet this block received. Preserved (rather than discarded once used to compute the Euler angles above) so callers can build per-packet variant-balance statistics, or group blocks by shared variant, without re-deriving it from the orientation matrices.

Return type:

tuple of (block_orientations, block_to_variant_idx)

static group_ks_variants_into_packets(variant_Rs: ndarray) → Dict[int, List[ndarray]][source]

Group 24 KS variants into 4 packets based on {110}BCC || {111}FCC planes.

Each packet corresponds to one of the four {111}FCC habit planes. For each variant, the {110}BCC plane normal is transformed back into the FCC frame and matched to the closest {111}FCC plane via dot product.

Parameters:

variant_Rs (np.ndarray) – Shape (24, 3, 3) array of KS variant rotation matrices.

Returns:

{packet_index (0-3): [list of variant rotation matrices]}.

Return type:

dict

verify_block_orientations(block_orientations: Dict[str, Tuple[float, float, float]], n_samples: int = 2) → Dict[str, any][source]

Verify block orientations are physically plausible.

Randomly samples pairs of blocks and computes misorientations. Expected values depend on their packet assignment and variant selection.

Parameters:
  • block_orientations (dict) – {block_id: (phi1, Phi, phi2)}.

  • n_samples (int, optional) – Number of random block pairs to check. Default 2.

Returns:

Verification results (e.g., misorientation statistics).

Return type:

dict

static cubic_euler_bunge_to_matrix_v1(phi1: ndarray, Phi: ndarray, phi2: ndarray, degrees: bool = True) → ndarray[source]

Convert Bunge Euler angles to rotation matrix (vectorized).

Despite the name, this returns the Bunge g matrix (sample -> crystal) – the transpose of upxo.xtalphy.crystal_orientation.euler_bunge_to_matrix, which returns R = Rz(phi1) Rx(Phi) Rz(phi2) (crystal -> sample) for the same angles. matrix_to_euler_bunge is this function’s inverse and also expects/returns g.

Parameters:
  • phi1 (np.ndarray) – Euler angles (1D arrays of same length, or scalars).

  • Phi (np.ndarray) – Euler angles (1D arrays of same length, or scalars).

  • phi2 (np.ndarray) – Euler angles (1D arrays of same length, or scalars).

  • degrees (bool, optional) – If True, input angles are in degrees. Default True.

Returns:

g matrices (sample -> crystal), shape (…, 3, 3).

Return type:

np.ndarray

static matrix_to_euler_bunge(R: ndarray, degrees: bool = True) → Tuple[float, float, float][source]

Convert rotation matrix to Bunge Euler angles.

Parameters:
  • R (np.ndarray) – Rotation matrix, shape (3, 3).

  • degrees (bool, optional) – If True, return angles in degrees. Default True.

Returns:

(phi1, Phi, phi2) in degrees (or radians).

Return type:

tuple

disorientation_deg(ea1: Tuple[float, float, float], ea2: Tuple[float, float, float], degrees: bool = True) → float[source]

Compute the cubic disorientation angle between two orientations.

Applies full bicrystal cubic symmetry: H_i @ ΔR @ H_j^T over all 24×24 = 576 combinations of the proper cubic operators (det = +1). Returns the minimum rotation angle (disorientation), which lies in [0°, 62.8°] for the cubic point group.

Use this instead of cubic_misorientation_old1 whenever a physically correct disorientation is required (e.g. PAG-PAG or block-block plots).

Parameters:
  • ea1 (tuple of (phi1, Phi, phi2)) – Bunge ZXZ Euler angles.

  • ea2 (tuple of (phi1, Phi, phi2)) – Bunge ZXZ Euler angles.

  • degrees (bool, optional) – If True, angles are in degrees. Default True.

Returns:

Disorientation angle in degrees.

Return type:

float

cubic_misorientation_old1(EA1: Tuple[float, float, float], EA2: Tuple[float, float, float], unique_tol_deg: float = 0.0001, degrees: bool = True) → Tuple[float, float, float][source]

Compute the cubic (m-3m) disorientation between two orientations.

The minimum rotation angle over all 24 x 24 crystal-symmetry-equivalent pairs, as in disorientation_deg and mtex orientation.angle.

Parameters:
  • EA1 (tuple or ndarray) – Bunge Euler angles.

  • EA2 (tuple or ndarray) – Bunge Euler angles.

  • unique_tol_deg (float, optional) – Tolerance for symmetry equivalence (degrees).

  • degrees (bool, optional) – If True, angles and result in degrees.

Returns:

(disorientation_angle_deg, reduced relative rotation matrix, disorientation_angle_deg).

Return type:

tuple

assign_pag_orientations_with_hagb(pag_ids: List[int], pag_neigh_map: Dict[int, List[int]], orientation_pool: List[Tuple[float, float, float]] | None = None, hagb_threshold: float = 15.0, random_seed: int | None = None, max_attempts: int = 1000) → Dict[int, Tuple[float, float, float]][source]

Assign FCC parent orientations to PAGs with a HAGB misorientation constraint.

For each PAG, a candidate orientation is drawn from orientation_pool (or from the uniform SO(3) distribution if pool is None) and accepted only if its cubic misorientation with every already-assigned neighbouring PAG is at least hagb_threshold degrees. This ensures all PAG-PAG boundaries are high-angle, which is physically required for martensite.

PAGs are processed in a random order to avoid systematic bias. If no valid candidate is found within max_attempts draws, the best candidate seen so far (highest minimum misorientation with neighbours) is used and a RuntimeWarning is emitted.

Parameters:
  • pag_ids (list of int) – PAG IDs to assign orientations to.

  • pag_neigh_map (dict) – {pag_id: [neighbor_pag_id, …]} adjacency map (from neigh_clid).

  • orientation_pool (list of (phi1, Phi, phi2), optional) – Pre-computed candidate Euler angle triples in degrees (Bunge ZXZ). If None, candidates are drawn from the uniform SO(3) distribution.

  • hagb_threshold (float, optional) – Minimum cubic misorientation in degrees required at every PAG-PAG interface. Default 15.0°.

  • random_seed (int, optional) – Seed for reproducibility.

  • max_attempts (int, optional) – Maximum draws per PAG before falling back to the best candidate seen. Default 1000.

Returns:

{pag_id: (phi1_deg, Phi_deg, phi2_deg)}. Also sets self.last_hagb_fallback_count to the number of PAGs that needed the best-effort fallback.

Return type:

dict

assign_subblock_orientations(all_subblocks: Dict[str, ndarray], block_orientations: Dict[str, Tuple[float, float, float]], intrablock_ori_spread_deg: float = 2.0, random_seed: int | None = None) → Dict[str, Tuple[float, float, float]][source]

Assign orientations to sub-blocks as small perturbations of their parent block.

Each sub-block receives the parent block orientation rotated by a random axis-angle perturbation sampled from Uniform(-spread, +spread) degrees. The rotation axis is drawn uniformly from the unit sphere.

Sub-block names are expected in the form ‘SB_{block_id}_{local}’ so that the parent block_id can be recovered by stripping ‘SB_’ prefix and the trailing ‘_{local}’ suffix.

Parameters:
  • all_subblocks (dict) – {subblock_id: voxel_coords_array} — only keys are used here.

  • block_orientations (dict) – {block_id: (phi1, Phi, phi2)} in degrees (Bunge ZXZ).

  • intrablock_ori_spread_deg (float, optional) – Half-width of the orientation spread in degrees. Each sub-block draws a perturbation angle from Uniform(-spread, +spread). Default 2.0.

  • random_seed (int, optional) – Seed for reproducibility.

Returns:

{subblock_id: (phi1, Phi, phi2)} in degrees.

Return type:

dict

class upxo.pxtal.fm_steel_3d.MeshExporter3D(verbosity: int = 0, phase_id: int = 2, mat_data_flag: int = 0)[source]

Bases: object

Worker for generating Abaqus FEM meshes from FM steel 3-D microstructures.

Usage example

exporter = MeshExporter3D(verbosity=1) exporter.set_output_units(‘mm’) exporter.set_output_base_path(r’C:/MyProject/FEMInputs’) exporter.ignore_lfi_ids([0]) out_dir = exporter.export_c3d8(fm_state, ‘run_001’,

custom_message=’Made by Dr. A. Smith, Univ. X’)

material_format
n_depvar
load_axis
applied_displacement
step_time
write_step
initial_inc
min_inc
max_inc
max_increments
output_interval
element_outputs
node_outputs
length_scale
configure_analysis(*, material_format='reference_umat', n_depvar=1, load_axis='z', applied_displacement=0.2, step_time=80.0, write_step=True, initial_inc=0.01, min_inc=1e-08, max_inc=1.0, max_increments=10000, output_interval=0.5, element_outputs=('LE', 'NE', 'S', 'SDV'), node_outputs=('U',), length_scale=1.0)[source]
set_output_units(unit: str) → None[source]

Set physical unit for node coordinates written to .inp files.

set_voxel_limit(elem_type: str, new_max: int, new_warn: int | None = None) → None[source]

Override hard voxel limit (and optionally warn threshold) for one element type.

set_output_base_path(path: str) → None[source]

Override default output base directory. The path must already exist.

ignore_lfi_ids(ids: List[int]) → None[source]

Register feature IDs to treat as voids before meshing. IDs <= 0 are always void regardless of this list.

check_voxel_threshold(n_vox: int, elem_type: str, max_voxels_override: int | None = None) → Dict[source]

Pure (no I/O, no prompting) size/threshold check – the computation _preflight_check uses internally, exposed as its own public method so a caller that cannot answer an interactive input() prompt (the hard-limit branch of _preflight_check blocks on input() when no stdin is attached, e.g. when run from a background thread) can decide up front whether to ask for confirmation by its own means, then call export with force=True to bypass the interactive prompt entirely.

Returns:

dict with keys

Return type:

exceeds_hard, exceeds_warn, hard, warn, est_mb

export_c3d8(fm_state, folder_name: str, output_unit: str | None = None, max_voxels: int | None = None, force: bool = False, custom_message: str = '', phase_id: int | None = None, mat_data_flag: int | None = None) → Path[source]

Export as C3D8 (linear hexahedral) Abaqus mesh.

Parameters:
  • fm_state – FM steel pipeline state: FMSteel3DWithPAGs, …WithBlocks, …WithOrientations, or …WithSubBlocks.

  • folder_name (str) – Base folder name; suffix ‘1’ appended, auto-incremented if taken.

  • output_unit (str, optional) – Override output unit for this call (‘microns’, ‘mm’, ‘m’).

  • max_voxels (int, optional) – Override C3D8 hard voxel limit for this call.

  • force (bool) – Skip the consent prompt even when hard limit is exceeded.

  • custom_message (str) – Written to *Heading (e.g. ‘Made by Dr. A. Smith, Univ. X’).

  • phase_id (int, optional) – Override instance phase_id for this call (must be 2).

  • mat_data_flag (int, optional) – Override instance mat_data_flag for this call (0 or 1).

Returns:

Path to created output directory.

Return type:

Path

export_c3d4(fm_state, folder_name: str, output_unit: str | None = None, max_voxels: int | None = None, force: bool = False, custom_message: str = '', phase_id: int | None = None, mat_data_flag: int | None = None) → Path[source]

Export as C3D4 (linear tet) Abaqus mesh — 6 Kuhn tets per voxel.

Parameters:

export_c3d8) ((same as)

Returns:

Path to created output directory.

Return type:

Path

export_c3d20(fm_state, folder_name: str, output_unit: str | None = None, max_voxels: int | None = None, force: bool = False, custom_message: str = '', phase_id: int | None = None, mat_data_flag: int | None = None) → Path[source]

Export as C3D20 (quadratic hexahedral) Abaqus mesh.

Each voxel maps to one 20-node element (8 corners + 12 mid-edge nodes). Hard limit 1.5 M voxels; warn at 750 k.

export_c3d10(fm_state, folder_name: str, output_unit: str | None = None, max_voxels: int | None = None, force: bool = False, custom_message: str = '', phase_id: int | None = None, mat_data_flag: int | None = None) → Path[source]

Export as C3D10 (quadratic tetrahedral) Abaqus mesh.

Each voxel is decomposed into 6 Kuhn tets, each with 10 nodes (4 corners + 6 mid-edge nodes). Hard limit 1 M voxels; warn at 500 k.

mesh_fm_steel_c3d8(*args, **kwargs)[source]
mesh_fm_steel_c3d20(*args, **kwargs)[source]
write_fm_steel_abaqus_inp(*args, **kwargs)[source]