CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-meshio

I/O for many mesh formats

Pending
Overview
Eval results
Files

core-io.mddocs/

Core I/O Functions

Essential functions for reading and writing mesh data across all supported formats, with automatic format detection and comprehensive error handling.

Capabilities

High-Level I/O Functions

Primary interface for mesh file operations that automatically detect file formats and handle various input/output scenarios.

def read(filename, file_format=None):
    """
    Read mesh data from file with automatic format detection.
    
    Parameters:
    - filename: str | Path | Buffer - File path or buffer to read from
    - file_format: str | None - Optional explicit format specification
        If None, format is auto-detected from file extension
        Required when reading from buffer objects
        
    Returns:
    - Mesh - Complete mesh object containing points, cells, and associated data
    
    Raises:
    - ReadError - If file doesn't exist, format unsupported, or reading fails
    - ValueError - If buffer provided without file_format specification
    
    Examples:
    >>> mesh = meshio.read("input.msh")  # Auto-detect GMSH format
    >>> mesh = meshio.read("data.vtk", file_format="vtk")  # Explicit format
    >>> with open("mesh.stl", "rb") as f:
    ...     mesh = meshio.read(f, file_format="stl")  # Buffer reading
    """

def write(filename, mesh, file_format=None, **kwargs):
    """
    Write mesh data to file with automatic format detection.
    
    Parameters:
    - filename: str | Path | Buffer - File path or buffer to write to
    - mesh: Mesh - Mesh object containing data to write
    - file_format: str | None - Optional explicit format specification
        If None, format is auto-detected from file extension
        Required when writing to buffer objects
    - **kwargs: dict - Format-specific options passed to writer
        Examples: binary=True for STL, compression for VTK formats
        
    Returns:
    - None
    
    Raises:
    - WriteError - If writing fails or format unsupported
    - ValueError - If buffer provided without file_format specification
    
    Examples:
    >>> meshio.write("output.vtk", mesh)  # Auto-detect VTK format
    >>> meshio.write("mesh.stl", mesh, binary=True)  # Binary STL
    >>> with open("output.ply", "wb") as f:
    ...     meshio.write(f, mesh, file_format="ply")  # Buffer writing
    """

def write_points_cells(filename, points, cells, point_data=None, cell_data=None, 
                      field_data=None, point_sets=None, cell_sets=None, 
                      file_format=None, **kwargs):
    """
    Write mesh data directly from components without creating Mesh object.
    
    Parameters:
    - filename: str | Path | Buffer - File path or buffer to write to
    - points: ArrayLike - Array of vertex coordinates with shape (n_points, dim)
        where dim is typically 2 or 3
    - cells: List[Tuple[str, ArrayLike]] | List[CellBlock] - Cell connectivity data
        Format: [("triangle", triangles), ("quad", quads)] or list of CellBlock objects
    - point_data: Dict[str, ArrayLike] | None - Point-associated data arrays
        Keys are data names, values are arrays with shape (n_points,) or (n_points, n_components)
    - cell_data: Dict[str, List[ArrayLike]] | None - Cell-associated data arrays
        Keys are data names, values are lists of arrays (one per cell block)
    - field_data: Dict[str, Any] | None - Global field data
        Can contain scalar values, arrays, or other metadata
    - point_sets: Dict[str, ArrayLike] | None - Named collections of point indices
        Used for boundary conditions or material definitions
    - cell_sets: Dict[str, List[ArrayLike]] | None - Named collections of cell indices
        Keys are set names, values are lists of arrays (one per cell block type)
    - file_format: str | None - Optional explicit format specification
    - **kwargs: dict - Format-specific options
        
    Returns:
    - None
    
    Raises:
    - WriteError - If writing fails or invalid data provided
    - ValueError - If inconsistent data shapes or missing required parameters
    
    Examples:
    >>> points = [[0, 0], [1, 0], [0, 1]]
    >>> cells = [("triangle", [[0, 1, 2]])]
    >>> meshio.write_points_cells("triangle.vtk", points, cells)
    
    >>> # With data
    >>> point_data = {"temperature": [0.5, 1.0, 0.8]}
    >>> cell_data = {"material": [[1]]}
    >>> meshio.write_points_cells("mesh.vtu", points, cells, 
    ...                          point_data=point_data, cell_data=cell_data)
    """

Error Handling

Specialized exception classes for mesh I/O operations with descriptive error messages.

