Configuration reference#

This page collects the configuration objects used across graintrace: meshing, boundary conditions, segmentation, clustering weights, the CPFE parameter groups, and external-tool paths.

sculpt_config#

Required for any builder step that calls builder.mesh(sculpt_config=...). It takes executable paths only, no license tokens.

sculpt_config = {
    "launcher": "/path/to/cubit/bin/mpi/bin/mpiexec",
    "psculpt":  "/path/to/cubit/bin/psculpt",
    "epu":      "/path/to/cubit/bin/epu",
    "nprocs":   10,
    "environment": {
        "OPAL_LIBDIR": "/path/to/cubit/bin/mpi/lib",
        "OPAL_PREFIX": "/path/to/cubit/bin/mpi",
    },
}

Required keys: psculpt, epu, nprocs. launcher and environment are needed for MPI-based execution.

sculpt_options#

A tuple of CLI flag strings passed to SCULPT:

sculpt_options = (
    "--adapt", "-A", "7",    # mesh adaptation level
    "-df", "1",              # dilation factor
    "-S", "2",               # smoothing passes
    "-CS", "4",              # curve smoothing
)

For FF Voronoi meshes without adaptation, pass (). Do not pass --void_mat: graintrace.nf.mesh.mesh_sculpt() sets --void_mat 1 when the grid has void (see SCULPT conventions: 1-based void, index coordinates, sparse block ids). After meshing, the block ids are renumbered to 1..N and <mesh stem>_block_map.csv maps each block_id to sculpt_block_id, grain_id, n_elem and source_grain_id. mesh(layer_spacing=...) sets the z thickness of a single-layer grid.

Boundary conditions (bc)#

bc = {
    "x": {"negative": "stress_free", "positive": "stress_free"},
    "y": {"negative": "stress_free", "positive": "stress_free"},
    "z": {"negative": 0, "positive": displace_amount},
}

"stress_free" means traction-free (no constraint). An integer/float is a prescribed displacement (0 = fixed).

Every face with a nonzero displacement is ramped from initialize_time to total_time and held flat by an EqualValueBoundaryConstraint named <face>_flat on that face’s own displacement component: front_flat on disp_z for the default z tension, right_flat on disp_x for an x-load, one constraint per loaded face. Fixed (0) and traction-free faces get none.

Segmentation#

Two methods are available for voxel segmentation (EBSD / NF-as-voxel).

Flood fill (simpler and faster):

segmentation = {
    "method": "flood",
    "params": {
        "misorientation_tol": 5.0 / 180 * np.pi,  # radians for VoxelMeshBuilder
        "connectivity": 26,                        # 6 or 26
        "grain_threshold_final": 1000,
        "batch_norm": 200_000,
        "grain_threshold": 1000,
        "stop_count": 500,         # budget of discarded segments; must be >= 1
    },
}

Graph-based (better for complex textures):

segmentation = {
    "method": "graph",
    "params": {
        "misorientation_tol": 5.0,   # degrees if angle_type="degrees", else radians
        "connectivity": 26,
        "grain_threshold_final": 100,
    },
    "graph_params": {
        "segmenter": "leiden",
        "graph_mode": "grid",
        "manhattan_radius": 2,
        "grid_tol": 1e-6,
        "n_jobs": 10,
        "weight_chunk_size": 1_000_000,
        "reduce_edges_topweights_k": 8,
        "nodes_chunk": 500_000,
        "seed": 42,
        "networkit_kwargs": {"gamma": 0.001},   # lower = fewer clusters
        "weight_cfg": {
            "mode": "rbf",
            "sigma": None,
            "sigma_auto": {"quantile": 0.5},
            "power": 2.0,
        },
        "plot": True,
    },
}

For reconstruct(), the segmentation argument is either the flat flood dict (no method/params nesting, with misorientation_tol in radians), or the graph/Leiden dict below, which runs segment() on the solid voxels (defaults in NearFieldMeshBuilder.DEFAULT_GRAPH_SEGMENTATION):

segmentation = {
    "method": "graph",
    "misori_tol_deg": 5.0,        # degrees
    "gamma": None,                # percolation sweep; ~0.1 for few-grain data
    "grain_threshold_final": 30,
    "remerge_miso_deg": 3.0,
    "downsample": (2, 2, 1),      # optional; large NF only
}

NF gridding options#

reconstruct() and convert() take:

