Common pitfalls#

Segmentation no longer caps grain size#

Behaviour change. segment() now runs with no size cap (percolation_max_frac=None) and gamma_pick="lowest". Its absorption is orientation-gated, and its re-merge is agglomerative and leak-checked. Scripts will therefore get more small grains and no cap-split large grains. Pass percolation_max_frac=0.03 to reproduce the old labels exactly.

Do not use the p95 orientation spread to detect leaks. It misses a small leak and flags a smooth intragranular gradient. Use cluster_leak_check() instead.

NEPER is bring-your-own#

VoronoiMeshBuilder and CrystalGenerator resolve a user-installed NEPER via graintrace/neper_env.py. Precedence: explicit neper_path=/env= → NEPER env var → graintrace_tools.json "neper" key → neper on PATH. If none resolve, the builder raises a clear error. On Linux, auto_install=True performs a ~/.local source build.

CrystalGenerator seed is random by default#

CrystalGenerator defaults to seed=None, which draws a fresh random seed on every instantiation (printed to stdout), so each unseeded run is a different microstructure. Pass an explicit seed=<int> for a reproducible tessellation; the printed value reproduces a given run. (NEPER honors -id: different seed gives different grains, the same seed is byte-identical. The FF reconstruction path VoronoiMeshBuilder centroid/centroidsize is data-seeded via -morphooptiini, so its seed is inert — grains come from the measured centroids.)

detect_splits on mixed grain sizes#

No single d_tol works when grain sizes differ widely: use d_tol_mode="radius" rather than inflating d_tol, which chains unrelated neighbours. A NaN or negative radius counts as 0 (with a warning); negative tolerances raise ValueError.

Derive the cpfe_base path dynamically#

Do not hardcode it:

import graintrace as _gt
from pathlib import Path
_cpfe_base = str(Path(_gt.__file__).parent / "cpfe_base")

FF output orientations are always in degrees#

build_voronoi() always writes orientations.dat in degrees, regardless of input units. When feeding to VoxelMeshBuilder afterward, set angle_type="degrees".

graintrace’s orientation matrix is the active R (crystal -> sample)#

euler_to_matrix returns R = Rz(phi1) Rx(Phi) Rz(phi2) (MIDAS Euler2OrientMat / Grains.csv O, NEPER rotmat:active), not the classical passive Bunge g = R^T, and euler_to_mrp is the NEML2 MRP of R, which is what a NEML2 crystal model’s orientation is. graintrace 0.2 and earlier used g: matrices/MRP it wrote are the inverse rotation (Euler files are unaffected). Convert old MRP with legacy_mrp_to_mrp() and old matrices by transposing; rerun CPFE that was driven by the old MRP. The error is invisible on a random texture and wrong grain by grain, so check it on a crystal direction or an IPF corner, not on a texture statistic.

A frame change rotates orientations on the sample side#

A frame rotation Q sends orientations to Q R (the left side of the active R), not R Q^T. Crystal symmetry acts on the other (right) side, R S. The wrong side is invisible modulo cubic symmetry, so test it on a crystal direction (R c -> Q R c), not a misorientation. FrameTransform applies the sample-side rule; VoronoiMeshBuilder’s orientation_active_convention is deprecated and ignored.

NEPER descriptors are explicit; a bare rotmat is passive#

NEPER’s default orientation convention is passive: a bare rotmat in a .tess is g = R^T. graintrace passes Euler angles as euler-bunge:passive and asks for rotmat:active; the readers (NeperTessToGraphNN, VoronoiMeshBuilder.apply_rotation_to_properties) honour the suffix of any file. If you hand graintrace a NEPER matrix yourself, check its descriptor line. NEPER parameterises quaternion / Rodrigues / axis-angle relative to its passive matrix, so their textbook matrix is R for :passive.

graintrace requires NEPER 7#

graintrace builds its NEPER command lines for NEPER 7.x and refuses any other major version (neper_env.require_neper_version, called whenever NEPER is resolved). NEPER 4.x differs in ways that silently give wrong geometry: it reads weight: as a radius rather than a power weight, it uses the opposite sense for hspace inside -transform cut(...) and deletes cut-away cells where 7.x keeps them as empty entries, and it truncates -o paths at the first .. NEPER 7 rejects -morphooptialgo praxis (graintrace’s old default); the default is now "subplex" ("lloyd" also works) and a rejection is a ValueError.

Laguerre weights are the squared radius#

VoronoiMeshBuilder(weighted=True) and the stitching refinement RegionBaseStitching(refine_extents=True, tess_weighted=True) (the default tess_weighted) write the seed weight GrainRadius**2 in the coordinates’ length unit (neper_env.laguerre_weights). Before graintrace 0.3 they wrote (4/3) pi r^3 normalised to sum to 1, which is negligible against micrometre distances, so “weighted” runs were effectively unweighted; weighted results made with older versions change when rerun.

With real weights a seed inside a much larger neighbour’s power sphere can get an empty Laguerre cell, which NEPER deletes before renumbering the rest. The builder drops those input rows with a UserWarning naming them, so builder.data, orientations.dat, the .tess and the reformatted voxels stay one row per cell. Overlapping or duplicate FF grains are the usual cause; check the listed rows.

orientation_tolerance units must match ori_units#

When ori_units="radians", convert orientation_tolerance before passing it to RegionBaseStitching:

