Volumetric Mesh Tools

Tetrahedral meshes filling each label of a labelmap, their relaxation onto a surface, and the repair of inverted elements.

Overview

ProcessVolumetricMesh offers three meshers that fill each label of a labelmap with its own tetrahedral mesh; each method’s suffix names the mesher it uses (_vtk, _netgen, _simpleware). Like ProcessSurfaceMesh.extract_label_surfaces(), all three take the labelmap, an optional element_size_mm and optional label_ids, and return {label id: pv.UnstructuredGrid} - positively oriented TETRA cells in the labelmap’s world frame, each grid tagged with field_data['SegmentationLabelIds'] - or {} for an empty labelmap, so switching meshers is a one-word change. A binary mask yields a single mesh, under its foreground value. Neighboring labels’ meshes meet on coincident nodes along their shared walls (each mesh holds its own copy of them). The netgen and Simpleware meshers also take smoothing_sigma_mm, the blur that sets how smooth their boundaries are, with the same default; the VTK mesher’s boundaries come from the surfaces they are trimmed to instead. Tutorial 1’s tetmesh variant (tutorials/tutorial_01_convert_to_usd_tetmesh_slicer_heart_4d_ct.py) builds, warps, and saves all three side by side, with one USD prim per label.

extract_label_tetrahedra_vtk()

extract_label_tetrahedra_netgen()

extract_label_tetrahedra_simpleware()

Method

Every voxel becomes a hexahedron that VTK splits into six tetrahedra

netgen fills each label’s smooth surface from ProcessSurfaceMesh.extract_label_surfaces()

Synopsys Simpleware Medical +FE Free meshes each label’s mask

Boundary

Voxel staircase; relax it with trim_tetrahedra_to_surface()

Smooth, as given

Smooth: each mask is Gaussian-blurred in Simpleware before meshing

Elements

Uniform, structured

Unstructured, graded

Unstructured, graded

Requirements

GPU (when resampling)

GPU, the netgen extra

A licensed Simpleware Medical install with +FE Free

Use when

Element-for-element correspondence across subjects matters, as for statistical shape models

An open-source, unstructured mesh is wanted

Simpleware’s mesh quality controls are wanted, or it is already in the pipeline

Labels with stray voxels or enclosed cavities give every mesher extra boundary shells; clean each label’s mask first with ProcessLabelmaps.remove_islands() and ProcessLabelmaps.fill_holes() (netgen in particular fails when such shells crowd the outer surface).

Voxel-based meshes

from monai_physio import ProcessSurfaceMesh, ProcessVolumetricMesh

surfaces = ProcessSurfaceMesh().extract_label_surfaces(labelmap)
volume_tools = ProcessVolumetricMesh()
meshes = volume_tools.extract_label_tetrahedra_vtk(labelmap, element_size_mm=1.5)
meshes = {
    label_id: volume_tools.remove_boundary_slivers(
        volume_tools.trim_tetrahedra_to_surface(mesh, surfaces[label_id])
    )
    for label_id, mesh in meshes.items()
}

Trimming moves each label’s mesh on its own, so the nodes neighboring labels share then match only as closely as their surfaces do.

netgen meshes

Install the optional extra first (source installs through dev already include it):

pip install "monai-physio[netgen]"
meshes = ProcessVolumetricMesh().extract_label_tetrahedra_netgen(
    labelmap, element_size_mm=2.0
)

element_size_mm sets both the grid the surface is contoured on and netgen’s maximum interior element size. The contour’s smoothing grows with it, so coarse sizes shrink thin structures: on the 1.5 mm heart test labels a 3 mm size loses about 5% of the voxel volume, the mask’s own spacing about 1%. None contours at the labelmap’s finest spacing and lets netgen grade the interior from the surface.

shared_interfaces picks how the surfaces reach netgen, as for Simpleware. True (default) hands netgen the contoured surfaces as they are: they are triangulated identically where labels meet and netgen keeps a boundary’s triangles, so neighboring labels’ meshes share those nodes. False has netgen re-tile each label’s surface on its own, to triangles about element_size_mm across, before filling it; the meshes are then independent and may overlap or gap slightly where labels meet. netgen’s re-tiling ends its whole process on a surface that intersects itself, so it runs in a child Python process and such a failure is raised as a RuntimeError.