min_confidence

Voxels whose source .mic point has a lower Confidence become void. NF confidence is bimodal, so one threshold (~0.3-0.5) separates sample from air and failed points. None (default) keeps every in-hull point.

max_point_distance

Maximum distance (µm) to the nearest measured point, replacing the Delaunay hull test; ~1.5 x TriEdgeSize.

voxel_size_um

(hx, hy) in-plane spacing instead of nx/ny (giving both raises).

The per-voxel confidence is saved as fixed_grid_confidence.npy. The builders take recursive=True for MIDAS per-layer subfolders. For VoxelMeshBuilder, only cell_id == -1 is void automatically; void_marker_col opts a column in (values <= 0 void).

Graph/Leiden is the default and better pathway for NF/EBSD; flood over-merges into percolating grains. The recipe (validated on Fe-9Cr NF reconstruction): hard 5° misorientation cutoff; manhattan_radius=2; a fixed broad RBF sigma ≈ half the cutoff (sigma_auto collapses to ~0.1° and shatters grains); reduce_edges_topweights_k=12; a Leiden gamma picked from a sweep [0.5, 1, 2, 4, 8]; then absorb sub-30-voxel fragments and an adjacency-only re-merge (~3°). It is implemented by graintrace.fragmentation.FragmentationAnalyzer.segment().

  • No grain-size cap. Mask low-confidence and void voxels instead. percolation_max_frac=0.03 restores the legacy pipeline exactly.

  • gamma_pick: "lowest" (default) or "spread", which picks the lowest gamma that cluster_leak_check() does not flag at spread_tol_deg (default: the cutoff). Per-gamma diagnostics are stored in last_gamma_diagnostics.

  • absorb_max_miso_deg (default: the cutoff): a fragment joins only the closest touching neighbour within this misorientation.

  • The re-merge is agglomerative, so it does not chain. remerge_spread_check (default on) rejects unions that fail the leak check.

  • downsample is optional; use it only when the graph does not fit.

  • seg_to_grain_table(trim_miso_deg=...) recomputes each grain mean without outlier points.

Orientation convention and NEPER#

All graintrace matrices are the active \(R = R_z(\varphi_1) R_x(\Phi) R_z(\varphi_2)\) (crystal \(\to\) sample; MIDAS O, NEPER rotmat:active) and every MRP is the NEML2 MRP of \(R\); see The rotation convention.

Option

Default

Meaning

VoronoiMeshBuilder(orientation_descriptor=)

"euler-bunge"

Euler convention of the input angles; passed to NEPER as <descriptor>:passive. ":active" Euler or a non-Euler descriptor raises ValueError.

build_voronoi(morphoalgo=) / build_graph(morphoalgo=)

"subplex"

NEPER -morphooptialgo: "subplex" or "lloyd"; NEPER 7 rejects "praxis" (raised as ValueError).

neper_env.ROTMAT_DESCRIPTOR

"rotmat:active"

descriptor graintrace requests for NEPER matrix output (.tess, .ori).

TaylorModel.load_experiment_data(angle_identifier=, angle_convention=, angle_type=)

Eul0..Eul2, "bunge", "auto"

calibration texture from Euler columns (auto: any value beyond \(2\pi\) means degrees); O11..O33 (active \(R\)) only as a fallback.

IPFProcessor.get_ipf_track_points(orientations, direction)

–

variant-consistent IPF points for one track (one sector operator for all steps); used by the IPF tracking plots.

TaylorModel.simulate(..., return_orientation=) / UniaxialTaylorModel.forward(..., return_orientation=)

False

also return per-grain neml2-MRP orientation histories (ntime, n_grains, 3) (appended after stress and the optional elastic strain).

CPFESimulation(slip_systems=) / TaylorModel(slip_systems=)

"fcc" (CPFE) / deck as written (Taylor)

crystal slip baked into the NEML2 deck: a preset ("fcc", "bcc", "bcc_112", "bcc_110_112", "bcc_110_112_123"), a SlipSystems, or explicit cubic (direction, plane) Miller families. Use the same value for calibration and CPFE.

VoronoiMeshBuilder(weighted=) / RegionBaseStitching(tess_weighted=)

False / True

Laguerre tessellation with seed weight GrainRadius**2 (NEPER 7 power weight).

RegionBaseStitching(z_uncertainty=)

None