if ori_units == "radians":
    orientation_tolerance = np.deg2rad(orientation_tolerance)

grid_properties bounding box should be inset#

Inset grid_bb by 0.0001 on each face to avoid mesh-boundary issues, while using the full box for the boundary conditions (see Configuration reference).

CUDA material calibration: the model must be on the device#

TaylorModel(device="cuda") works because taylor.py moves the whole nonlinear system with nsys.to(device) before wrapping it in the pyzag factory. Moving only the factory leaves the crystal-geometry buffers on CPU, which surfaces as a silent loss=inf.

Use the GPU when one is available#

The GPU-accelerated steps are CPFE, material calibration, and pole figures. When a CUDA GPU is present, use it (device="cuda:0" for CPFE, TaylorModel(device="cuda") for calibration); CPU is much slower for these NEML2-dominated workloads.

Resuming a checkpoint validates the parameters that built it#

GraphSpatialCluster.run(resume_from_checkpoint=True) loads the stored edges and weights and skips graph building, distance filtering, sigma estimation and top-k pruning. Anything that shaped those arrays is therefore compared against the checkpoint metadata on resume, and a mismatch raises rather than returning the old graph as the answer to a new question. That covers the data itself (a sha256 of the coordinate and feature arrays), the metric, the graph mode and its connectivity, max_edge_distance, reduce_edges_topweights_k, and the weighting parameters each weight_cfg.mode actually reads: sigma and power for rbf, sigma for exp, eps for inverse and log_inv.

segmenter and the NetworKit options are deliberately not compared. They act after the graph is loaded, which is what makes reusing one checkpoint across a gamma sweep worthwhile.

One case needs care. When sigma is None the value is estimated from the edge distances, and resume skips the step that computes them, so the resolved sigma is not knowable without rebuilding the graph. Such a request is compared by its sigma_auto quantile instead, which is exact because everything feeding those distances is already compared. The consequence is that resuming a sigma-pinned checkpoint with a sigma=None request is reported as a mismatch. Pin the resolved sigma (it is recorded in <base>.meta.json as weight_sigma) if you want to reuse such a checkpoint.

Checkpoints written before a given check existed lack its metadata key; those warn instead of failing.

The multiprocessing guard#

NF reconstruction (graintrace/nf/convert.py) uses multiprocess.Pool, so scripts that call it must be under an if __name__ == "__main__": guard. The graph-clustering / REI pipeline does not require the guard, but keeping it is good practice.

Unsegmented voxels must not reach the mesh writers#

A segmented grid uses 0 for void, >= 1 for a grain and -1 for a voxel that is material but belongs to no grain. -1 is not only a flood-fill leftover: graintrace.nf.segment.remove_small_segments() reassigns a sub-threshold segment to -1 when it has no kept neighbour, so a pipeline that runs the infill before the removal, as reconstruct() does, can still hold orphans at the end.

nf.mesh.write_spn raises ValueError on such a grid rather than meshing it. Run graintrace.nf.segment.infill_nearest_neighbor() after remove_small_segments, or mask the orphans to void (0) yourself — write_spn will not do it for you, because dropping them silently removes material from the mesh. nf.mesh.write_voxel_exodus skips negative ids the same way it skips the background id, so an orphan never becomes a block of its own. Both builders end with graintrace.nf.segment.void_unsegmented(), which voids a -1 island that has no grain to join (e.g. a stray point in an air notch).

NF gridding is unmasked by default#

With min_confidence=None every grid point inside a layer’s Delaunay hull is crystal: air, the sample surface and low-confidence boundary voxels included. The boundary voxels connect neighbouring grains, so segmentation leaks across them. Set min_confidence on real data (see NF gridding options).

A phase column is not a void marker#

An EBSD .ang phase may be 0-based, so VoxelMeshBuilder no longer reads phase <= 0 as void. Pass void_marker_col="phase" when 0 means void.

SCULPT conventions: 1-based void, index coordinates, sparse block ids#

  • SCULPT ranks .spn values 1-based: with void present the void is material 1 and grain g is block g + 1. --void_mat 0 meshed the void as block 1. mesh_sculpt() passes --void_mat 1 when the grid has void (none otherwise), and raises if a block is still mostly void.

  • SCULPT writes voxel-index coordinates. They are mapped exactly, x = c0 - h/2 + raw * h, so the mesh covers the sample, not the scan box, and a single layer keeps a thickness (layer_spacing; NF uses dz).

  • SCULPT may drop small grains, leaving gaps in the block ids that the CPFE decks reject. Blocks are renumbered 1..N in file order; orientations row k is block k + 1.

Grain orientation averages need the crystal symmetry#

A cubic orientation has 24 equivalent rotation matrices, and a reconstruction may report voxels of one grain in different variants. Averaging across variants gives a mean close to no member of the set, so graintrace.nf.metrics.average_rotations() takes a symmetry argument and folds every member onto the variant closest to the first before averaging.

The default is symmetry="1" (the plain quaternion mean), which keeps direct callers of the low-level graintrace.nf.mesh writers unchanged. The NearFieldMeshBuilder and VoxelMeshBuilder pass their own symmetry (default "432") through to every orientation export, so the builder path is symmetry-aware without any extra configuration. If you call nf.mesh.write_spn, nf.mesh.mesh_sculpt or nf.mesh.write_voxel_exodus yourself, pass the crystal point group explicitly.