Library to make reading, writing and modifying both binary and ascii STL files easy.
85
Evaluation — 85%
↑ 1.39xAgent success when using this tile
Calculate geometric properties, validate mesh integrity, and analyze 3D mesh characteristics including volume, mass properties, surface area, and mesh closure validation.
Calculate volume, center of gravity, and inertia tensor for closed meshes.
def get_mass_properties(self):
"""
Calculate volume, center of gravity, and inertia matrix.
Returns:
tuple[float, numpy.array, numpy.array]: (volume, cog, inertia)
- volume (float): Volume of the closed mesh
- cog (numpy.array): Center of gravity coordinates (3,)
- inertia (numpy.array): 3x3 inertia matrix expressed at COG
Notes:
- Requires a closed mesh for accurate results
- Automatically calls check() to validate mesh closure
- Uses polyhedral mass properties algorithm
"""
def get_mass_properties_with_density(self, density):
"""
Calculate mass properties with specified material density.
Parameters:
- density (float): Material density in kg/m³ (when mesh units are meters)
Returns:
tuple[float, float, numpy.array, numpy.array]: (volume, mass, cog, inertia)
- volume (float): Volume of the mesh
- mass (float): Total mass (volume * density)
- cog (numpy.array): Center of gravity coordinates (3,)
- inertia (numpy.array): 3x3 inertia matrix at COG including mass
"""Calculate triangle areas and centroid positions for geometric analysis.
def update_areas(self, normals=None):
"""
Calculate surface areas for all triangles.
Parameters:
- normals (numpy.array, optional): Pre-computed normal vectors
(calculated if not provided)
Notes:
- Updates the areas property with triangle surface areas
- Areas calculated as 0.5 * |cross_product|
- Results stored in areas property as (N, 1) array
"""
def update_centroids(self):
"""
Calculate centroid positions for all triangles.
Notes:
- Updates the centroids property with triangle centers
- Centroids calculated as mean of three vertices
- Results stored in centroids property as (N, 3) array
"""
def update_min(self):
"""
Calculate minimum coordinate values across all vertices.
Notes:
- Updates the min_ property with computed values
- Called automatically when min_ property is accessed
"""
def update_max(self):
"""
Calculate maximum coordinate values across all vertices.
Notes:
- Updates the max_ property with computed values
- Called automatically when max_ property is accessed
"""Validate mesh integrity and closure for accurate geometric calculations.
def is_closed(self, exact=False):
"""
Check if the mesh forms a closed surface.
Parameters:
- exact (bool): Perform exact edge-based validation
False uses normal vector sum approximation
Returns:
bool: True if mesh is closed, False otherwise
Notes:
- Exact=True: Validates all edges are properly paired
- Exact=False: Uses normal vector sum (faster but less reliable)
- Closed meshes required for volume and mass calculations
- Warns about potential issues when mesh is not closed
"""
def check(self, exact=False):
"""
Validate mesh integrity.
Parameters:
- exact (bool): Perform exact validation checks
Returns:
bool: True if mesh passes validation, False otherwise
Notes:
- Currently equivalent to is_closed()
- May include additional validation checks in future versions
"""Access computed geometric properties through convenient properties.
@property
def areas(self):
"""
Triangle surface areas.
Returns:
numpy.array: Surface areas for each triangle (N, 1)
Notes:
- Automatically calculated when first accessed
- Cached until mesh geometry changes
"""
@property
def centroids(self):
"""
Triangle centroid positions.
Returns:
numpy.array: Centroid coordinates for each triangle (N, 3)
Notes:
- Automatically calculated when first accessed
- Centroids are geometric centers of triangles
"""
@property
def min_(self):
"""
Minimum coordinate values across all vertices.
Returns:
numpy.array: Minimum [x, y, z] coordinates (3,)
Notes:
- Automatically calculated when first accessed
- Cached until mesh geometry changes
"""
@property
def max_(self):
"""
Maximum coordinate values across all vertices.
Returns:
numpy.array: Maximum [x, y, z] coordinates (3,)
Notes:
- Automatically calculated when first accessed
- Cached until mesh geometry changes
"""
def update_min(self):
"""
Calculate minimum coordinate values across all vertices.
Notes:
- Updates the min_ property with computed values
- Called automatically when min_ property is accessed
- Can be called manually to refresh cached values
"""
def update_max(self):
"""
Calculate maximum coordinate values across all vertices.
Notes:
- Updates the max_ property with computed values
- Called automatically when max_ property is accessed
- Can be called manually to refresh cached values
"""
@property
def units(self):
"""
Unit normal vectors for each triangle.
Returns:
numpy.array: Normalized normal vectors (N, 3)
Notes:
- Automatically calculated when first accessed
- Used for surface area and orientation calculations
"""Calculate and work with triangle normal vectors for mesh analysis.
def update_normals(self, update_areas=True, update_centroids=True):
"""
Calculate normal vectors for all triangles.
Parameters:
- update_areas (bool): Whether to update surface areas
- update_centroids (bool): Whether to update centroid positions
Notes:
- Normals calculated using cross product of edge vectors
- Updates normals property with computed vectors
- Optionally updates dependent properties (areas, centroids)
"""
def get_unit_normals(self):
"""
Get normalized normal vectors.
Returns:
numpy.array: Unit normal vectors (N, 3)
Notes:
- Returns normalized versions of current normals
- Zero-length normals remain unchanged
- Does not modify the original normals property
"""import numpy as np
from stl import mesh
# Load a mesh
my_mesh = mesh.Mesh.from_file('model.stl')
# Calculate basic mass properties
volume, cog, inertia = my_mesh.get_mass_properties()
print(f"Volume: {volume:.3f}")
print(f"Center of gravity: {cog}")
print(f"Inertia matrix:\n{inertia}")
# Calculate with material density (aluminum: ~2700 kg/m³)
volume, mass, cog, inertia = my_mesh.get_mass_properties_with_density(2700)
print(f"Mass: {mass:.3f} kg")from stl import mesh
my_mesh = mesh.Mesh.from_file('model.stl')
# Quick validation using normal vectors
if my_mesh.is_closed():
print("Mesh is closed - volume calculations will be accurate")
else:
print("Warning: Mesh is not closed")
# More thorough validation (slower)
if my_mesh.is_closed(exact=True):
print("Mesh passes exact closure validation")
else:
print("Mesh has gaps or inconsistent edge orientations")from stl import mesh
import numpy as np
my_mesh = mesh.Mesh.from_file('model.stl')
# Calculate surface properties
my_mesh.update_areas()
my_mesh.update_centroids()
# Analyze surface area distribution
total_area = np.sum(my_mesh.areas)
mean_area = np.mean(my_mesh.areas)
print(f"Total surface area: {total_area:.3f}")
print(f"Average triangle area: {mean_area:.6f}")
# Find largest triangles
large_triangles = my_mesh.areas.flatten() > mean_area * 2
print(f"Large triangles: {np.sum(large_triangles)}")
# Analyze bounding box
bounds = my_mesh.max_ - my_mesh.min_
print(f"Bounding box: {bounds}")from stl import mesh
import numpy as np
my_mesh = mesh.Mesh.from_file('model.stl')
# Get normalized normal vectors
unit_normals = my_mesh.get_unit_normals()
# Analyze surface orientations
up_facing = unit_normals[:, 2] > 0.9 # Nearly vertical faces
print(f"Upward-facing triangles: {np.sum(up_facing)}")
# Check for degenerate triangles
normal_lengths = np.linalg.norm(my_mesh.normals, axis=1)
degenerate = normal_lengths < 1e-6
if np.any(degenerate):
print(f"Warning: {np.sum(degenerate)} degenerate triangles found")Install with Tessl CLI
npx tessl i tessl/pypi-numpy-stlevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10