floor (um) on the grain \(z\) half-extent for region classification; "auto" = half the scan height (FF box-beam \(z\) uncertainty). Ignored with refine_extents=True.

VoxelMeshBuilder.mesh(quality_check=) / NearFieldMeshBuilder.mesh(quality_check=)

"raise"

SCULPT path: per-hex minimum scaled Jacobian after meshing (<mesh>_quality.json); "raise" on inverted elements, "warn", or "off".

orientation_helper.legacy_mrp_to_mrp(p)

–

converts an MRP written by graintrace 0.2 and earlier (-p).

FrameTransform#

A stated specimen-frame change: x' = Q (s * x) + t, R' = Q R (sample side, on the left of the active orientation matrix), e' = Q e Q^T. graintrace never estimates it.

from graintrace import FrameTransform

frame = FrameTransform(
    rotation=[("z", 172.3), ("x", 180.0), ("y", -0.9)],  # or 3x3 / unit quaternion / rotvec
    axis_sign=(1, 1, -1),        # +-1 per axis, positions only
    translation=(12.0, -3.5, 40.0),
    angle_unit="degrees",        # "degrees" | "radians"
    sequence="extrinsic",        # "extrinsic" | "intrinsic"
)
frame.positions(xyz); frame.euler(eul); frame.mrp(p); frame.tensors(eps)
frame.inverse(); frame_a @ frame_b; frame.to_json(path)

# adapters, each also writes <dst>.transform.json
frame.apply_ff_csv(src, dst)       # coords, Euler, eKen/eFab, O11..O33 (active R)
frame.apply_ee_csv(src, dst)       # headerless x, y, z + 9 strains
frame.apply_pointcloud(src, dst)
frame.apply_voxel_grid(src, dst)

# points (target frame) on a source-frame voxel solid, e.g. for in_overlap masks
from graintrace.frame_transform import voxel_solid_from_grid
solid, origin, spacing = voxel_solid_from_grid("merged_segmented_fixed_grid.npy")
mask = frame.inside_voxel_solid(points, solid, origin, spacing, margin_vox=1)

rotation must be proper; non-orthogonal matrices and non-unit quaternions raise. There is no scale term.

WeightConfig#

Controls edge weighting for graph clustering.

from graintrace.user_data_class import WeightConfig

weight_cfg = WeightConfig(
    mode="rbf",           # "rbf" | "inverse"
    power=2.0,
    sigma=None,           # if None, use sigma_auto
    sigma_auto={"quantile": 0.5},
)

CPFE parameters#

set_parameters() takes named groups. The main groups and common keys:

material: slip_constant_strength, voce_hardening_initial_slope, voce_hardening_saturation, power_slip_n, power_slip_g0, elastic_E, elastic_nu, elastic_G, burger_scale.

simulation_parameters: dt, total_time, initialize_time (load ramps from initialize_time to total_time), device ("cpu", "cuda:N", or a space-separated list), device_batch (per-device NEML2 chunk), sync_times (space-separated grid-output times). Output-frequency knobs:

Knob

Values

grid_transfer

"final" (default) | "per_step" | "off" (regular-grid MultiApp transfer)

exodus_output

"sync" (default, only at sync_times) | "per_step"

mesh_csv

"sync" (default) | "per_step" | "off" (per-element CSV on the true mesh)

distributed_mesh

False (default, replicated) | True — pre-split the mesh to ncore and run --use-split (distributed mesh; low per-rank memory for large meshes; requires ncore >= 2)

solver_route

"timestep_optimized" (default) | "hpc_memory" — swaps the linear solver / Executioner deck

growth_factor

2.0 (default, legacy) — IterationAdaptiveDT dt multiplier after an easy step, >= 1 in both decks. Lower (e.g. 1.5) gives fewer overshoot/cutback cycles around yield, at the cost of more time steps

The defaults are the cheap settings; the per-step grid transfer dominates wall time. Three sources of REI field data are described in Rare-event identification (REI).

The per-element mesh_out CSVs also carry a block_id column (the element subdomain id == grain id). It lets post-processing select all elements of a grain without the mesh file &mdash; e.g. intragranular reorientation / fragmentation via graintrace.ipf_orientation_tracking.OrientationTracker.simulation_element_tracks() (see Reorientation and fragmentation).

Fragmentation & reorientation analysis#

