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: object

Reorientation 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).

last_gamma_diagnostics: List[dict]#

per-gamma diagnostics from the most recent segment() sweep

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_step and step on id and returns the symmetry-reduced misorientation between the two orientations at each shared element. The ori_cols hold neml2 v3 MRP orientations.

Parameters:
  • results – a SimulationResults whose field_dir holds 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. Passing extra_cols (e.g. nye_tensor_* or stress columns) carries those features through so the same CSV can drive a combined rare-event criterion.

Parameters:
  • results – a SimulationResults.

  • step (int) – field-step index to measure.

  • out_csv (str) – output CSV path.

  • ref_step (int | None) – reference field-step index (defaults to the first field step).

  • extra_cols (Sequence[str]) – additional feature columns to copy through for combined REI.

Returns:

The output CSV path.

Return type:

str

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 symmetry names 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. With symmetry="1" (the default) this reduces to the plain quaternion eigenvector (Markley) mean.

Parameters:
  • mrp_arr (ndarray) – (N, 3) neml2 MRP orientations.

  • symmetry (str) – crystal symmetry (orbifold notation) to fold variants under; "1" disables folding.

Returns:

(3,) mean neml2 MRP orientation.

Return type:

ndarray

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; 0 uses 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:

Dict[int, float]

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_frac and min_leak_points of its points is separated from the dominant one by an orientation gap and lies more than tol_deg away, or when its q-th percentile spread exceeds backstop_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; None disables it.

  • max_points (int) – per-cluster random subsample size; 0 uses 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:

Dict[int, Dict[str, Any]]

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_deg apart. 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:
  • mrp (ndarray) – (N, 3) neml2 MRP orientations aligned to labels.

  • labels (ndarray) – (N,) integer fragment labels.

  • tol_deg (float) – minimum mean misorientation (degrees) to keep two fragments distinct; closer pairs merge.

  • symmetry (str) – crystal symmetry (orbifold notation).

Returns:

(N,) contiguous 0-based labels after merging.

Return type:

ndarray

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_size clusters into a touching neighbour.

Without the gate, a small cluster joins its largest-contact neighbour (legacy). With mrp and max_miso_deg, it joins the closest-misorientation neighbour within max_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); None disables 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:

ndarray

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_deg mean 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_frac is 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; None means no cap.

  • spread_tol_deg (float | None) – reject a union that cluster_leak_check() flags at this tolerance; None skips 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:

ndarray

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:

List[dict]

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. Prefer pick_gamma().

Parameters:
Returns:

The selected sweep entry.

Return type:

dict

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 that cluster_leak_check() does not flag, or else the one with the fewest flagged clusters. When mrp and spread_tol_deg are given, every row is annotated in place with n_flagged and max_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 mode or an empty sweep, or for "spread" without mrp and spread_tol_deg.

Return type:

dict

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 GraphSpatialCluster with 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 in last_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; None sweeps gamma_sweep.

  • gamma_sweep (Sequence[float]) – resolutions to sweep when gamma is None.

  • 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" (see pick_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. None means no cap.

  • absorb_max_miso_deg (float | str | None) – absorption gate (degrees); "auto" means misori_tol_deg (off on the legacy path), None disables 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 to coords rows.

Raises:

ValueError – for an invalid "auto"-style string option.

Return type:

ndarray

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, Eul2 schema 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 that detect_splits() consumes.

Orientation is a proper quaternion mean per grain (not an arithmetic mean of Euler angles). Provide orientations as either mrp (neml2 MRP) or euler (with angle_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 with euler).

  • euler (ndarray | None) – (N, 3) Euler angles (mutually exclusive with mrp).

  • angle_convention (str) – Euler convention (used when euler is given).

  • angle_type (str) – "degrees" or "radians" for the input euler.

  • 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:

object

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. 0 is a real grain here, and there is no void row at all, so the default -1 excludes nothing and is correct. Passing background_label=0 on this input silently deletes a grain.

A raw segmented voxel grid (nf.segment.flood, or anything written through graintrace.nf.mesh.write_spn()). The domain is 0 void, >= 1 grain, -1 material-but-unsegmented. Pass background_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 in detect_splits().

Returns:

A pandas.DataFrame with the grain-table schema (Euler in degrees, Bunge convention).

Parameters:
Return type:

object

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 step by block_id (the original grain subdomain), runs segment() (graph_mode="knn" for scattered mesh elements) within each grain, and composes a fragment_label of 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. 0 disables the merge.

  • seg_kwargs (Dict | None) – overrides forwarded to segment(); gamma defaults to 0.25 ({"gamma": None} sweeps) and absorption is ungated.

Returns:

(fragments_df, per_element_labels) where fragments_df has one row per grain (grain_id, n_fragments, fragment_sizes, n_elements) and per_element_labels maps each element id to its "{grain}.{k}" fragment label.

Return type:

Tuple[object, Dict[int, str]]

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 via seg_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).

  • ori_cols (Sequence[str]) – the three orientation columns.

  • coord_cols (Sequence[str]) – the three coordinate columns.

  • id_col (str) – the grain-id column.

  • top_k (int | None) – B candidates probed per A grain (default 8; None = all within d_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 (cost miso/theta_tol_deg + d/gate); None skips 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_null orientations.

Returns:

dict with components (list of {a_ids, b_ids, kind}), split_correspondences (DataFrame), the counts n_splits, n_merges, n_matches, n_births, n_deaths, and recall (per-side linked fractions). Optionally one_to_one (DataFrame of a_id, b_id, miso_deg, dist, cost) and null (n_null, mean_links, std_links, observed_links counted before the adjacency prune, observed_links_after_adjacency).

Raises:

ValueError – on an unknown d_tol_mode or assignment, a negative tolerance or multiplier, or a radius mode without radius_col.

Warns:

UserWarning – on NaN or negative radii in a radius mode.

Return type:

Dict[str, Any]