contour_spacing_mm sets the grid the surfaces are contoured on, which otherwise is element_size_mm. Where a label’s voxels are finer than that grid, its surface carries steps of the grid’s size, so a finer grid gives smaller steps. With shared interfaces netgen keeps every contoured triangle: on the full Slicer heart labelmap at 2 mm elements, a 1 mm grid grows the meshes from about 420,000 to 1,750,000 cells. Without shared interfaces the re-tiling brings the triangles back to the element size, about 760,000 cells from a 1 mm grid.

# Smaller steps, shared interface nodes, four times the cells.
meshes = ProcessVolumetricMesh().extract_label_tetrahedra_netgen(
    labelmap, element_size_mm=2.0, contour_spacing_mm=1.0
)
# Smaller steps at about the element size, independent meshes.
meshes = ProcessVolumetricMesh().extract_label_tetrahedra_netgen(
    labelmap, element_size_mm=2.0, contour_spacing_mm=1.0,
    shared_interfaces=False,
)

element_size_image gives netgen finer elements where they are needed: an image of target edge lengths in mm, in the labelmap’s world frame but on any grid. Each voxel whose size is below element_size_mm restricts netgen’s local size at its centre, and netgen grades the elements back up to element_size_mm over the next few elements; infinite voxels leave the size alone. create_element_size_image() builds such an image from a labelmap and a size per label, so any region that can be labelled - an organ of interest, a lesion, a zone around the openings of a vessel - can be refined. Without shared interfaces the re-tiled surface is refined too; with them the contoured surface is kept, so only the interior is refined and a finer contour_spacing_mm is what refines the boundary.

from monai_physio import ProcessMeshKernels, ProcessVolumetricMesh

volume_tools = ProcessVolumetricMesh()
# 0.5 mm elements in label 3 (say, a tumour), 2 mm elsewhere.  The size
# image is labelled on a 0.5 mm grid, not the scan's finer one.
zones = ProcessMeshKernels().vote_resample_labelmap(labelmap, 0.5)
sizes = volume_tools.create_element_size_image(zones, {3: 0.5})
meshes = volume_tools.extract_label_tetrahedra_netgen(
    labelmap, element_size_mm=2.0, element_size_image=sizes,
    shared_interfaces=False,
)

Each restricting voxel is one point handed to netgen, so give the size image a spacing near the sizes it holds rather than the labelmap’s finest, as above; a whole organ at a CT’s 0.6 mm spacing would be millions. The 3D rigid blood-flow experiment (experiments/BloodFlow-3D-Rigid-Warp/prepare.py) refines a ball around each narrow vessel opening this way, so that every outlet is tiled finely enough to carry flow.

smoothing_sigma_mm is passed to ProcessSurfaceMesh.extract_label_surfaces() as distance_sigma_mm: None (default) blurs the distance map by the contour grid spacing and 0 turns the blur off. The surface is resampled and Taubin-smoothed either way, so the blur mostly trades volume for smoothness: on the 1.5 mm heart test label at 3 mm elements, no blur keeps 97% of the voxel volume, the default 95%, and 6 mm 91%.

smoothing_iterations (default 30) is the surfaces’ Taubin smoothing. The labels’ surfaces are smoothed together, which can pinch a thin wall between two labels - such as the heart wall between the contrast-filled blood pool and the background - until a surface touches itself, and netgen rejects such a surface. 0 avoids that, but leaves irregular triangles (roughness about 0.34 against 0.08 on the Slicer heart labelmap at 2 mm) and, with them, thousands of sliver elements that a warp inverts beyond repair. Fewer iterations without the blur balance the two: with smoothing_iterations=10 and smoothing_sigma_mm=0 the full Slicer heart labelmap’s shared 2 mm surfaces leave no element below a scaled Jacobian of 0.08 once remove_boundary_slivers() has run. Tutorial 1’s tetmesh variant adds contour_spacing_mm=1.0 and shared_interfaces=False (below) for smaller voxel steps: about 760,000 cells, whose 21 warped phases needed one inverted element repaired.

Simpleware meshes