Reorientation-driven REI and grain fragmentation (see Reorientation and fragmentation) add these options:

Reorientation REI (graintrace.fragmentation.FragmentationAnalyzer.write_reorientation_field()): step and ref_step (field-step indices; ref_step defaults to the first field step), symmetry (default "432"), and extra_cols (feature columns to carry through for a combined criterion). The rare-event scalar is compared with the new abs_scalar_diff() metric (exactly one feature column).

Orientation segmentation (graintrace.fragmentation.FragmentationAnalyzer.segment()): misori_tol_deg (hard edge cutoff, default 5°), graph_mode ("grid" for voxel grids, "knn" for scattered mesh elements), gamma (fixed Leiden resolution; when None a sweep over gamma_sweep runs and gamma_pick chooses), rbf_sigma_deg (fixed broad RBF sigma, default ≈ half the cutoff — not sigma_auto, which shatters grains), manhattan_radius, reduce_topk, grain_threshold_final (absorb threshold), remerge_miso_deg (adjacency re-merge), gamma_pick, spread_tol_deg, remerge_spread_check, absorb_max_miso_deg, percolation_max_frac (legacy cap, None = off) and verbose. For intragranular sub-grain segmentation use a fixed low gamma (~0.25 for the shipped CPFE data; gamma=0.1 under-splits). grain_fragments() uses gamma=0.25 by default.

For intragranular sub-grain segmentation, grain_fragments() adds min_subgrain_miso_deg (default 1°) — a minimum sub-grain misorientation applied after Leiden: fragments whose symmetry-aware mean orientations are closer than this are merged agglomeratively (closest-pair first, means recomputed each step, so no single-linkage chaining), via merge_fragments_by_misorientation(). gamma sets the raw resolution; min_subgrain_miso_deg sets the physical threshold so a smooth intragranular gradient is not chopped into near-identical fragments (0 disables it). The fragment means (and the branching-IPF fork endpoints) use mean_orientation_mrp(), a symmetry-aware quaternion mean: pass symmetry (e.g. "432") so a set whose members are reported in different symmetry variants still averages correctly (the default "1" is the plain mean).

Split detection (graintrace.fragmentation.FragmentationAnalyzer.detect_splits()): d_tol (cross-step centroid distance, at grain scale), theta_tol_deg (cross-step misorientation link, generous ~15°), top_k, and an optional adjacency_b to reject a spurious split child. adjacency_b only prunes a multi-child candidate set that has a mutually adjacent pair; when no two candidates are adjacent there is no split to reject, so the best candidate is kept and the parent still matches. The same detector serves FF, NF, and EBSD; NF/EBSD reach it through segment + graintrace.fragmentation.FragmentationAnalyzer.seg_to_grain_table().

d_tol_mode sizes the distance gate; the radius modes read radius_col (default GrainRadius) from both tables:

d_tol_mode

Link when

Use it for

"absolute"

\(d \le d_{tol}\)

Default; comparable grain sizes.

"radius"

\(d \le \max(d_{tol},\ \alpha_a R_a,\ \alpha_b R_b)\)

Mixed sizes, e.g. sub-grains inside a coarse parent.

"radius_sum"

\(d \le \alpha (R_a + R_b)\)

“The two grains touch” (alpha near 1).

top_k applies only to "absolute"; the radius modes use a ball query that covers the gate. assignment="one_to_one" adds strict Hungarian pairs (one_to_one). recall gives each side’s linked fraction, volume-weighted when volume_col exists and limited to in_overlap_a/in_overlap_b. n_null (with seed) counts links under random B orientations; compare null["mean_links"] with null["observed_links"].

Annotated Exodus (add_element_field_to_exodus() and add_element_rgb_to_exodus()): write a per-element (not block-constant) field into an Exodus copy, mapping values to elements by a centroid KD-tree. The first writes a float scalar (encode the "{grain}.{k}" fragment_label as a float); the second writes an RGB triple (rgb_x/rgb_y/rgb_z) so ParaView can show the fragments in the same colors as the branching-IPF figure (map the 3-component array to color with scalar mapping off). Pass one color per element from the shared fragment palette; for a consistent result annotate the Exodus of the analyzed mesh (a co-registered loaded run’s sim_output.e/mesh.e), not a bare mesh of a different microstructure.