class ReadError(Exception):
    """
    Exception raised when mesh reading operations fail.
    
    Common scenarios:
    - File not found or inaccessible
    - Unsupported or unrecognized file format
    - Corrupted or malformed mesh data
    - Missing format specification for buffer reading
    - Format-specific parsing errors
    
    Examples:
    >>> try:
    ...     mesh = meshio.read("nonexistent.msh")
    ... except meshio.ReadError as e:
    ...     print(f"Read failed: {e}")
    """

class WriteError(Exception):
    """
    Exception raised when mesh writing operations fail.
    
    Common scenarios:
    - Permission denied or disk full
    - Unsupported format for given data type
    - Invalid mesh data (e.g., mismatched array sizes)
    - Format-specific constraints violated
    - Missing format specification for buffer writing
    
    Examples:
    >>> try:
    ...     meshio.write("readonly.vtk", mesh)
    ... except meshio.WriteError as e:
    ...     print(f"Write failed: {e}")
    """

Usage Examples

Basic File Operations

import meshio
import numpy as np

# Read mesh from file
mesh = meshio.read("input.msh")

# Write mesh to different format
meshio.write("output.vtk", mesh)

# Explicit format specification
mesh = meshio.read("data", file_format="gmsh")
meshio.write("result", mesh, file_format="vtk")

Direct Point/Cell Writing

# Simple triangle mesh
points = np.array([
    [0.0, 0.0, 0.0],
    [1.0, 0.0, 0.0], 
    [0.0, 1.0, 0.0]
])

cells = [("triangle", [[0, 1, 2]])]

# Write without creating Mesh object
meshio.write_points_cells("triangle.stl", points, cells)

# With associated data
point_data = {
    "temperature": np.array([20.0, 25.0, 22.0]),
    "velocity": np.array([[0, 0, 0], [1, 0, 0], [0.5, 0.5, 0]])
}

cell_data = {
    "material_id": [np.array([1])],
    "density": [np.array([2.5])]
}

meshio.write_points_cells(
    "mesh_with_data.vtu", 
    points, 
    cells,
    point_data=point_data,
    cell_data=cell_data
)

Buffer I/O Operations

# Reading from buffer
with open("mesh.stl", "rb") as buffer:
    mesh = meshio.read(buffer, file_format="stl")

# Writing to buffer
import io
buffer = io.BytesIO()
meshio.write(buffer, mesh, file_format="vtk")
binary_data = buffer.getvalue()

Format-Specific Options

# STL binary format
meshio.write("mesh.stl", mesh, binary=True)

# VTK with compression
meshio.write("mesh.vtu", mesh, compression="zlib")

# GMSH with specific version
meshio.write("mesh.msh", mesh, file_format="gmsh", fmt_version="4.1")

Error Handling Patterns

import meshio

def safe_read_mesh(filename):
    """Safely read mesh with error handling."""
    try:
        return meshio.read(filename)
    except meshio.ReadError as e:
        print(f"Failed to read {filename}: {e}")
        return None
    except FileNotFoundError:
        print(f"File {filename} not found")
        return None

def convert_with_fallback(input_file, output_file, fallback_format=None):
    """Convert mesh with fallback format if auto-detection fails."""
    try:
        mesh = meshio.read(input_file)
        meshio.write(output_file, mesh)
    except meshio.ReadError:
        if fallback_format:
            mesh = meshio.read(input_file, file_format=fallback_format)
            meshio.write(output_file, mesh)
        else:
            raise

Format Auto-Detection

The core I/O functions automatically detect file formats based on file extensions:

# These calls automatically detect format
mesh = meshio.read("data.msh")      # GMSH format
mesh = meshio.read("data.vtk")      # VTK format  
mesh = meshio.read("data.stl")      # STL format
mesh = meshio.read("data.ply")      # PLY format

# Multi-extension detection
mesh = meshio.read("data.vtu.gz")   # Compressed VTU format

Performance Considerations

Large File Handling

# For very large meshes, consider format choice
# Binary formats are faster than ASCII
meshio.write("large_mesh.vtu", mesh, binary=True)

# Compression can reduce file size at cost of I/O speed
meshio.write("large_mesh.vtu", mesh, compression="lzma")

Memory Efficiency

# Use write_points_cells to avoid creating intermediate Mesh object
# for simple export scenarios
meshio.write_points_cells("output.stl", points, cells)

# Instead of:
# mesh = meshio.Mesh(points, cells)
# meshio.write("output.stl", mesh)

Install with Tessl CLI

npx tessl i tessl/pypi-meshio

docs

cli.md

core-io.md

format-registration.md

formats.md

index.md

mesh-data.md

tile.json