graintrace.nf#

NF (near-field) HEDM voxel grid processing subpackage.

NF point-cloud to fixed-grid conversion and VTK export helpers.

graintrace.nf.convert.layer_number(path, token='layer')[source]#

Extract the layer index that follows token in a filename.

Raises:

ValueError if no layer number can be found. –

Parameters:
Return type:

int

graintrace.nf.convert.nf_to_pointcloud(folder, dz, layer_token='layer', recursive=False)[source]#

Stack nearfield .mic/.csv layers into one point cloud.

Layers sort by the number after layer_token and must be contiguous. With recursive=False an empty folder still falls back to its subfolders.

Parameters:
  • folder (str) – folder with nearfield data

  • dz (float) – spacing between layers in the z-direction

  • layer_token (str) – filename token that precedes the layer number

  • recursive (bool) – search subfolders (MIDAS Layer1/...layer1.mic)

Returns:

every layer column (incl. Confidence) plus Z and layer.

Return type:

pd.DataFrame

Raises:
graintrace.nf.convert.nearest_simplex_vertex(tri, query_points, simplex_indices)[source]#

Index of the nearest vertex of each query point’s containing simplex.

The legacy source-point rule, kept so an unmasked grid is unchanged; it can differ from the globally nearest measured point.

Parameters:
  • tri (scipy.spatial.Delaunay) – triangulation of the measured points

  • query_points (np.ndarray) – (m, 2) points, all inside the hull

  • simplex_indices (np.ndarray) – (m,) containing simplex of each point

Returns:

(m,) indices into the triangulation’s points

Return type:

np.ndarray

graintrace.nf.convert.process_layer_pointcloud(df_layer, plane_points, nx, ny, min_confidence=None, max_point_distance=None)[source]#

Interpolate one point-cloud layer onto a fixed nx x ny grid.

Solid points are those within max_point_distance of a measured point, else inside the Delaunay hull; points whose source is below min_confidence are void.

Parameters:
  • df_layer (pd.DataFrame) – one layer: X, Y, Z, Eul1..3 and optionally Confidence

  • plane_points (np.ndarray) – (nx*ny, 2) in-plane grid coordinates

  • nx (int) – in-plane grid resolution

  • ny (int) – in-plane grid resolution

  • min_confidence (float, optional) – confidence threshold; None keeps all

  • max_point_distance (float, optional) – solid radius (um); None uses the hull

Returns:

(nx x ny x 7 grid [phase, Eul1, Eul2, Eul3, X, Y, Z], nx x ny confidence, 0 where void)

Return type:

tuple

graintrace.nf.convert.grid_axis(lo, hi, n=None, spacing=None)[source]#

Build one grid axis from a point count or a spacing.

Parameters:
  • lo (float) – axis extent of the data

  • hi (float) – axis extent of the data

  • n (int, optional) – number of points spread over [lo, hi]

  • spacing (float, optional) – spacing (um); starts at lo and covers hi

Returns:

the axis coordinates

Return type:

np.ndarray

Raises:

ValueError – unless exactly one positive n or spacing is given.

graintrace.nf.convert.pointcloud_to_fixed_grid(pointcloud, nx=None, ny=None, voxel_size_um=None, min_confidence=None, max_point_distance=None)[source]#

Convert a point cloud to an nx x ny x nz x 7 fixed grid.

Parameters:
Returns:

(nx x ny x nz x 7 grid, nx x ny x nz confidence, 0 where void)

Return type:

tuple

Raises:

ValueError – if voxel_size_um is combined with nx/ny, neither is given, or it is not a pair.

graintrace.nf.convert.fixed_grid_to_vtk(fixed_grid, filename, varlabels=['phase', 'Eul1', 'Eul2', 'Eul3', 'X', 'Y', 'Z'])[source]#

Save an nx x ny x nz x 7 fixed grid to a structured-grid VTK file.

Parameters:
  • fixed_grid (np.ndarray) – grid [phase, Eul1, Eul2, Eul3, X, Y, Z]

  • filename (str) – output VTK filename

  • varlabels (list) – labels for the 7 columns

