Easier Pythonic interface to VTK for 3D scientific data visualization and mesh analysis
—
PyVista provides comprehensive mesh processing and filtering capabilities through mixin classes that extend dataset functionality with geometric operations, topological modifications, and data transformations.
Removes portions of meshes using planes or implicit functions.
def clip(self, normal='x', origin=None, invert=False, value=0.0, inplace=False) -> 'DataSet':
"""
Clip dataset with a plane or scalar value.
Parameters:
normal (str or tuple): Clipping plane normal ('x', 'y', 'z') or vector
origin (tuple): Point on clipping plane
invert (bool): Invert clipping direction
value (float): Scalar value for clipping
inplace (bool): Modify dataset in place
Returns:
DataSet: Clipped dataset
"""
def clip_box(self, bounds, invert=False, factor=0.35, inplace=False) -> 'DataSet':
"""
Clip dataset with a box.
Parameters:
bounds (tuple): Bounding box (xmin, xmax, ymin, ymax, zmin, zmax)
invert (bool): Keep region outside box
factor (float): Implicit function factor
inplace (bool): Modify dataset in place
Returns:
DataSet: Clipped dataset
"""
def clip_scalar(self, scalars=None, invert=False, value=0.0, both=False,
inplace=False) -> 'DataSet':
"""
Clip dataset by scalar values.
Parameters:
scalars (str): Name of scalar array to use
invert (bool): Invert clipping direction
value (float): Clipping threshold value
both (bool): Return both clipped parts
inplace (bool): Modify dataset in place
Returns:
DataSet: Clipped dataset
"""Creates cross-sections through datasets.
def slice(self, normal='x', origin=None, generate_triangles=False,
contour=False, inplace=False) -> PolyData:
"""
Slice dataset with a plane.
Parameters:
normal (str or tuple): Plane normal direction
origin (tuple): Point on plane
generate_triangles (bool): Triangulate slice
contour (bool): Generate contour lines
inplace (bool): Modify dataset in place
Returns:
PolyData: Sliced surface
"""
def slice_orthogonal(self, x=None, y=None, z=None, generate_triangles=False,
contour=False) -> MultiBlock:
"""
Create orthogonal slices through dataset.
Parameters:
x (float): X-coordinate for YZ slice
y (float): Y-coordinate for XZ slice
z (float): Z-coordinate for XY slice
generate_triangles (bool): Triangulate slices
contour (bool): Generate contour lines
Returns:
MultiBlock: Collection of slices
"""
def slice_along_axis(self, n=5, axis='x', tolerance=None,
generate_triangles=False) -> MultiBlock:
"""
Create multiple parallel slices along an axis.
Parameters:
n (int): Number of slices
axis (str): Axis direction ('x', 'y', 'z')
tolerance (float): Slicing tolerance
generate_triangles (bool): Triangulate slices
Returns:
MultiBlock: Collection of slices
"""Extracts regions based on scalar values.
def threshold(self, value=None, scalars=None, invert=False, continuous=False,
preference='cell', all_scalars=False, component_mode='selected',
component=0, method='upper', inplace=False) -> UnstructuredGrid:
"""
Extract cells/points with scalar values above/below threshold.
Parameters:
value (float or tuple): Threshold value(s)
scalars (str): Name of scalar array
invert (bool): Invert threshold logic
continuous (bool): Use continuous thresholding
preference (str): Data association ('cell' or 'point')
all_scalars (bool): Threshold all scalar arrays
component_mode (str): Component selection mode
component (int): Component number for vector data
method (str): Threshold method ('upper', 'lower', 'between')
inplace (bool): Modify dataset in place
Returns:
UnstructuredGrid: Thresholded dataset
"""
def threshold_percent(self, percent=0.5, scalars=None, invert=False,
continuous=False, preference='cell',
inplace=False) -> UnstructuredGrid:
"""
Threshold by percentage of scalar range.
Parameters:
percent (float): Percentage of range (0.0 to 1.0)
scalars (str): Name of scalar array
invert (bool): Invert threshold logic
continuous (bool): Use continuous thresholding
preference (str): Data association
inplace (bool): Modify dataset in place
Returns:
UnstructuredGrid: Thresholded dataset
"""Generates isosurfaces and contour lines.
def contour(self, isosurfaces=10, scalars=None, compute_normals=False,
compute_gradients=False, compute_scalars=True, rng=None,
preference='point', method='contour', locator=None,
progress_bar=False) -> PolyData:
"""
Generate isosurfaces/contours from scalar data.
Parameters:
isosurfaces (int or list): Number or list of isovalues
scalars (str): Name of scalar array
compute_normals (bool): Compute surface normals
compute_gradients (bool): Compute gradients
compute_scalars (bool): Compute scalars on output
rng (tuple): Value range for isosurfaces
preference (str): Data association
method (str): Contouring method
locator (object): Point locator for acceleration
progress_bar (bool): Show progress bar
Returns:
PolyData: Contoured surface
"""
def contour_banded(self, n_contours=10, scalars=None, compute_normals=False,
rng=None, preference='point') -> PolyData:
"""
Generate banded contours with filled regions.
Parameters:
n_contours (int): Number of contour bands
scalars (str): Name of scalar array
compute_normals (bool): Compute surface normals
rng (tuple): Value range
preference (str): Data association
Returns:
PolyData: Banded contour surface
"""Reduces mesh roughness through various smoothing algorithms.
def smooth(self, n_iter=20, relaxation_factor=0.01, feature_angle=45.0,
edge_angle=15.0, boundary_smoothing=True, feature_smoothing=False,
normalize_coordinates=False, inplace=False) -> PolyData:
"""
Smooth mesh using Laplacian smoothing.
Parameters:
n_iter (int): Number of smoothing iterations
relaxation_factor (float): Relaxation factor (0.0 to 1.0)
feature_angle (float): Feature edge angle threshold
edge_angle (float): Edge angle threshold
boundary_smoothing (bool): Smooth boundary edges
feature_smoothing (bool): Smooth feature edges
normalize_coordinates (bool): Normalize coordinates
inplace (bool): Modify mesh in place
Returns:
PolyData: Smoothed mesh
"""
def smooth_taubin(self, n_iter=20, pass_band=0.1, normalize_coordinates=False,
inplace=False) -> PolyData:
"""
Smooth mesh using Taubin algorithm.
Parameters:
n_iter (int): Number of iterations
pass_band (float): Pass band value
normalize_coordinates (bool): Normalize coordinates
inplace (bool): Modify mesh in place
Returns:
PolyData: Smoothed mesh
"""Reduces mesh complexity by removing vertices and faces.
def decimate(self, target_reduction=0.5, volume_preservation=False,
attribute_error=False, split_boundary=False, preserve_topology=True,
inplace=False, progress_bar=False) -> PolyData:
"""
Reduce mesh complexity through decimation.
Parameters:
target_reduction (float): Fraction of triangles to remove (0.0 to 1.0)
volume_preservation (bool): Preserve volume during decimation
attribute_error (bool): Use attribute error metric
split_boundary (bool): Allow boundary edge splitting
preserve_topology (bool): Maintain mesh topology
inplace (bool): Modify mesh in place
progress_bar (bool): Show progress bar
Returns:
PolyData: Decimated mesh
"""
def decimate_pro(self, target_reduction=0.9, feature_angle=45.0,
split_angle=75.0, splitting=True, preserve_topology=False,
inplace=False, progress_bar=False) -> PolyData:
"""
Advanced decimation with more control options.
Parameters:
target_reduction (float): Fraction of triangles to remove
feature_angle (float): Feature angle for edge classification
split_angle (float): Edge splitting angle
splitting (bool): Enable edge splitting
preserve_topology (bool): Maintain topology
inplace (bool): Modify mesh in place
progress_bar (bool): Show progress bar
Returns:
PolyData: Decimated mesh
"""Increases mesh resolution through subdivision schemes.
def subdivide(self, nsub=1, subfilter='linear', inplace=False) -> PolyData:
"""
Subdivide mesh to increase resolution.
Parameters:
nsub (int): Number of subdivision levels
subfilter (str): Subdivision algorithm ('linear', 'butterfly', 'loop')
inplace (bool): Modify mesh in place
Returns:
PolyData: Subdivided mesh
"""
def subdivide_adaptive(self, max_tri_area=1.0, max_n_tris=None,
max_n_passes=1, inplace=False) -> PolyData:
"""
Adaptive subdivision based on triangle area.
Parameters:
max_tri_area (float): Maximum triangle area
max_n_tris (int): Maximum number of triangles
max_n_passes (int): Maximum subdivision passes
inplace (bool): Modify mesh in place
Returns:
PolyData: Adaptively subdivided mesh
"""Basic geometric transformations.
def scale(self, xyz, transform_all_input_vectors=False, inplace=False) -> 'DataSet':
"""
Scale dataset coordinates.
Parameters:
xyz (float or tuple): Scale factor(s) for x, y, z axes
transform_all_input_vectors (bool): Scale vector data
inplace (bool): Modify dataset in place
Returns:
DataSet: Scaled dataset
"""
def translate(self, xyz, transform_all_input_vectors=False,
inplace=False) -> 'DataSet':
"""
Translate dataset coordinates.
Parameters:
xyz (tuple): Translation vector (dx, dy, dz)
transform_all_input_vectors (bool): Translate vector data
inplace (bool): Modify dataset in place
Returns:
DataSet: Translated dataset
"""
def rotate_x(self, angle, point=(0.0, 0.0, 0.0), transform_all_input_vectors=False,
inplace=False) -> 'DataSet':
"""Rotate around X-axis by specified angle in degrees."""
def rotate_y(self, angle, point=(0.0, 0.0, 0.0), transform_all_input_vectors=False,
inplace=False) -> 'DataSet':
"""Rotate around Y-axis by specified angle in degrees."""
def rotate_z(self, angle, point=(0.0, 0.0, 0.0), transform_all_input_vectors=False,
inplace=False) -> 'DataSet':
"""Rotate around Z-axis by specified angle in degrees."""Apply arbitrary transformation matrices.
def transform(self, trans, transform_all_input_vectors=False,
inplace=False) -> 'DataSet':
"""
Apply 4x4 transformation matrix.
Parameters:
trans (array-like): 4x4 transformation matrix
transform_all_input_vectors (bool): Transform vector data
inplace (bool): Modify dataset in place
Returns:
DataSet: Transformed dataset
"""
def reflect(self, normal, point=None, transform_all_input_vectors=False,
inplace=False) -> 'DataSet':
"""
Reflect dataset across a plane.
Parameters:
normal (tuple): Plane normal vector
point (tuple): Point on reflection plane
transform_all_input_vectors (bool): Reflect vector data
inplace (bool): Modify dataset in place
Returns:
DataSet: Reflected dataset
"""Combine meshes using boolean set operations.
def boolean_union(self, mesh, tolerance=1e-5, inplace=False) -> PolyData:
"""
Compute boolean union with another mesh.
Parameters:
mesh (PolyData): Second mesh for operation
tolerance (float): Numerical tolerance
inplace (bool): Modify mesh in place
Returns:
PolyData: Union result
"""
def boolean_difference(self, mesh, tolerance=1e-5, inplace=False) -> PolyData:
"""
Compute boolean difference with another mesh.
Parameters:
mesh (PolyData): Mesh to subtract
tolerance (float): Numerical tolerance
inplace (bool): Modify mesh in place
Returns:
PolyData: Difference result
"""
def boolean_intersection(self, mesh, tolerance=1e-5, inplace=False) -> PolyData:
"""
Compute boolean intersection with another mesh.
Parameters:
mesh (PolyData): Second mesh for operation
tolerance (float): Numerical tolerance
inplace (bool): Modify mesh in place
Returns:
PolyData: Intersection result
"""Fix common mesh problems.
def clean(self, point_merging=True, tolerance=None, lines_to_points=True,
polys_to_lines=True, strips_to_polys=True, inplace=False,
absolute=True) -> 'DataSet':
"""
Clean mesh by merging duplicate points and removing degenerate cells.
Parameters:
point_merging (bool): Merge duplicate points
tolerance (float): Point merging tolerance
lines_to_points (bool): Convert degenerate lines to points
polys_to_lines (bool): Convert degenerate polygons to lines
strips_to_polys (bool): Convert triangle strips to polygons
inplace (bool): Modify mesh in place
absolute (bool): Use absolute tolerance
Returns:
DataSet: Cleaned mesh
"""
def fill_holes(self, hole_size, inplace=False, progress_bar=False) -> PolyData:
"""
Fill holes in mesh surface.
Parameters:
hole_size (float): Maximum hole size to fill
inplace (bool): Modify mesh in place
progress_bar (bool): Show progress bar
Returns:
PolyData: Mesh with filled holes
"""
def remove_duplicate_cells(self, inplace=False) -> 'DataSet':
"""
Remove duplicate cells from mesh.
Parameters:
inplace (bool): Modify mesh in place
Returns:
DataSet: Mesh without duplicate cells
"""Compute mesh quality measures.
def compute_cell_quality(self, quality_measure='scaled_jacobian',
progress_bar=False) -> 'DataSet':
"""
Compute cell quality metrics.
Parameters:
quality_measure (str): Quality metric to compute
progress_bar (bool): Show progress bar
Returns:
DataSet: Mesh with quality data
"""Transform between coordinate systems.
def cartesian_to_spherical(x, y, z):
"""
Convert Cartesian coordinates to spherical coordinates.
Parameters:
x (array-like): X coordinates
y (array-like): Y coordinates
z (array-like): Z coordinates
Returns:
tuple: (radius, theta, phi) spherical coordinates
"""
def spherical_to_cartesian(r, theta, phi):
"""
Convert spherical coordinates to Cartesian coordinates.
Parameters:
r (array-like): Radial distance
theta (array-like): Azimuthal angle
phi (array-like): Polar angle
Returns:
tuple: (x, y, z) Cartesian coordinates
"""
def transform_vectors_sph_to_cart(theta, phi, r, u, v, w):
"""
Transform vectors from spherical to Cartesian coordinates.
Parameters:
theta (array-like): Azimuthal angles
phi (array-like): Polar angles
r (array-like): Radial distances
u (array-like): Radial components
v (array-like): Theta components
w (array-like): Phi components
Returns:
tuple: (x, y, z) vector components in Cartesian coordinates
"""Utilities for creating and manipulating grids.
def create_grid(dataset, dimensions):
"""
Create structured grid from dataset.
Parameters:
dataset (DataSet): Input dataset
dimensions (tuple): Grid dimensions
Returns:
StructuredGrid: Structured grid
"""
def grid_from_sph_coords(theta, phi, r):
"""
Create grid from spherical coordinates.
Parameters:
theta (array-like): Azimuthal coordinates
phi (array-like): Polar coordinates
r (array-like): Radial coordinates
Returns:
StructuredGrid: Grid in spherical coordinates
"""
def merge(datasets, merge_points=True, tolerance=None, main_has_priority=True):
"""
Merge multiple datasets into single dataset.
Parameters:
datasets (list): List of datasets to merge
merge_points (bool): Merge coincident points
tolerance (float): Point merging tolerance
main_has_priority (bool): Main dataset has priority
Returns:
UnstructuredGrid: Merged dataset
"""
def sample_function(function, bounds=(-1, 1, -1, 1, -1, 1), dims=(50, 50, 50),
compute_gradients=False, scalars_name='scalars',
generate_vertex_normals=True):
"""
Sample a function over a regular grid.
Parameters:
function (callable): Function to sample f(x, y, z)
bounds (tuple): Sampling bounds (xmin, xmax, ymin, ymax, zmin, zmax)
dims (tuple): Grid dimensions (nx, ny, nz)
compute_gradients (bool): Compute gradient vectors
scalars_name (str): Name for scalar array
generate_vertex_normals (bool): Generate vertex normals
Returns:
ImageData: Sampled function data
"""
def voxelize_volume(mesh, density, check_surface=True, progress_bar=False):
"""
Voxelize the volume of a surface mesh.
Parameters:
mesh (PolyData): Surface mesh to voxelize
density (float): Voxel density
check_surface (bool): Check surface closure
progress_bar (bool): Show progress bar
Returns:
ImageData: Voxelized volume
"""Specialized data generation functions.
def perlin_noise(amplitude=1.0, freq=(1, 1, 1), phase=(0, 0, 0)):
"""
Generate Perlin noise function.
Parameters:
amplitude (float): Noise amplitude
freq (tuple): Frequency in each direction
phase (tuple): Phase offset in each direction
Returns:
callable: Perlin noise function f(x, y, z)
"""Create 3D objects from 2D profiles.
def extrude(self, vector, capping=True, inplace=False,
progress_bar=False) -> PolyData:
"""
Extrude mesh along vector direction.
Parameters:
vector (tuple): Extrusion direction and distance
capping (bool): Cap extruded ends
inplace (bool): Modify mesh in place
progress_bar (bool): Show progress bar
Returns:
PolyData: Extruded mesh
"""
def extrude_rotate(self, resolution=30, translation=0.0, dradius=0.0,
angle=360.0, capping=True, inplace=False) -> PolyData:
"""
Extrude by rotation around axis.
Parameters:
resolution (int): Number of rotation steps
translation (float): Translation along axis
dradius (float): Change in radius
angle (float): Rotation angle in degrees
capping (bool): Cap ends
inplace (bool): Modify mesh in place
Returns:
PolyData: Rotationally extruded mesh
"""import pyvista as pv
# Load example mesh
mesh = pv.examples.load_airplane()
# Clip with plane
clipped = mesh.clip(normal='x', origin=(0, 0, 0))
# Create multiple slices
slices = mesh.slice_orthogonal(x=0, y=0, z=0)
# Plot results
plotter = pv.Plotter(shape=(1, 2))
plotter.subplot(0, 0)
plotter.add_mesh(clipped, show_edges=True)
plotter.add_title("Clipped Mesh")
plotter.subplot(0, 1)
plotter.add_mesh(slices, show_edges=True)
plotter.add_title("Orthogonal Slices")
plotter.show()import pyvista as pv
# Load noisy mesh
mesh = pv.examples.download_bunny()
# Processing pipeline
smoothed = mesh.smooth(n_iter=50, relaxation_factor=0.1)
decimated = smoothed.decimate(target_reduction=0.7)
subdivided = decimated.subdivide(nsub=1)
# Compare results
plotter = pv.Plotter(shape=(2, 2))
plotter.subplot(0, 0)
plotter.add_mesh(mesh, show_edges=True)
plotter.add_title("Original")
plotter.subplot(0, 1)
plotter.add_mesh(smoothed, show_edges=True)
plotter.add_title("Smoothed")
plotter.subplot(1, 0)
plotter.add_mesh(decimated, show_edges=True)
plotter.add_title("Decimated")
plotter.subplot(1, 1)
plotter.add_mesh(subdivided, show_edges=True)
plotter.add_title("Subdivided")
plotter.show()Install with Tessl CLI
npx tessl i tessl/pypi-pyvista