volume_tools = ProcessVolumetricMesh()
# Only needed when Simpleware is not at the default install path.
volume_tools.set_simpleware_executable_path(
    "C:/Program Files/Synopsys/Simpleware Medical/Y-2026.03/"
    "ConsoleSimplewareMedical.exe"
)
meshes = volume_tools.extract_label_tetrahedra_simpleware(
    labelmap, element_size_mm=2.0
)

The labelmap is cropped, padded clear of its blur, and handed to ConsoleSimplewareMedical.exe in one run, which executes simpleware_medical/SimplewareScript_tetrahedral_mesh.py: each label becomes a mask blurred with Simpleware’s recursive Gaussian filter, the masks become +FE Free model parts, element_size_mm becomes the maximum edge length (with half of it as the target minimum; None keeps Simpleware’s default sizes), and the linear tetrahedra are exported as VTK volumes. shared_interfaces picks the model layout: True (default) meshes every label as a part of one model, so neighboring labels’ meshes share their interface nodes, and Simpleware’s part priority settles where blurred masks overlap; False meshes each label in a model of its own, so the meshes are independent and may overlap or gap slightly where labels meet. Simpleware receives the labelmap with an identity direction and a zero origin, and its points are mapped back through the labelmap’s own origin and direction, so the result does not depend on how Simpleware reads image orientation. timeout_s (default 600) bounds the external process.

The blur is what keeps the voxel staircase out of the meshes: a 0/1 mask holds no sub-voxel boundary position, and +FE Free meshes it as given. smoothing_sigma_mm sets its standard deviation; None (default) uses element_size_mm, or the labelmap’s finest spacing when that is None too - the same blur netgen’s surfaces get - and 0 turns it off. On the 1.5 mm Slicer heart mask at 2 mm elements:

smoothing_sigma_mm

Boundary roughness

Mean distance to the smooth surface

Volume vs. voxels

0 (staircase)

0.129

1.50 mm

0.993

1.5

0.097

0.24 mm

0.982

3.0

0.079

0.31 mm

0.960

netgen, for comparison

0.069

0.22 mm

0.973

Roughness is a boundary point’s mean offset from its neighbors’ centroid, per mean edge length. Larger blurs smooth further but thin small structures.

Simpleware’s own smart mask smoothing (Model.SetUseSmartMaskSmoothing) did less: 10 iterations reached a roughness of 0.112.

Mesh quality and repair

remove_boundary_slivers() drops flat boundary caps before a mesh is warped, and repair_inverted_tetrahedra() relaxes the nodes of elements a warp has inverted. Both work on meshes from any of the three meshers.

Module Reference

Tools for creating and relaxing tetrahedral (volumetric) meshes.

This module provides the ProcessVolumetricMesh class: one tetrahedral mesh per label of a labelmap (voxel-based, netgen, or Simpleware Medical), their relaxation onto a smooth surface, and the repair of inverted elements. Surfaces come from ProcessSurfaceMesh; the GPU primitives live in ProcessMeshKernels.

class monai_physio.process_volumetric_mesh.ProcessVolumetricMesh(log_level=20)[source]

Tools for creating and relaxing tetrahedral meshes.

Example

>>> surfaces = ProcessSurfaceMesh().extract_label_surfaces(labelmap)
>>> volume_tools = ProcessVolumetricMesh()
>>> meshes = volume_tools.extract_label_tetrahedra_vtk(labelmap, 1.5)
>>> meshes = {
...     label_id: volume_tools.trim_tetrahedra_to_surface(
...         mesh, surfaces[label_id]
...     )
...     for label_id, mesh in meshes.items()
... }
>>> meshes = volume_tools.extract_label_tetrahedra_netgen(labelmap, 1.5)
VOXEL_TO_HEX: ClassVar[list[int]] = [0, 1, 3, 2, 4, 5, 7, 6]
VOXEL_TO_HEX_FLIPPED: ClassVar[list[int]] = [4, 5, 7, 6, 0, 1, 3, 2]
MIN_TRIM_DAMPING = 0.0009765625
NETGEN_GRADING = 0.3
__init__(log_level=20)[source]

Initialize ProcessVolumetricMesh.

Parameters:

log_level (int | str) – Logging level (default: logging.INFO)

set_simpleware_executable_path(path)[source]

Set the path to the Simpleware Medical console executable.

Parameters:

path (str) – Full path to ConsoleSimplewareMedical.exe.

Return type:

None

extract_label_tetrahedra_vtk(labelmap_image, element_size_mm=None, label_ids=None)[source]

Build one tetrahedral mesh filling each label of a labelmap.

Every labeled voxel becomes a hexahedron, which VTK then splits into six tetrahedra sharing the hexahedra’s points, and each label keeps the tetrahedra of its own voxels. The labels are meshed on one grid, so neighboring labels’ meshes have coincident nodes along their shared walls (each mesh holds its own copy of them). Each boundary is the voxel staircase rather than the smooth surface ProcessSurfaceMesh.extract_label_surfaces() returns; pass each mesh through trim_tetrahedra_to_surface() with its label’s surface to relax that staircase onto it. Relaxing moves each mesh on its own, so the shared nodes then match only as closely as the two surfaces do.

Parameters:
  • labelmap_image (image) – Multi-label image; every non-zero label present is meshed. A binary mask yields a single mesh.

  • element_size_mm (Optional[float]) – Edge length of the isotropic voxels the labelmap is resampled to, with a label-aware vote, before meshing, which is the resulting element size. None meshes the labelmap’s own voxels, so on anisotropic data the elements inherit that anisotropy. A size above the thinnest part of a structure drops that part.

  • label_ids (Optional[Sequence[int]]) – Labels to mesh; every other label is treated as background. None meshes every label. To mesh a union of labels as one structure, relabel them to one id first.

Return type:

dict[int, UnstructuredGrid]

Returns:

Label id → that label’s tetrahedral mesh, whose field_data['SegmentationLabelIds'] holds the id. A label that element_size_mm is too coarse to keep is left out, so the mapping is empty when the labelmap holds no non-zero label.

static create_element_size_image(labelmap_image, element_sizes_mm)[source]

Return an image of target element sizes taken from a labelmap.

Each voxel of a label in element_sizes_mm holds that label’s size; every other voxel holds infinity, which leaves the mesher’s own size there. The labels need not be the ones being meshed: label an organ, a region of interest or a zone around a boundary feature, such as a ball around each outlet of a vessel, and pass the result as extract_label_tetrahedra_netgen()’s element_size_image. Each voxel below the mesher’s size becomes one restriction, so label on a grid near the target sizes (for example a labelmap resampled with ProcessMeshKernels.vote_resample_labelmap()), not a fine scan’s.

Parameters:
  • labelmap_image (image) – Labelmap whose labels mark the regions to size.

  • element_sizes_mm (Mapping[int, float]) – Label id → target edge length in that label.

Return type:

image

Returns:

A float image on labelmap_image’s grid.

extract_label_tetrahedra_netgen(labelmap_image, element_size_mm=None, smoothing_sigma_mm=None, label_ids=None, smoothing_iterations=30, shared_interfaces=True, contour_spacing_mm=None, element_size_image=None)[source]

Build one unstructured tetrahedral mesh filling each label with netgen.

The labels’ smooth surfaces from ProcessSurfaceMesh.extract_label_surfaces() are handed to netgen one at a time as the mesh boundary and netgen fills each with tetrahedra, keeping the boundary’s triangles. With shared_interfaces the surfaces are used as contoured: they are triangulated identically where two labels meet, so neighboring labels’ meshes have coincident nodes along their shared walls (each mesh holds its own copy of them). Without it, netgen first re-tiles each surface on its own into triangles about element_size_mm across, so the meshes are independent and may overlap or gap slightly where labels meet. Unlike extract_label_tetrahedra_vtk() the boundaries are already smooth, so no trim_tetrahedra_to_surface() pass is needed.

Requires the optional netgen extra (netgen-mesher).

Parameters:
  • labelmap_image (image) – Multi-label image; every non-zero label present is meshed. A binary mask yields a single mesh.

  • element_size_mm (Optional[float]) – Target edge length. It caps netgen’s interior element size and, unless contour_spacing_mm is given, sets the isotropic grid the surfaces are contoured on, and so their triangle size. The contour’s smoothing grows with it, so coarse sizes shrink the meshes: on the 1.5 mm heart test labels, 3 mm loses about 5% of the voxel volume where the labelmap’s own spacing loses about 1%. None contours at the labelmap’s finest spacing and lets netgen grade the interior freely from the surface.

  • smoothing_sigma_mm (Optional[float]) – Blur of the labels’ distance maps before their surfaces are contoured, passed to ProcessSurfaceMesh.extract_label_surfaces() as distance_sigma_mm. None uses the contour grid spacing (contour_spacing_mm, else element_size_mm, else the labelmap’s finest spacing), the same default as extract_label_tetrahedra_simpleware(); 0 disables it, leaving only the surfaces’ Taubin smoothing.

  • label_ids (Optional[Sequence[int]]) – Labels to mesh; every other label is treated as background. None meshes every label.

  • smoothing_iterations (int) – Taubin smoothing iterations applied to the surfaces, passed to ProcessSurfaceMesh.extract_label_surfaces() (0 disables). Smoothing the labels’ surfaces together can pinch a thin wall between two labels until a surface touches itself, which netgen rejects; 0 avoids that, leaving the blur alone to smooth the surfaces, at the cost of more irregular triangles.

  • shared_interfaces (bool) – Keep the contoured surfaces, so neighboring labels’ meshes share their interface nodes (default), or have netgen re-tile each label’s surface on its own to triangles about element_size_mm across.

  • contour_spacing_mm (Optional[float]) – Isotropic grid the surfaces are contoured on; None uses element_size_mm. The surfaces carry steps of this size where the labelmap’s voxels are coarser than the smoothing can round off, so a finer grid gives smaller steps. With shared_interfaces netgen keeps every contoured triangle, so halving the spacing roughly quadruples the boundary triangles and the mesh; without it netgen’s re-tiling brings the triangles back to about element_size_mm.

  • element_size_image (Optional[image]) – Target edge length at each voxel, for finer elements in parts of the mesh, such as an organ of interest or the openings of a vessel (see create_element_size_image()). Every voxel whose size is finite and below element_size_mm restricts netgen’s local element size at its centre, and netgen grades the elements back up to element_size_mm away from it; infinite voxels leave the size unrestricted. Each such voxel is one restriction, so give the image a spacing near the sizes it holds rather than finer. Without shared_interfaces the re-tiled surfaces are refined too; with it the contoured surfaces are kept, so only the interior is refined and a finer contour_spacing_mm is what refines the boundary. None (default) sizes the elements by element_size_mm alone.

Return type:

dict[int, UnstructuredGrid]

Returns:

Label id → that label’s tetrahedral mesh, whose field_data['SegmentationLabelIds'] holds the id. A label too thin to keep a surface is left out, so the mapping is empty when the labelmap holds no non-zero label.

Raises:
  • RuntimeError – If netgen produces no tetrahedra from a surface, or, without shared_interfaces, cannot re-tile one; a surface that intersects itself, as heavy smoothing can make of a thin wall, is the usual cause.

  • ValueError – If element_size_image holds a size that is NaN or not positive.

extract_label_tetrahedra_simpleware(labelmap_image, element_size_mm=None, smoothing_sigma_mm=None, label_ids=None, shared_interfaces=True, timeout_s=600)[source]

Build one unstructured tetrahedral mesh filling each label with Simpleware.

Runs Synopsys Simpleware Medical’s +FE Free mesher on the labelmap, as one external process (see simpleware_exe_path), and reads back the linear tetrahedra it exports. Each label becomes a mask that is blurred inside Simpleware (its recursive Gaussian filter) before meshing: a mask carries no sub-voxel boundary position, so +FE Free would otherwise mesh the voxel staircase. No trim_tetrahedra_to_surface() pass is needed.

Simpleware receives the labelmap with an identity direction and a zero origin, and its points are mapped back through the labelmap’s own origin and direction, so the result lies in the labelmap’s world frame whatever Simpleware’s convention for reading image orientation.

Requires a Simpleware Medical installation licensed for +FE Free.

Parameters:
  • labelmap_image (image) – Multi-label image; every non-zero label present is meshed. A binary mask yields a single mesh.

  • element_size_mm (Optional[float]) – Target edge length: the maximum edge length, with half of it as the target minimum. None keeps Simpleware’s defaults.

  • smoothing_sigma_mm (Optional[float]) – Standard deviation of the Gaussian blur applied to each label’s mask before meshing. None uses element_size_mm, or the labelmap’s finest spacing when that is None too – the same blur extract_label_tetrahedra_netgen()’s surfaces get. 0 meshes the unblurred voxel staircase. On the 1.5 mm Slicer heart mask at 2 mm elements, 1.5 mm cut the boundary roughness by a quarter and lost under 2% of the volume; 3 mm smoothed further but lost 4%, thinning small structures.

  • label_ids (Optional[Sequence[int]]) – Labels to mesh; every other label is treated as background. None meshes every label.

  • shared_interfaces (bool) – True (default) meshes all labels as the parts of one +FE Free model, so neighboring labels’ meshes have coincident nodes along their shared walls (each mesh holds its own copy of them); where blurred masks overlap, Simpleware’s part priority decides which label keeps the voxel. False meshes each label in a model of its own, so the meshes are independent and may overlap or gap slightly where labels meet.

  • timeout_s (int) – Seconds before the Simpleware process is killed.

Return type:

dict[int, UnstructuredGrid]

Returns:

Label id → that label’s tetrahedral mesh, whose field_data['SegmentationLabelIds'] holds the id. A label Simpleware exports no tetrahedra for is left out, so the mapping is empty when the labelmap holds no non-zero label.

Raises:
trim_tetrahedra_to_surface(tetrahedra, surface, iterations=5, relaxation=0.6, min_scaled_jacobian=0.1)[source]

Relax a tetrahedral mesh onto surface, keeping every cell whole.

extract_label_tetrahedra_vtk() meshes voxels, so each label’s boundary is a staircase that both protrudes through the smooth surface ProcessSurfaceMesh.extract_label_surfaces() builds for the same label and falls short of it elsewhere. Cutting the mesh at the surface with clip_surface would follow it exactly but shatters the boundary tetrahedra into slivers (about a tenth of the cells drop below a scaled Jacobian of 0.1), and neither VTK nor any current dependency can repair those.

So nothing is cut. A crinkle clip drops the cells that lie entirely outside while leaving every surviving cell intact, then the mesh is relaxed: each sweep moves every point part of the way toward the average of its neighbors, and every boundary point instead toward its closest point on surface. The interior smoothing is what makes room for the boundary to reach the surface – projecting the boundary alone flattens the cells behind it, and the quality bound below then undoes the move, which is why one projection pass leaves the staircase in place.

A move that would still wreck a cell is backed off: every point of a cell below min_scaled_jacobian has that sweep’s step halved, repeatedly, until the whole mesh clears the bound.

Parameters:
  • tetrahedra (UnstructuredGrid) – Volume mesh to relax; its cell and field data survive.

  • surface (PolyData) – Closed surface to relax onto, in the same frame.

  • iterations (int) – Relaxation sweeps. The boundary reaches the surface in the first few and then stops moving: on the Duke heart labels, sweeps beyond the default leave the mean boundary-to-surface distance and the worst cell quality where they already were, and only cost time.

  • relaxation (float) – Fraction of the way to its target a point moves per sweep. 1.0 moves the whole way and oscillates.

  • min_scaled_jacobian (float) – Cell-quality bound every tetrahedron must meet after each sweep. 0.0 only rules out flattened and inverted cells; the default also rules out slivers.

Return type:

UnstructuredGrid

Returns:

The relaxed mesh.

remove_boundary_slivers(tetrahedra, min_scaled_jacobian=0.15)[source]

Drop flat tetrahedra lying entirely on the mesh’s boundary.

trim_tetrahedra_to_surface() presses boundary cells against the surface until they reach its quality bound, which leaves flat caps whose four corners all sit on the surface. Each holds almost no volume, but warping the mesh – through a registration, say – carries its corners along nearly together, and a modest compression across the cap is enough to invert it. repair_inverted_tetrahedra() cannot help: averaging a boundary node with its neighbors pulls the cap flatter, not open. Removing the caps before the warp avoids that.

Removing a cap exposes the cell behind it, so this repeats until no cell below the bound has all four corners on the boundary.

Parameters:
  • tetrahedra (UnstructuredGrid) – Volume mesh to clean; its point, cell and field data survive on the cells kept.

  • min_scaled_jacobian (float) – Cells whose four corners are all on the boundary are removed when their scaled Jacobian is below this. The default sits just above trim_tetrahedra_to_surface()’s own 0.1 bound.

Return type:

UnstructuredGrid

Returns:

The mesh without those cells, or tetrahedra unchanged if it had none.

repair_inverted_tetrahedra(tetrahedra, max_iterations=100)[source]

Relax the nodes of any inverted or degenerate tetrahedron.

trim_tetrahedra_to_surface() holds every cell of the template above a scaled Jacobian of 0.1, but warping that template onto a specific subject – a statistical-model fit, say – carries no such constraint, and can flip a handful of elements even though the template it started from was clean. Only the nodes touching a bad element are moved, each to the mean of its mesh neighbors, which leaves geometry the fit got right alone.

Parameters:
  • tetrahedra (UnstructuredGrid) – Volume mesh to repair; its cell and field data survive.

  • max_iterations (int) – Smoothing passes to attempt before giving up.

Return type:

UnstructuredGrid

Returns:

The repaired mesh, or tetrahedra unchanged if every cell already clears zero volume.

Raises:

ValueError – If tetrahedra has no TETRA cells, or if elements are still inverted or degenerate after max_iterations passes.

TETRAHEDRON_FACES: ClassVar[tuple[list[int], ...]] = ([1, 2, 3], [0, 3, 2], [0, 1, 3], [0, 2, 1])

Vertex triples of the four faces of a positively oriented tetrahedron, each wound so that its normal points out of the tetrahedron.

static tetrahedra_arrays(mesh)[source]

Return the points and positively oriented tetrahedra of a TETRA grid.

Parameters:

mesh (UnstructuredGrid) – Grid of TETRA cells only.

Return type:

tuple[ndarray, ndarray]

Returns:

(n, 3) float64 points and (m, 4) int64 tetrahedra, each reordered where needed so that its signed volume is positive.

Raises:

ValueError – If a tetrahedron’s determinant is exactly zero, so it has no orientation. Slivers of tiny but nonzero volume are oriented by their sign and kept.

static boundary_faces(tetrahedra)[source]

Return the outward-wound boundary triangles of positive tetrahedra.

A boundary triangle is a face that belongs to exactly one tetrahedron.

Return type:

ndarray

static tetrahedron_edges(tetrahedra)[source]

Return the sorted unique edges of tetrahedra (the P2 edge node order).

Return type:

ndarray

static triangle_nodes(faces, edges, vertex_count)[source]

Return the six P2 nodes (v0, v1, v2, e01, e12, e20) of each triangle.

Parameters:
  • faces (ndarray) – Triangles as vertex indices.

  • edges (ndarray) – Sorted unique edges, from tetrahedron_edges().

  • vertex_count (int) – Number of vertices; edge node k is numbered vertex_count + k.

Return type:

ndarray

static common_point_ids(*point_sets)[source]

Number the points of all sets so that equal coordinates share an id.

Conforming meshes share interface points with identical coordinates, so this identifies them across meshes.

Return type:

list[ndarray]

Returns:

One id array per point set.

Raises:

ValueError – If there are too many distinct points for face_keys().

static face_keys(point_ids, faces)[source]

Return one integer per triangle that ignores its vertex order.

Parameters:
Raises:

ValueError – If an id of a triangle is negative or not below 2**21, which the 21 bits per vertex of the key cannot hold.

Return type:

ndarray

static shared_faces(points, faces, others)[source]

Return which triangles of a mesh some other mesh holds exactly.

Parameters:
Return type:

ndarray

Returns:

True for each triangle whose three vertex coordinates are those of a triangle in others; all False when others is empty.

static enclosed_volume(points, faces)[source]

Return the volume enclosed by a closed, outward-wound triangle surface.

Return type:

float

Navigation

Surface Mesh Tools | Utility Modules | Mesh Kernels