Flood-fill grain segmentation and cleanup for NF voxel grids.

graintrace.nf.segment.flood(angles, phase, misorientation_tol, connectivity=26, batch_norm=10000000, grain_threshold=100, stop_count=100, **kwargs)[source]#

Flood-fill segmentation of connected components in a 3D voxel grid.

Parameters:
  • angles (nx,ny,nz,3) – Euler angles, interpreted per metrics.misorientation kwargs

  • phase (nx,ny,nz) – phase identifiers per voxel (>0 material, 0 void)

  • misorientation_tol (float) – misorientation tolerance for connectivity

  • connectivity (int) – 6 or 26

  • batch_norm (int) – batch size for distance calculation

  • grain_threshold (int) – minimum segment size to keep

  • stop_count (int) – stop after discarding this many small segments; must be >= 1

  • **kwargs – extra arguments for metrics.misorientation()

Returns:

(nx,ny,nz) array of segmented phases

Raises:

ValueError – if stop_count is less than 1

graintrace.nf.segment.infill_nearest_neighbor(grid, connectivity=6)[source]#

Infill unmarked voxels (phase == -1) from nearest filled neighbors.

Parameters:
  • grid (nx,ny,nz,7) – fixed grid, grid[…,0] is the phase index

  • connectivity (int) – 6 or 26

Returns:

(nx,ny,nz,7) tensor with all phase == -1 voxels filled

graintrace.nf.segment.void_unsegmented(grid)[source]#

Set every voxel still unsegmented (phase < 0) to void.

Run after the final cleanup: an island with no solid neighbour survives both infill and small-segment removal at -1, which write_spn rejects.

Parameters:

grid (nx,ny,nz,7) – fixed grid, grid[…,0] is the phase index

Returns:

(nx,ny,nz,7) tensor without negative phases; voided orientations are zeroed

graintrace.nf.segment.remove_small_segments(grid, min_size, connectivity=6)[source]#

Merge segments smaller than min_size into their largest-contact neighbor.

Parameters:
  • grid (nx,ny,nz,7) – fixed grid, grid[…,0] is the phase index

  • min_size (int) – minimum segment size in voxels

  • connectivity (int) – 6 or 26

Returns:

(nx,ny,nz,7) tensor with small segments merged into neighbors

SCULPT hex meshing and orientation mapping for NF voxel grids.

graintrace.nf.mesh.write_spn(data, filename_spn, filename_orientations, angle_convention='bunge', angle_type='radians', symmetry='1')[source]#

Write an spn and per-grain orientation file from fixed grid data.

Parameters:
  • data (np.ndarray) – nx x ny x nz x 7 array [phase, Eul1, Eul2, Eul3, X, Y, Z]

  • filename_spn (str) – output spn filename

  • filename_orientations (str) – output orientations filename

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’

  • angle_type (str) – ‘degrees’ or ‘radians’

  • symmetry (str) – crystal symmetry for the per-grain orientation average (see graintrace.nf.metrics.average_rotations()). Pass the crystal point group (e.g. "432") so voxels of one grain reported in different symmetry variants average correctly.

Raises:

ValueError – if any voxel still carries a negative (“unsegmented”) phase. Such a voxel is not a grain, and mapping it to void here would silently delete material from the mesh, so the caller decides.

graintrace.nf.mesh.VOID_MAT_FLAGS = ('--void_mat', '-VM')#

SCULPT flags that name the void material; mesh_sculpt owns them.

graintrace.nf.mesh.sculpt_void_options(sculpt_options, has_void)[source]#

Return sculpt_options with the void flag this grid needs.

SCULPT ranks spn values 1-based, so with void present the void is material 1. Any --void_mat/-VM is replaced by --void_mat 1 when there is void, and dropped when there is none (there, 1 would delete grain 1); both cases warn on a conflicting value.

Parameters:
  • sculpt_options (sequence of str) – SCULPT CLI flags

  • has_void (bool) – whether the grid has any phase-0 voxel

