graintrace.fragmentation#
Grain fragmentation and reorientation analysis.
FragmentationAnalyzer groups the reorientation and fragmentation
capabilities that share the same crystal symmetry and column conventions:
reorientation (misorientation-from-a-reference-step) as a rare-event scalar;
orientation-based point-set segmentation (graph/Leiden) and its reduction to a per-grain table, shared by the simulation and experiment paths;
fragmentation detection: simulation intragranular sub-grains (
FragmentationAnalyzer.grain_fragments()) and experiment grain splits across load steps (FragmentationAnalyzer.detect_splits()).
Heavy dependencies (torch, neml2, scipy, networkit via GraphSpatialCluster)
are imported lazily inside the methods.
- class graintrace.fragmentation.FragmentationAnalyzer(symmetry='432', ori_cols=('ori_rodrigues_x', 'ori_rodrigues_y', 'ori_rodrigues_z'), coord_cols=('x', 'y', 'z'))[source]#
Bases:
objectReorientation and fragmentation analysis for simulation and experiment data.
Holds the crystal symmetry and the simulation orientation/coordinate column conventions shared by the methods. The experiment split detector (
detect_splits()) takes its own column params because grain tables use a different schema (Eul0/1/2,X/Y/Z).- Parameters:
symmetry (str) – crystal symmetry in orbifold notation (default
"432").ori_cols (Sequence[str]) – per-element neml2 MRP orientation columns in the simulation field CSVs (default
ori_rodrigues_x/y/z).coord_cols (Sequence[str]) – per-element coordinate columns in the simulation field CSVs (default
x/y/z).
- reorientation_from_reference(results, step, ref_step=None)[source]#
Per-element misorientation angle (deg) from a reference load step.
Joins the per-element field CSVs at
ref_stepandsteponidand returns the symmetry-reduced misorientation between the two orientations at each shared element. Theori_colshold neml2 v3 MRP orientations.- Parameters:
results – a
SimulationResultswhosefield_dirholds per-element CSVs.step (int) – field-step index to measure.
ref_step (int | None) – reference field-step index (defaults to the first field step).
- Returns:
element ids
(N,)and misorientation angles in degrees(N,), aligned to the ids common to both steps.- Return type:
(ids, deg)
- write_reorientation_field(results, step, out_csv, ref_step=None, extra_cols=())[source]#
Write
id,x,y,z,reorientation_deg(+ optional passthrough) for REI.The output is consumed unchanged by
IdentifyRareClusters. Passingextra_cols(e.g.nye_tensor_*or stress columns) carries those features through so the same CSV can drive a combined rare-event criterion.- Parameters:
- Returns:
The output CSV path.
- Return type:
- static mean_orientation_mrp(mrp_arr, symmetry='1')[source]#
Symmetry-aware quaternion (eigenvector) mean of neml2 MRP orientations.
A proper orientation mean (NOT an arithmetic mean of the MRP components). When
symmetrynames a crystal point group, every orientation is first folded to the symmetry-equivalent variant closest to the first (reference) orientation, so a set whose members are reported in different symmetry variants (which the plain quaternion mean would average into a meaningless result) still yields the correct mean. Withsymmetry="1"(the default) this reduces to the plain quaternion eigenvector (Markley) mean.
- static cluster_orientation_spread(mrp, labels, symmetry='432', q=95.0, max_points=5000, seed=0, background_label=-1)[source]#
Per-cluster
q-th percentile misorientation (deg) of points to the mean.Descriptive only; use
cluster_leak_check()to flag percolation.- Parameters:
mrp (ndarray) –
(N, 3)neml2 MRP orientations.labels (ndarray) –
(N,)integer cluster labels.symmetry (str) – crystal symmetry (orbifold notation).
q (float) – percentile.
max_points (int) – per-cluster random subsample size;
0uses all points.seed (int) – RNG seed for the subsampling.
background_label (int | Iterable[int] | None) – label(s) to skip in addition to all negative labels.
- Returns:
{label: spread_deg}per cluster.- Return type:
- static cluster_leak_check(mrp, labels, tol_deg, symmetry='432', min_leak_frac=0.02, min_leak_points=10, q=95.0, backstop_factor=2.0, max_points=5000, seed=0, background_label=-1)[source]#
Flag clusters that leaked across a grain boundary.
A cluster is flagged when a population of at least
min_leak_fracandmin_leak_pointsof its points is separated from the dominant one by an orientation gap and lies more thantol_degaway, or when itsq-th percentile spread exceedsbackstop_factor * tol_deg. Gap separation, unlike a spread percentile, catches a small leak without flagging a smooth intragranular gradient.- Parameters:
mrp (ndarray) –
(N, 3)neml2 MRP orientations.labels (ndarray) –
(N,)integer cluster labels.tol_deg (float) – segmentation misorientation cutoff (degrees).
symmetry (str) – crystal symmetry (orbifold notation).
min_leak_frac (float) – minimum fraction of the cluster in a leaked population.
min_leak_points (int) – minimum number of points in a leaked population.
q (float) – percentile for the reported spread and the backstop.
backstop_factor (float) – spread backstop as a multiple of
tol_deg;Nonedisables it.max_points (int) – per-cluster random subsample size;
0uses all points.seed (int) – RNG seed for the subsampling.
background_label (int | Iterable[int] | None) – label(s) to skip in addition to all negative labels.
- Returns:
{label: {"flagged", "spread_deg", "leak_frac", "leak_sep_deg"}}.- Return type:
- static merge_fragments_by_misorientation(mrp, labels, tol_deg, symmetry='432')[source]#
Merge sub-grain fragments whose mean orientations are within
tol_deg.Agglomerative, orientation-only merge for intragranular sub-grains: the two fragments with the smallest (symmetry-aware) mean misorientation are merged first, the merged mean is recomputed, and the process repeats until the closest remaining pair is at least
tol_degapart. Recomputing the mean each step avoids the single-linkage chaining that a fixed-mean union-find would suffer. Use it to impose a minimum sub-grain misorientation so a smooth intragranular gradient is not reported as several near-identical fragments.- Parameters:
- Returns:
(N,)contiguous 0-based labels after merging.- Return type:
- static absorb_fragments(coords, labels, min_size, k_neighbors=8, max_passes=25, mrp=None, max_miso_deg=None, symmetry='432', background_label=-1)[source]#
Absorb sub-
min_sizeclusters into a touching neighbour.Without the gate, a small cluster joins its largest-contact neighbour (legacy). With
mrpandmax_miso_deg, it joins the closest-misorientation neighbour withinmax_miso_deg, or stays as it is.- Parameters:
coords (ndarray) –
(N, 3)point coordinates.labels (ndarray) –
(N,)integer cluster labels.min_size (int) – clusters with fewer points are absorbed.
k_neighbors (int) – neighbours per point used to measure contact.
max_passes (int) – maximum number of absorption passes.
mrp (ndarray | None) –
(N, 3)neml2 MRP orientations; enables the gate.max_miso_deg (float | None) – gate tolerance (degrees);
Nonedisables the gate.symmetry (str) – crystal symmetry (orbifold notation).
background_label (int | Iterable[int] | None) – label(s) left untouched in addition to all negative labels; use
(0, -1)for a raw voxel grid.
- Returns:
(N,)labels, with clusters contiguous from 0 and ignored labels unchanged.- Return type:
- static adjacency_remerge(coords, mrp, labels, tol_deg, symmetry='432', k_neighbors=8, percolation_max_frac=None, spread_tol_deg=None, background_label=-1)[source]#
Merge spatially adjacent clusters within
tol_degmean misorientation.Merges are agglomerative: the closest pair merges first and the union mean is recomputed, so a gradual orientation change does not chain. The size cap applies only when
percolation_max_fracis set, which also restores the legacy fixed-mean union-find.- Parameters:
coords (ndarray) –
(N, 3)point coordinates.mrp (ndarray) –
(N, 3)neml2 MRP orientations.labels (ndarray) –
(N,)integer cluster labels.tol_deg (float) – merge threshold on mean misorientation (degrees).
symmetry (str) – crystal symmetry (orbifold notation).
k_neighbors (int) – neighbours per point used to measure contact.
percolation_max_frac (float | None) – legacy size cap, as a fraction of points;
Nonemeans no cap.spread_tol_deg (float | None) – reject a union that
cluster_leak_check()flags at this tolerance;Noneskips the check.background_label (int | Iterable[int] | None) – label(s) left untouched in addition to all negative labels.
- Returns:
(N,)labels, with clusters contiguous from 0 and ignored labels unchanged.- Return type:
- static gamma_sweep_leiden(csv_path, ckpt_base, gammas, n_points, spec, weight_cfg, max_edge_distance, graph_mode='grid', manhattan_radius=2, k=16, reduce_topk=12, n_jobs=1, n_threads=1, seed=42)[source]#
Build the misorientation graph once, then run Leiden per gamma.
The edges/weights depend only on the graph + misorientation cutoff (not gamma), so they are checkpointed and reused across the sweep.
- Returns:
list of dicts with keys
gamma,n_grains,max_frac,labels.- Parameters:
- Return type:
- static pick_gamma_by_percolation(sweep, percolation_max_frac=None)[source]#
Legacy pick: the smallest gamma whose biggest cluster is below a size cap.
If no gamma is below the cap, returns the one with the smallest
max_frac. Preferpick_gamma().- Parameters:
sweep (Sequence[dict]) – per-gamma results from
gamma_sweep_leiden().percolation_max_frac (float | None) – size cap as a fraction of points;
Nonereturns the lowest gamma.
- Returns:
The selected sweep entry.
- Return type:
- static pick_gamma(sweep, mode='lowest', mrp=None, spread_tol_deg=None, symmetry='432', percolation_max_frac=None, spread_q=95.0)[source]#
Choose a Leiden resolution from a gamma sweep, without a size cap.
"lowest"returns the lowest swept gamma."spread"returns the lowest gamma thatcluster_leak_check()does not flag, or else the one with the fewest flagged clusters. Whenmrpandspread_tol_degare given, every row is annotated in place withn_flaggedandmax_spread_deg.- Parameters:
sweep (Sequence[dict]) – per-gamma results from
gamma_sweep_leiden().mode (str) –
"lowest"or"spread".mrp (ndarray | None) –
(N, 3)neml2 MRP orientations; required for"spread".spread_tol_deg (float | None) – leak-check tolerance (degrees); required for
"spread".symmetry (str) – crystal symmetry (orbifold notation).
percolation_max_frac (float | None) – if set, use the legacy
pick_gamma_by_percolation().spread_q (float) – percentile for the spread diagnostics.
- Returns:
The selected sweep entry.
- Raises:
ValueError – for an unknown
modeor an emptysweep, or for"spread"withoutmrpandspread_tol_deg.- Return type:
- segment(coords, mrp, misori_tol_deg=5.0, graph_mode='grid', gamma=None, gamma_sweep=(0.5, 1.0, 2.0, 4.0, 8.0), rbf_sigma_deg=None, manhattan_radius=2, k=16, reduce_topk=12, grain_threshold_final=30, remerge_miso_deg=3.0, gamma_pick='lowest', spread_tol_deg=None, remerge_spread_check='auto', percolation_max_frac=None, absorb_max_miso_deg='auto', n_jobs=1, n_threads=1, seed=42, workdir=None, verbose=True)[source]#
Segment a point set by crystal orientation (graph / Leiden).
Wraps
GraphSpatialClusterwith a symmetry-aware misorientation metric. It picks a gamma, absorbs small fragments under a misorientation gate, then runs an agglomerative adjacency re-merge. There is no grain-size cap by default. Per-gamma diagnostics are stored inlast_gamma_diagnostics.- Parameters:
coords (ndarray) –
(N, 3)point coordinates (voxel centres or element centroids).mrp (ndarray) –
(N, 3)neml2 MRP orientations.misori_tol_deg (float) – hard misorientation edge cutoff (degrees).
graph_mode (str) –
"grid"for voxel grids,"knn"for scattered centroids.gamma (float | None) – fixed Leiden resolution;
Nonesweepsgamma_sweep.gamma_sweep (Sequence[float]) – resolutions to sweep when
gammaisNone.rbf_sigma_deg (float | None) – fixed RBF sigma (degrees); defaults to half
misori_tol_deg.manhattan_radius (int) – grid connectivity radius (
graph_mode="grid").k (int) – neighbours per node (
graph_mode="knn").reduce_topk (int | None) – keep the top-k edges per node by weight.
grain_threshold_final (int) – clusters smaller than this are absorbed.
remerge_miso_deg (float) – adjacency re-merge threshold (degrees).
gamma_pick (str) –
"lowest"or"spread"(seepick_gamma()).spread_tol_deg (float | None) – leak-check tolerance (degrees); defaults to
misori_tol_deg.remerge_spread_check (bool | str) – reject re-merges that the leak check flags;
"auto"means on, except on the legacy path.percolation_max_frac (float | None) – legacy size cap; setting it restores the legacy pipeline exactly.
Nonemeans no cap.absorb_max_miso_deg (float | str | None) – absorption gate (degrees);
"auto"meansmisori_tol_deg(off on the legacy path),Nonedisables the gate.n_jobs (int) – parallel workers for the edge-distance build.
n_threads (int) – threads for Leiden.
seed (int) – RNG seed.
workdir (str | None) – scratch directory; a temporary directory is used if
None.verbose (bool) – print the per-gamma diagnostics.
- Returns:
(N,)contiguous 0-based cluster labels aligned tocoordsrows.- Raises:
ValueError – for an invalid
"auto"-style string option.- Return type:
- seg_to_grain_table(labels, coords, mrp=None, euler=None, angle_convention='bunge', angle_type='radians', out_csv=None, background_label=-1, trim_miso_deg=None, trim_iters=2)[source]#
Reduce a labelled point set to a per-grain table (FF/NF/EBSD connector).
Produces the
grain_id, X, Y, Z, GrainRadius, Eul0, Eul1, Eul2schema shared by the FF reconstruction and synthetic-load experiment CSVs, so segmented NF/EBSD voxel grids and FF grain tables converge on one grain table thatdetect_splits()consumes.Orientation is a proper quaternion mean per grain (not an arithmetic mean of Euler angles). Provide orientations as either
mrp(neml2 MRP) oreuler(withangle_convention/angle_type).- Parameters:
labels (ndarray) –
(N,)integer grain labels.coords (ndarray) –
(N, 3)point coordinates.mrp (ndarray | None) –
(N, 3)neml2 MRP orientations (mutually exclusive witheuler).euler (ndarray | None) –
(N, 3)Euler angles (mutually exclusive withmrp).angle_convention (str) – Euler convention (used when
euleris given).angle_type (str) –
"degrees"or"radians"for the inputeuler.out_csv (str | None) – if given, also write the table to this CSV path.
background_label (int | Iterable[int]) – label, or iterable of labels, treated as non-grain and skipped. Defaults to
-1. See the note on label domains below before changing it.trim_miso_deg (float | None) – if set, drop points farther than this (degrees) from the grain mean and recompute it (orientation only).
trim_iters (int) – number of trim-and-recompute passes.
- Return type:
Note
Two different label domains reach this method, and the right ``background_label`` differs between them.
Output of
segment()(the documented NF/EBSD bridge). Contiguous 0-based grain labels over a point set the caller has already restricted to solid material.0is a real grain here, and there is no void row at all, so the default-1excludes nothing and is correct. Passingbackground_label=0on this input silently deletes a grain.A raw segmented voxel grid (
nf.segment.flood, or anything written throughgraintrace.nf.mesh.write_spn()). The domain is0void,>= 1grain,-1material-but-unsegmented. Passbackground_label=(0, -1)to drop both sentinels. Left at the default, the whole void region is emitted as one enormous “grain” with a meaningless mean orientation, which then matches against the next step indetect_splits().- Returns:
A
pandas.DataFramewith the grain-table schema (Euler in degrees, Bunge convention).- Parameters:
- Return type:
- grain_fragments(results, step, tol_deg=5.0, block_id_col='block_id', grain_ids=None, min_fragment_elems=5, min_subgrain_miso_deg=1.0, seg_kwargs=None)[source]#
Re-segment each original grain’s elements by orientation at a loaded step.
Groups the per-element field at
stepbyblock_id(the original grain subdomain), runssegment()(graph_mode="knn"for scattered mesh elements) within each grain, and composes afragment_labelof the form"{grain}.{k}"(k the 0-based sub-grain index). This measures intragranular fragmentation – how a single grain breaks into orientation sub-domains under load – keeping the parent grain id.- Parameters:
results – a
SimulationResults.step (int) – field-step index to analyse.
tol_deg (float) – misorientation tolerance (degrees) for the sub-grain segmenter.
block_id_col (str) – the grain/block-id column in the field CSV.
grain_ids (Sequence[int] | None) – grains (block ids) to analyse; defaults to all blocks present.
min_fragment_elems (int) – grains with fewer elements than this are left whole (one fragment); also passed as the segmenter absorb threshold.
min_subgrain_miso_deg (float) – minimum misorientation (degrees) between two sub-grains for them to count as distinct fragments. After Leiden, fragments whose mean orientations are closer than this are merged (agglomeratively, closest-pair first, means recomputed each step), so a smooth intragranular gradient chopped into near-identical Leiden communities collapses back to one fragment while genuine sub-grains (a real low-angle sub-boundary) survive.
0disables the merge.seg_kwargs (Dict | None) – overrides forwarded to
segment();gammadefaults to 0.25 ({"gamma": None}sweeps) and absorption is ungated.
- Returns:
(fragments_df, per_element_labels)wherefragments_dfhas one row per grain (grain_id,n_fragments,fragment_sizes,n_elements) andper_element_labelsmaps each elementidto its"{grain}.{k}"fragment label.- Return type:
- detect_splits(nodes_a, nodes_b, d_tol, theta_tol_deg, angle_convention='bunge', angle_type='degrees', ori_cols=('Eul0', 'Eul1', 'Eul2'), coord_cols=('X', 'Y', 'Z'), id_col='grain_id', top_k=8, adjacency_b=None, out_csv=None, d_tol_mode='absolute', alpha_a=1.0, alpha_b=1.0, alpha=1.0, radius_col='GrainRadius', assignment=None, volume_col='volume', in_overlap_a=None, in_overlap_b=None, n_null=0, seed=None)[source]#
Detect grain splits/merges/births/deaths between two load steps.
Cross edges pass a centroid-distance gate and a misorientation gate; each connected component of the A/B union graph is a lineage, classified by its
(nA, nB)shape. NF/EBSD reach this viaseg_to_grain_table().- Parameters:
nodes_a – per-grain tables (DataFrame or CSV path) for the two steps, with id, coordinate and orientation columns.
nodes_b – per-grain tables (DataFrame or CSV path) for the two steps, with id, coordinate and orientation columns.
d_tol (float) – maximum centroid distance; the gate floor in
"radius"mode.theta_tol_deg (float) – maximum misorientation (degrees).
angle_convention (str) –
"bunge"/"kocks"/"roe"Euler, or"mrp".angle_type (str) –
"degrees"or"radians"(Euler conventions only).id_col (str) – the grain-id column.
top_k (int | None) – B candidates probed per A grain (default 8;
None= all withind_tol). It caps a split’s child count."absolute"mode only; a non-default value warns in the radius modes.adjacency_b (Iterable[Tuple[int, int]] | None) – optional
(grain_id, grain_id)step-B adjacency pairs; drops split children not adjacent to a sibling (if no siblings are adjacent, the best candidate is kept as a match).out_csv (str | None) – if given, write the split correspondences to this CSV path.
d_tol_mode (str) –
"absolute"(default,d <= d_tol),"radius"(d <= max(d_tol, alpha_a*R_a, alpha_b*R_b)) or"radius_sum"(d <= alpha*(R_a + R_b)).alpha_a (float) – A-radius multiplier in
"radius"mode.alpha_b (float) – B-radius multiplier in
"radius"mode.alpha (float) – radius-sum multiplier in
"radius_sum"mode.radius_col (str) – radius column the radius modes need in both tables (default
"GrainRadius"); NaN or negative values count as 0.assignment (str | None) –
"one_to_one"adds a Hungarian assignment over the gated candidates (costmiso/theta_tol_deg + d/gate);Noneskips it.volume_col (str) – per-grain volume column; when present, recall is also volume-weighted.
in_overlap_a (str | Sequence[bool] | ndarray | None) – boolean mask or column name restricting A-side recall to the volume both steps see.
in_overlap_b (str | Sequence[bool] | ndarray | None) – the same for step B.
n_null (int) – chance trials with uniformly random B orientations (0 = skip).
seed (int | None) – seed for the
n_nullorientations.
- Returns:
dict with
components(list of{a_ids, b_ids, kind}),split_correspondences(DataFrame), the countsn_splits,n_merges,n_matches,n_births,n_deaths, andrecall(per-side linked fractions). Optionallyone_to_one(DataFrame ofa_id, b_id, miso_deg, dist, cost) andnull(n_null,mean_links,std_links,observed_linkscounted before the adjacency prune,observed_links_after_adjacency).- Raises:
ValueError – on an unknown
d_tol_modeorassignment, a negative tolerance or multiplier, or a radius mode withoutradius_col.- Warns:
UserWarning – on NaN or negative radii in a radius mode.
- Return type: