Volume#
- class medicalimageanalysis.utils.mesh.volume.Volume(surface_meshes, names=None, cavities=None)[source]
Bases:
objectConverts one or more closed surface meshes into a single tetrahedral mesh.
The prepared surfaces are kept on surface_meshes and the tetrahedral result on mesh (None until create is called). The index of a surface in surface_meshes is its region label in mesh.cell_data[‘Region’].
- surface_meshes
Source surfaces, triangulated, cleaned, and oriented (outward, or inward for cavities), in mm.
- Type:
list[pv.PolyData]
- mesh
Tetrahedral mesh built by create, with cell array ‘Region’ and field array ‘RegionNames’.
- Type:
pv.UnstructuredGrid | None
Examples
Tetrahedralize a single sphere:
>>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume(pv.Sphere(radius=10.0)) >>> volume.mesh is None True >>> volume.create(edge_length_fac=0.1, quiet=True) >>> volume.mesh.n_cells > 0 True
Nested and separate surfaces in one mesh:
>>> outer = pv.Sphere(radius=20.0) >>> inner = pv.Sphere(radius=8.0) >>> separate = pv.Sphere(radius=6.0, center=(40.0, 0.0, 0.0)) >>> volume = Volume([outer, inner, separate]) >>> volume.create(edge_length_abs=4.0, quiet=True) >>> sorted(set(volume.mesh.cell_data['Region'].tolist())) [0, 1, 2]
Liver with a tumor, finer inside the tumor, and the tumor surface and nodes for FEBio:
>>> import medicalimageanalysis as mia >>> image = mia.Data.image[mia.Data.image_list()[0]] >>> volume = Volume([image.roi['Liver'].mesh, image.roi['GTV'].mesh], names=['Liver', 'GTV']) >>> volume.create(edge_length_abs=3.0, region_edge_lengths=[None, 1.0]) >>> gtv_surface = volume.extract_boundary('GTV', neighbor='Liver') >>> gtv_nodes = volume.region_node_ids('GTV') >>> volume.write('C:/Data/liver_gtv_tet.vtu')
- static prepare_surface(surface, inward=False)[source]
Triangulate, clean, and orient a surface.
- Parameters:
surface (pv.PolyData) – Closed surface, in mm.
inward (bool) – False orients normals outward (meshed region). True orients them inward (cavity).
- Returns:
Triangle surface with consistently oriented cell normals in ‘Normals’.
- Return type:
pv.PolyData
Examples
An inside-out sphere comes back facing outward:
>>> import numpy as np >>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> flipped = pv.Sphere(radius=10.0).flip_faces() >>> fixed = Volume.prepare_surface(flipped) >>> outward = np.einsum('ij,ij->i', fixed.cell_data['Normals'], fixed.cell_centers().points) >>> bool((outward > 0).all()) True
A cavity faces inward:
>>> cavity = Volume.prepare_surface(pv.Sphere(radius=10.0), inward=True) >>> inward = np.einsum('ij,ij->i', cavity.cell_data['Normals'], cavity.cell_centers().points) >>> bool((inward < 0).all()) True
Quads are split into triangles:
>>> Volume.prepare_surface(pv.Box()).is_all_triangles True
- compute_quality(quality_measure='scaled_jacobian')[source]
Compute a per-cell quality measure and store it on the mesh.
The values are stored in mesh.cell_data[‘Quality’]. For the scaled Jacobian, 1 is a regular tetrahedron, values near 0 are slivers, and negative values are inverted elements that FEBio will reject.
- Parameters:
quality_measure (str) – Any measure accepted by pv.UnstructuredGrid.cell_quality, e.g. ‘scaled_jacobian’, ‘aspect_ratio’, ‘min_angle’, ‘radius_ratio’.
- Returns:
(n_cells,) quality values.
- Return type:
np.ndarray
Examples
>>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume(pv.Sphere(radius=10.0)) >>> volume.create(edge_length_fac=0.1, quiet=True) >>> quality = volume.compute_quality() >>> bool(quality.min() > 0) True >>> 'Quality' in volume.mesh.cell_data True
Count slivers per region:
>>> int((quality[volume.mesh.cell_data['Region'] == 0] < 0.1).sum()) >= 0 True
- create(edge_length_fac=0.05, edge_length_abs=None, region_edge_lengths=None, optimize=True, simplify=True, epsilon=0.001, stop_energy=10.0, coarsen=False, num_threads=0, num_opt_iter=80, loglevel=6, quiet=False, disable_filtering=False, sizing_field=None, sizing_field_scalars=None, bg_vertices=None, bg_tets=None, bg_values=None)[source]
Generate one conforming tetrahedral mesh from all surface meshes.
All surfaces are merged and run through PyTetWild together with VTK node ordering, so every tetrahedron has positive volume. The result is stored on self.mesh with each cell labeled in ‘Region’.
Sizing priority: region_edge_lengths, then sizing_field, then bg_* arrays, then a uniform edge_length_abs / edge_length_fac.
- Parameters:
edge_length_fac (float) – Target edge length as a fraction of the bounding-box diagonal of the largest single surface. Ignored when edge_length_abs is given.
edge_length_abs (float, optional) – Target edge length in mm.
region_edge_lengths (list[float | None], optional) – Target edge length in mm per surface, same order as surface_meshes. None entries, and space outside all surfaces, use edge_length_abs (or edge_length_fac). A cavity’s entry sizes the elements on its wall. Requires optimize=True.
optimize (bool) – Improve element quality (minimum scaled Jacobian). Controlled by stop_energy and num_opt_iter.
simplify (bool) – Simplify the input surfaces before tetrahedralization.
epsilon (float) – Envelope size: max distance of the output surfaces from the input, relative to the bounding-box diagonal of the largest single surface.
stop_energy (float) – Optimization stops when the conformal AMIPS energy reaches this.
coarsen (bool) – Coarsen the output as much as possible while keeping quality.
num_threads (int) – Threads used; 0 uses all cores.
num_opt_iter (int) – Maximum optimization iterations when optimize=True.
loglevel (int) – 0 = most verbose, 6 = minimal.
quiet (bool) – Disable all output. Overrides loglevel.
disable_filtering (bool) – Keep all tetrahedra of the bounding box instead of only those inside the surfaces. Outside cells get Region -1.
sizing_field (pv.UnstructuredGrid, optional) – All-tetrahedral grid with a point array of target edge lengths in mm, covering all surfaces. Requires optimize=True.
sizing_field_scalars (str, optional) – Name of the point array on sizing_field; defaults to its active point scalars.
bg_vertices (np.ndarray, optional) – The same sizing field as raw arrays: points (n, 3), tetrahedra (m, 4), and target edge length per point (n,).
bg_tets (np.ndarray, optional) – The same sizing field as raw arrays: points (n, 3), tetrahedra (m, 4), and target edge length per point (n,).
bg_values (np.ndarray, optional) – The same sizing field as raw arrays: points (n, 3), tetrahedra (m, 4), and target edge length per point (n,).
- Returns:
The result is stored on self.mesh.
- Return type:
None
Examples
Uniform mesh of a 10 mm radius sphere:
>>> import numpy as np >>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume(pv.Sphere(radius=10.0)) >>> volume.create(edge_length_fac=0.1, quiet=True) >>> sizes = volume.mesh.compute_cell_sizes(length=False, area=False) >>> bool((sizes.cell_data['Volume'] > 0).all()) True
A smaller edge_length_fac gives more tetrahedra:
>>> coarse = volume.mesh.n_cells >>> volume.create(edge_length_fac=0.05, quiet=True) >>> volume.mesh.n_cells > coarse True
A distant second surface does not change the first one’s edge length (within ~10%, from PyTetWild’s own tolerances):
>>> def mean_edge(grid): ... return grid.extract_all_edges().compute_cell_sizes()['Length'].mean() >>> pair = Volume([pv.Sphere(radius=10.0), pv.Sphere(radius=10.0, center=(200.0, 0.0, 0.0))]) >>> pair.create(edge_length_fac=0.05, quiet=True) >>> bool(abs(mean_edge(pair.extract_region(0)) / mean_edge(volume.mesh) - 1) < 0.15) True
Nested spheres, 1.5 mm inside the inner sphere and 4 mm elsewhere:
>>> volume = Volume([pv.Sphere(radius=20.0), pv.Sphere(radius=8.0)]) >>> volume.create(edge_length_abs=4.0, region_edge_lengths=[None, 1.5], quiet=True) >>> sizes = volume.mesh.compute_cell_sizes(length=False, area=False).cell_data['Volume'] >>> region = volume.mesh.cell_data['Region'] >>> bool(sizes[region == 1].mean() < sizes[region == 0].mean()) True
An inner cavity is left empty:
>>> hollow = Volume([pv.Sphere(radius=20.0), pv.Sphere(radius=8.0)], cavities=[1]) >>> hollow.create(edge_length_abs=3.0, quiet=True) >>> centers = np.linalg.norm(hollow.mesh.cell_centers().points, axis=1) >>> int((centers < 7.5).sum()) 0
A custom sizing field, finer toward +x:
>>> field = pv.ImageData(dimensions=(12, 12, 12), spacing=(5.0, 5.0, 5.0), ... origin=(-27.5, -27.5, -27.5)).triangulate() >>> field.point_data['size'] = np.interp(field.points[:, 0], [-25.0, 25.0], [5.0, 1.5]) >>> volume.create(sizing_field=field, sizing_field_scalars='size', quiet=True) >>> volume.mesh.n_cells > 0 True
A sizing field needs optimization on:
>>> volume.create(region_edge_lengths=[None, 1.5], optimize=False, quiet=True) Traceback (most recent call last): ... ValueError: A sizing field requires optimize=True.
- extract_boundary(region, neighbor=None)[source]
Extract a region’s boundary faces as a surface, e.g. for an FEBio surface, contact pair, or load.
Faces are oriented with normals pointing out of region. Global ids refer to mesh, so they can be written directly into FEBio sets.
- Parameters:
- Returns:
Triangle surface with point array ‘GlobalNodeIds’, and cell arrays ‘GlobalElementIds’ (the tetrahedron each face belongs to) and ‘Neighbor’ (region on the other side).
- Return type:
pv.PolyData
Examples
Interface between a tumor and the surrounding tissue:
>>> import numpy as np >>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume([pv.Sphere(radius=20.0), pv.Sphere(radius=8.0)], names=['Tissue', 'Tumor']) >>> volume.create(edge_length_abs=3.0, quiet=True) >>> interface = volume.extract_boundary('Tumor', neighbor='Tissue') >>> bool(abs(np.linalg.norm(interface.points, axis=1).mean() - 8.0) < 0.2) True
Normals point out of the region asked for:
>>> normals = interface.compute_normals(cell_normals=True, point_normals=False, ... auto_orient_normals=False).cell_data['Normals'] >>> bool((np.einsum('ij,ij->i', normals, interface.cell_centers().points) > 0).all()) True
The tissue’s full boundary is its outer skin plus the tumor wall:
>>> boundary = volume.extract_boundary('Tissue') >>> sorted(np.unique(boundary.cell_data['Neighbor']).tolist()) [-1, 1]
Global node ids index straight into the volume mesh:
>>> ids = interface.point_data['GlobalNodeIds'] >>> bool(np.allclose(volume.mesh.points[ids], interface.points)) True
A cavity wall, e.g. for a pressure load:
>>> hollow = Volume([pv.Sphere(radius=20.0), pv.Sphere(radius=8.0)], names=['Wall', 'Lumen'], ... cavities=['Lumen']) >>> hollow.create(edge_length_abs=3.0, quiet=True) >>> lumen_wall = hollow.extract_boundary('Wall', neighbor='Lumen') >>> bool(abs(np.linalg.norm(lumen_wall.points, axis=1).mean() - 8.0) < 0.2) True
- extract_region(region)[source]
Return the tetrahedra labeled with one region.
- Parameters:
region (int | str) – Region index or name, or -1 for unlabeled cells.
- Returns:
Tetrahedra of that region, with ‘Region’ carried over and ‘vtkOriginalPointIds’ / ‘vtkOriginalCellIds’ pointing back into mesh. Empty if no cell has that label.
- Return type:
pv.UnstructuredGrid
Examples
Split nested spheres into the outer shell and the inner core:
>>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume([pv.Sphere(radius=20.0), pv.Sphere(radius=8.0)], names=['Shell', 'Core']) >>> volume.create(edge_length_abs=3.0, quiet=True) >>> shell = volume.extract_region('Shell') >>> core = volume.extract_region(1) >>> shell.n_cells + core.n_cells == volume.mesh.n_cells True >>> round(core.bounds[1]) 8
- region_node_ids(region)[source]
Return the global node ids used by a region, e.g. for an FEBio node set or to assign initial temperature.
Nodes on an interface belong to both regions.
- Parameters:
- Returns:
Sorted unique node ids into mesh.points.
- Return type:
np.ndarray
Examples
>>> import numpy as np >>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume([pv.Sphere(radius=20.0), pv.Sphere(radius=8.0)], names=['Tissue', 'Tumor']) >>> volume.create(edge_length_abs=3.0, quiet=True) >>> tumor_nodes = volume.region_node_ids('Tumor') >>> bool(np.linalg.norm(volume.mesh.points[tumor_nodes], axis=1).max() < 8.5) True
The interface nodes are the overlap of the two sets:
>>> shared = np.intersect1d(tumor_nodes, volume.region_node_ids('Tissue')) >>> interface = volume.extract_boundary('Tumor', neighbor='Tissue') >>> bool(np.array_equal(shared, np.sort(interface.point_data['GlobalNodeIds']))) True
- write(path)[source]
Save the tetrahedral mesh to a file in ASCII.
create must be called first. ‘Region’, ‘RegionNames’, and ‘Quality’ (if computed) are saved with it.
- Parameters:
path (str) – Output path. Any PyVista-supported extension (.vtu, .vtk, …).
- Return type:
None
Examples
Write and read back a sphere:
>>> import pyvista as pv >>> from medicalimageanalysis.utils.mesh.volume import Volume >>> volume = Volume(pv.Sphere(radius=10.0), names=['Ball']) >>> volume.create(edge_length_fac=0.1, quiet=True) >>> volume.write('sphere_tet.vtu') >>> reloaded = pv.read('sphere_tet.vtu') >>> reloaded.n_cells == volume.mesh.n_cells True >>> reloaded.field_data['RegionNames'].tolist() ['Ball']