Returns:

the options to pass to psculpt

Return type:

list of str

graintrace.nf.mesh.mesh_sculpt(sculpt_config, sculpt_options, input_spn, data, output_mesh_filename, output_angle_filename, split_output_prefix='output_mesh', angle_convention='bunge', angle_type='radians', symmetry='1', layer_spacing=None, source_labels=None, block_map_filename=None, quality_check='raise')[source]#

Call sculpt (+epu) to generate an Exodus mesh from an spn file.

Sets --void_mat (sculpt_void_options()), maps SCULPT’s index coordinates to physical ones (rescale_exodus_mesh()), renumbers blocks to 1..N (renumber_blocks_contiguous()) and writes one orientation row per block.

Parameters:
  • sculpt_config (dict) – configuration for the sculpt call

  • sculpt_options (list) – extra command line options for sculpt

  • input_spn (str) – path to input spn file

  • data (np.ndarray) – nx x ny x nz x 7 array [phase, Eul1, Eul2, Eul3, X, Y, Z]

  • output_mesh_filename (str) – path to output exodus mesh file

  • output_angle_filename (str) – path to output orientations file

  • split_output_prefix (str) – prefix for temporary output files

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’

  • angle_type (str) – ‘degrees’ or ‘radians’

  • symmetry (str) – crystal symmetry for the per-block orientation average

  • layer_spacing (float, optional) – z voxel size of a single-layer grid

  • source_labels (array, optional) – pre-write_spn grain ids for the block map

  • block_map_filename (str, optional) – defaults to <mesh stem>_block_map.csv

  • quality_check (str) – after meshing, compute every hex’s minimum corner scaled Jacobian (check_mesh_quality(), report in <mesh stem>_quality.json). "raise" (default) raises RuntimeError if any element is inverted (scaled Jacobian <= 0), which would abort a CPFE solve; "warn" only warns; "off" skips the check.

Returns:

path to the block map CSV.

Return type:

str

graintrace.nf.mesh.hex_scaled_jacobian(exo_file)[source]#

Minimum corner scaled Jacobian of every 8-node hex in an Exodus mesh.

At each corner the three edge vectors e1, e2, e3 give (e1 x e2) . e3 / (|e1| |e2| |e3|); the element value is the minimum over its corners (1 for a perfect cube, <= 0 for an inverted element). Non-HEX8 blocks are skipped.

Parameters:

exo_file (str) – path to the Exodus mesh.

Returns:

one value per HEX8 element, in block order.

Return type:

numpy.ndarray

graintrace.nf.mesh.check_mesh_quality(exo_file, on_inverted='raise', report_path=None)[source]#

Scaled-Jacobian report for a hex mesh; act on inverted elements.

Writes {n_elements, min, p01, mean, n_inverted, n_below_0.2} as JSON to report_path (default <mesh stem>_quality.json) and prints a summary.

Parameters:
  • exo_file (str) – path to the Exodus mesh.

  • on_inverted (str) – "raise" (RuntimeError) or "warn" when any element has scaled Jacobian <= 0.

  • report_path (str, optional) – JSON report path.

Returns:

the report.

Return type:

dict

graintrace.nf.mesh.voxel_spacing(data, layer_spacing=None)[source]#

Per-axis voxel size of a fixed grid from its voxel-centre coordinates.

A single-voxel axis takes layer_spacing (z only), else the mean in-plane spacing, else 1.0.

Parameters:
  • data (np.ndarray) – nx x ny x nz x 7 fixed grid

  • layer_spacing (float, optional) – known z voxel size

Returns:

(3,) spacing (hx, hy, hz).

Return type:

np.ndarray

graintrace.nf.mesh.voxel_edge_bounds(data, layer_spacing=None)[source]#

Voxel-edge bounding box [min - h/2, max + h/2] of a fixed grid.

Parameters:
  • data (np.ndarray) – nx x ny x nz x 7 fixed grid

  • layer_spacing (float, optional) – see voxel_spacing()

Returns:

(lo, hi), each a (3,) array.