IPF trajectory plot styling (plot_ipf_orientation_tracking() and plot_ipf_fragmentation_tracking()): both take a shared ax (returning it instead of saving, for a side-by-side 1x2 figure) and the styling knobs arrow_color (single color, a per-entity sequence, or the sentinel "ipf_final" — tint each track/fork by the IPF color of its final-stage orientation, which reads as “where it ended up” and needs no legend), start_color (start-dot color; None = the initial-orientation IPF color, or e.g. "black" for a neutral origin), line_style / child_line_styles + parent_line_style (per-track / per-child linestyles), child_colors + parent_color (per-child colors and the parent color on the fragmentation plot, so a grain’s sub-grains can be given contrasting categorical colors), line_width, start_size, step_size, arrow_scale (arrowhead size), show_arrow (False draws headless lines to declutter a crowded panel), and label_fontsize. The signature 1x2 figure links its panels on two channels keyed to a per-grain fragment index: a dark categorical color (a grain’s sub-grains contrast; grains told apart by IPF position) and a shared fragment -> line-style map, with black start dots and a gray parent trajectory.

The solver_route selects one of two Executioner decks merged into the run. "timestep_optimized" (default) uses a direct LU factorization (superlu_dist) with preconditioner reuse — robust and iteration-cheap, but the factorization fill-in makes it memory-bound on large meshes; best for small/medium problems. "hpc_memory" uses an iterative fgmres solve preconditioned by GAMG algebraic multigrid — no global factorization, so the memory footprint stays low and scales across ranks; it is the recommended partner of distributed_mesh=True for large HPC meshes, at the cost of looser and more numerous linear iterations. Both decks keep residual_and_jacobian_together = false (required by the nodal-constraint loading BC; MOOSE issue 33531).

Set distributed_mesh=True for large meshes that exhaust memory as a replicated mesh: it pre-splits the mesh once (--split-mesh ncore) and runs --use-split so each rank reads only its partition. It is pre-split only (no in-situ option), requires ncore >= 2, and needs a puma-opt build with the EqualValueBoundaryConstraint distributed-mesh fix. Outputs are unchanged (a single sim_output.e via gather, plus complete mesh_out/ and grid_out/ CSVs).

Running on HPC#

For a cluster run, combine the memory-lean solver with the scheduler launcher, and add the distributed mesh only when the replicated mesh no longer fits:

sim.set_parameters(
    "simulation_parameters",
    solver_route="hpc_memory",   # iterative fgmres + GAMG (low, scalable memory)
    launcher="srun",             # Slurm/Cray; default "mpiexec" elsewhere
    distributed_mesh=True,       # large meshes only (~1M+ elements); needs ncore >= 2
    device="cuda:0 cuda:1 cuda:2 cuda:3",  # GPU: a cuda list, one entry per GPU on the node
    device_batch=20000,          # finite chunk caps per-GPU memory (0 risks OOM)
)
sim.run(ncore=4)                 # GPU: ncore == number of GPUs in the device list
  • GPU node: device is a space-separated cuda list and ncore equals the number of GPUs; fewer, larger ranks give better GPU utilisation for the NEML2-dominated solve. Keep device_batch finite to bound per-GPU memory.

  • CPU node: set device="cpu" and ncore to the number of MPI ranks (srun -n); distributed_mesh=True is what keeps per-rank memory bounded as the mesh grows.

  • solver_route="hpc_memory" and distributed_mesh=True are independent levers but pair naturally: GAMG avoids the LU factorisation blow-up, the distributed mesh avoids holding the full mesh per rank. Enable distributed_mesh only for meshes that OOM as replicated (it needs the EVBC-fixed puma-opt); hpc_memory is safe to use at any size.

boundary: bounding_box and the bc dict (above).

grid_properties: number_of_elements and bounding_box. The grid box should be inset by a small amount on each face to avoid mesh-boundary issues:

grid_bb = bounding_box.copy()
for i in range(0, 6, 2):   # xlo, ylo, zlo
    grid_bb[i] += 0.0001
for i in range(1, 6, 2):   # xhi, yhi, zhi
    grid_bb[i] -= 0.0001

External-tool paths (tools.json)#

External tool locations can be supplied via a JSON file instead of environment variables. The template is graintrace/mcp/tools.example.json with keys puma_opt, neper, and a sculpt_config block. Search order: $GRAINTRACE_TOOLS_JSON → ./graintrace_tools.json → ~/.config/graintrace/tools.json.