Return type:

tuple

graintrace.nf.mesh.rescale_exodus_mesh(exo_file, data, layer_spacing=None)[source]#

Map SCULPT’s voxel-index coordinates onto physical coordinates.

SCULPT writes index units with 0 at the first voxel edge, so the map is the exact affine x = (c0 - h/2) + raw * h; the mesh min/max are not used.

Parameters:
  • exo_file (str) – path to Exodus mesh file

  • data (np.ndarray) – nx x ny x nz x 7 fixed grid the mesh came from

  • layer_spacing (float, optional) – see voxel_spacing()

graintrace.nf.mesh.renumber_blocks_contiguous(exo_file, data, block_map_filename, source_labels=None, background_id=0)[source]#

Renumber Exodus block ids to 1..N in file order and write a block map.

Each block’s grain is the majority grid label (void included) under its element centroids. The CSV has block_id, sculpt_block_id, grain_id, n_elem and, given source_labels, source_grain_id. Names ending in the old id follow it.

Parameters:
  • exo_file (str) – Exodus mesh, modified in place

  • data (np.ndarray) – nx x ny x nz x 7 fixed grid the mesh came from

  • block_map_filename (str) – output block map CSV

  • source_labels (array, optional) – (nx, ny, nz) ids to report per block

  • background_id (int) – grid id treated as void

Returns:

block_grains (grain per block), renumbered and block_map.

Return type:

dict

Raises:

ValueError – if the grid has no solid voxel, or a block is mostly void (the void was meshed).

graintrace.nf.mesh.map_orientations(exo_file, data, output_angle_filename, angle_convention='bunge', angle_type='radians', symmetry='1', background_id=0, block_grains=None)[source]#

Map orientations from fixed grid data onto an Exodus mesh’s blocks.

Each block is one grain, looked up against that grain’s own voxels only (void and neighbouring grains excluded). One row per block in file order. Blocks map to grains by block_grains, else eb_prop1 when those are grid ids, else positionally when the counts match.

Parameters:
  • exo_file (str) – path to Exodus mesh file

  • data (np.ndarray) – nx x ny x nz x 7 array [phase, Eul1, Eul2, Eul3, X, Y, Z]

  • output_angle_filename (str) – path to output orientations file

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’

  • angle_type (str) – ‘degrees’ or ‘radians’

  • symmetry (str) – crystal symmetry for the per-block orientation average (see graintrace.nf.metrics.average_rotations()).

  • background_id (int) – grid id treated as void and excluded from the lookup. Default 0.

  • block_grains (array, optional) – grid grain id of each block, in file order

Raises:

ValueError – if the grid has no non-void voxels, or the Exodus blocks cannot be associated with the grid’s grains.

graintrace.nf.mesh.write_voxel_exodus(data, output_mesh_filename, output_angle_filename, angle_convention='bunge', angle_type='radians', background_id=0, symmetry='1', layer_spacing=None)[source]#

Dump a segmented voxel grid directly to an Exodus hex mesh (no SCULPT).

Emits one axis-aligned cube HEX8 per non-background voxel, with nodes shared between adjacent voxels (conformal, including across grain boundaries). Because every element is a perfect cube its scaled Jacobian is exactly 1, so the mesh has no inverted/sliver elements – at the cost of stair-stepped grain boundaries and one hex per filled voxel. This is the robust alternative to mesh_sculpt when conformal smoothing produces bad elements.

Parameters:
  • data – (nx, ny, nz, 7) array [grain_id, Eul1, Eul2, Eul3, X, Y, Z] (torch or numpy); coordinates are voxel centers.

  • output_mesh_filename (str) – output Exodus (.e) path. One element block per grain, block ids relabeled to a contiguous 1..N (matching MOOSE/PUMA).

  • output_angle_filename (str) – orientation output stem; the per-block MRP file is written to output_angle_filename + ".csv" (one row per block, same order/convention as map_orientations).

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’.

  • angle_type (str) – ‘degrees’ or ‘radians’.

  • background_id (int) – voxel id treated as void (skipped). Default 0. Voxels with a negative (“unsegmented”) id are skipped as well, so an orphan left by remove_small_segments does not become a block of its own and shift every grain id.

  • symmetry (str) – crystal symmetry for the per-block orientation average (see graintrace.nf.metrics.average_rotations()).

  • layer_spacing (float, optional) – z voxel size of a single-layer grid (voxel_spacing()); the mesh spans the voxel-edge box.

Returns:

{‘nodes’, ‘elements’, ‘blocks’} counts.

Return type:

dict

Orientation-field smoothing for NF voxel grids.

graintrace.nf.smooth.smooth(data, connectivity=6, symmetry='1', angle_convention='bunge', angle_type='radians')[source]#

Smooth voxel orientations via a neighbor quaternion mean.

Parameters:
  • data (nx,ny,nz,7) – fixed grid [phase, Eul1, Eul2, Eul3, X, Y, Z]

  • connectivity (int) – 6 or 26

  • symmetry (str) – crystal symmetry in orbifold notation

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’

  • angle_type (str) – ‘degrees’ or ‘radians’

Voxel connectivity helpers for NF grid images.

graintrace.nf.image.get_neighbor_indices(offsets, shape)[source]#

Compute neighbor indices for every voxel given a set of offsets.

Parameters:
  • offsets – (n_offsets, 3) tensor of (dx, dy, dz)

  • shape – (nx, ny, nz) tuple

Returns:

(n_offsets, nx, ny, nz) clamped neighbor indices valid: (n_offsets, nx, ny, nz) mask of in-bounds neighbors

Return type:

Xk, Yk, Zk

Orientation averaging and misorientation metrics for NF grids.

graintrace.nf.metrics.fold_to_reference_variant(R, symmetry)[source]#

Fold rotations onto the symmetry variant closest to the first of the set.

A crystal orientation has one rotation matrix per symmetry operator (24 for cubic 432), and a reconstruction may report neighbouring voxels of one grain in different variants. Averaging across variants is meaningless, so every member is first replaced by the symmetry-equivalent R S (crystal symmetry on the right) that is closest (largest Frobenius inner product) to the reference member R[..., 0, :, :].

Parameters:
  • R – (..., N, 3, 3) active rotation matrices; the set is averaged over axis -3.

  • symmetry (str) – crystal symmetry in orbifold notation; "1" disables folding and returns R unchanged.

Returns:

(..., N, 3, 3) rotation matrices, all in a common symmetry variant.

graintrace.nf.metrics.average_rotations(e, angle_convention='kocks', angle_type='radians', symmetry='1')[source]#

Average a set of Euler angles via quaternion (eigenvector) mean.

Parameters:
  • e – Nx…x3 array of Euler angles

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’

  • angle_type (str) – ‘degrees’ or ‘radians’

  • symmetry (str) – crystal symmetry in orbifold notation (e.g. "432"). Members are folded into a common symmetry variant before averaging, so a grain whose voxels are reported in different variants still yields the correct mean. "1" (the default) disables folding and gives the plain quaternion eigenvector (Markley) mean.

Returns:

averaged orientation as a neml2 v3 MRP (…, 3) of the active R and as Euler angles (…, 3) in the given convention.

Return type:

tuple (mrp, euler)

graintrace.nf.metrics.batched_norm(v1, v2, norm, chunk_size, **kwargs)[source]#

Compute norm(v1, v2) in chunks of chunk_size to save memory.

graintrace.nf.metrics.misorientation(e1, e2, angle_convention='kocks', angle_type='degrees', symmetry='1')[source]#

Compute misorientation angles between two sets of Euler angles.

Parameters:
  • e1 – Nx3 arrays of Euler angles

  • e2 – Nx3 arrays of Euler angles

  • angle_convention (str) – ‘kocks’, ‘bunge’, or ‘roe’

  • angle_type (str) – ‘degrees’ or ‘radians’

  • symmetry (str) – crystal symmetry in orbifold notation

Returns:

Nx1 array of misorientation angles in degrees