0
# Core I/O Functions
1
2
Essential functions for reading and writing mesh data across all supported formats, with automatic format detection and comprehensive error handling.
3
4
## Capabilities
5
6
### High-Level I/O Functions
7
8
Primary interface for mesh file operations that automatically detect file formats and handle various input/output scenarios.
9
10
```python { .api }
11
def read(filename, file_format=None):
12
"""
13
Read mesh data from file with automatic format detection.
14
15
Parameters:
16
- filename: str | Path | Buffer - File path or buffer to read from
17
- file_format: str | None - Optional explicit format specification
18
If None, format is auto-detected from file extension
19
Required when reading from buffer objects
20
21
Returns:
22
- Mesh - Complete mesh object containing points, cells, and associated data
23
24
Raises:
25
- ReadError - If file doesn't exist, format unsupported, or reading fails
26
- ValueError - If buffer provided without file_format specification
27
28
Examples:
29
>>> mesh = meshio.read("input.msh") # Auto-detect GMSH format
30
>>> mesh = meshio.read("data.vtk", file_format="vtk") # Explicit format
31
>>> with open("mesh.stl", "rb") as f:
32
... mesh = meshio.read(f, file_format="stl") # Buffer reading
33
"""
34
35
def write(filename, mesh, file_format=None, **kwargs):
36
"""
37
Write mesh data to file with automatic format detection.
38
39
Parameters:
40
- filename: str | Path | Buffer - File path or buffer to write to
41
- mesh: Mesh - Mesh object containing data to write
42
- file_format: str | None - Optional explicit format specification
43
If None, format is auto-detected from file extension
44
Required when writing to buffer objects
45
- **kwargs: dict - Format-specific options passed to writer
46
Examples: binary=True for STL, compression for VTK formats
47
48
Returns:
49
- None
50
51
Raises:
52
- WriteError - If writing fails or format unsupported
53
- ValueError - If buffer provided without file_format specification
54
55
Examples:
56
>>> meshio.write("output.vtk", mesh) # Auto-detect VTK format
57
>>> meshio.write("mesh.stl", mesh, binary=True) # Binary STL
58
>>> with open("output.ply", "wb") as f:
59
... meshio.write(f, mesh, file_format="ply") # Buffer writing
60
"""
61
62
def write_points_cells(filename, points, cells, point_data=None, cell_data=None,
63
field_data=None, point_sets=None, cell_sets=None,
64
file_format=None, **kwargs):
65
"""
66
Write mesh data directly from components without creating Mesh object.
67
68
Parameters:
69
- filename: str | Path | Buffer - File path or buffer to write to
70
- points: ArrayLike - Array of vertex coordinates with shape (n_points, dim)
71
where dim is typically 2 or 3
72
- cells: List[Tuple[str, ArrayLike]] | List[CellBlock] - Cell connectivity data
73
Format: [("triangle", triangles), ("quad", quads)] or list of CellBlock objects
74
- point_data: Dict[str, ArrayLike] | None - Point-associated data arrays
75
Keys are data names, values are arrays with shape (n_points,) or (n_points, n_components)
76
- cell_data: Dict[str, List[ArrayLike]] | None - Cell-associated data arrays
77
Keys are data names, values are lists of arrays (one per cell block)
78
- field_data: Dict[str, Any] | None - Global field data
79
Can contain scalar values, arrays, or other metadata
80
- point_sets: Dict[str, ArrayLike] | None - Named collections of point indices
81
Used for boundary conditions or material definitions
82
- cell_sets: Dict[str, List[ArrayLike]] | None - Named collections of cell indices
83
Keys are set names, values are lists of arrays (one per cell block type)
84
- file_format: str | None - Optional explicit format specification
85
- **kwargs: dict - Format-specific options
86
87
Returns:
88
- None
89
90
Raises:
91
- WriteError - If writing fails or invalid data provided
92
- ValueError - If inconsistent data shapes or missing required parameters
93
94
Examples:
95
>>> points = [[0, 0], [1, 0], [0, 1]]
96
>>> cells = [("triangle", [[0, 1, 2]])]
97
>>> meshio.write_points_cells("triangle.vtk", points, cells)
98
99
>>> # With data
100
>>> point_data = {"temperature": [0.5, 1.0, 0.8]}
101
>>> cell_data = {"material": [[1]]}
102
>>> meshio.write_points_cells("mesh.vtu", points, cells,
103
... point_data=point_data, cell_data=cell_data)
104
"""
105
```
106
107
### Error Handling
108
109
Specialized exception classes for mesh I/O operations with descriptive error messages.
110
111
```python { .api }
112
class ReadError(Exception):
113
"""
114
Exception raised when mesh reading operations fail.
115
116
Common scenarios:
117
- File not found or inaccessible
118
- Unsupported or unrecognized file format
119
- Corrupted or malformed mesh data
120
- Missing format specification for buffer reading
121
- Format-specific parsing errors
122
123
Examples:
124
>>> try:
125
... mesh = meshio.read("nonexistent.msh")
126
... except meshio.ReadError as e:
127
... print(f"Read failed: {e}")
128
"""
129
130
class WriteError(Exception):
131
"""
132
Exception raised when mesh writing operations fail.
133
134
Common scenarios:
135
- Permission denied or disk full
136
- Unsupported format for given data type
137
- Invalid mesh data (e.g., mismatched array sizes)
138
- Format-specific constraints violated
139
- Missing format specification for buffer writing
140
141
Examples:
142
>>> try:
143
... meshio.write("readonly.vtk", mesh)
144
... except meshio.WriteError as e:
145
... print(f"Write failed: {e}")
146
"""
147
```
148
149
## Usage Examples
150
151
### Basic File Operations
152
153
```python
154
import meshio
155
import numpy as np
156
157
# Read mesh from file
158
mesh = meshio.read("input.msh")
159
160
# Write mesh to different format
161
meshio.write("output.vtk", mesh)
162
163
# Explicit format specification
164
mesh = meshio.read("data", file_format="gmsh")
165
meshio.write("result", mesh, file_format="vtk")
166
```
167
168
### Direct Point/Cell Writing
169
170
```python
171
# Simple triangle mesh
172
points = np.array([
173
[0.0, 0.0, 0.0],
174
[1.0, 0.0, 0.0],
175
[0.0, 1.0, 0.0]
176
])
177
178
cells = [("triangle", [[0, 1, 2]])]
179
180
# Write without creating Mesh object
181
meshio.write_points_cells("triangle.stl", points, cells)
182
183
# With associated data
184
point_data = {
185
"temperature": np.array([20.0, 25.0, 22.0]),
186
"velocity": np.array([[0, 0, 0], [1, 0, 0], [0.5, 0.5, 0]])
187
}
188
189
cell_data = {
190
"material_id": [np.array([1])],
191
"density": [np.array([2.5])]
192
}
193
194
meshio.write_points_cells(
195
"mesh_with_data.vtu",
196
points,
197
cells,
198
point_data=point_data,
199
cell_data=cell_data
200
)
201
```
202
203
### Buffer I/O Operations
204
205
```python
206
# Reading from buffer
207
with open("mesh.stl", "rb") as buffer:
208
mesh = meshio.read(buffer, file_format="stl")
209
210
# Writing to buffer
211
import io
212
buffer = io.BytesIO()
213
meshio.write(buffer, mesh, file_format="vtk")
214
binary_data = buffer.getvalue()
215
```
216
217
### Format-Specific Options
218
219
```python
220
# STL binary format
221
meshio.write("mesh.stl", mesh, binary=True)
222
223
# VTK with compression
224
meshio.write("mesh.vtu", mesh, compression="zlib")
225
226
# GMSH with specific version
227
meshio.write("mesh.msh", mesh, file_format="gmsh", fmt_version="4.1")
228
```
229
230
### Error Handling Patterns
231
232
```python
233
import meshio
234
235
def safe_read_mesh(filename):
236
"""Safely read mesh with error handling."""
237
try:
238
return meshio.read(filename)
239
except meshio.ReadError as e:
240
print(f"Failed to read {filename}: {e}")
241
return None
242
except FileNotFoundError:
243
print(f"File {filename} not found")
244
return None
245
246
def convert_with_fallback(input_file, output_file, fallback_format=None):
247
"""Convert mesh with fallback format if auto-detection fails."""
248
try:
249
mesh = meshio.read(input_file)
250
meshio.write(output_file, mesh)
251
except meshio.ReadError:
252
if fallback_format:
253
mesh = meshio.read(input_file, file_format=fallback_format)
254
meshio.write(output_file, mesh)
255
else:
256
raise
257
```
258
259
## Format Auto-Detection
260
261
The core I/O functions automatically detect file formats based on file extensions:
262
263
```python
264
# These calls automatically detect format
265
mesh = meshio.read("data.msh") # GMSH format
266
mesh = meshio.read("data.vtk") # VTK format
267
mesh = meshio.read("data.stl") # STL format
268
mesh = meshio.read("data.ply") # PLY format
269
270
# Multi-extension detection
271
mesh = meshio.read("data.vtu.gz") # Compressed VTU format
272
```
273
274
## Performance Considerations
275
276
### Large File Handling
277
278
```python
279
# For very large meshes, consider format choice
280
# Binary formats are faster than ASCII
281
meshio.write("large_mesh.vtu", mesh, binary=True)
282
283
# Compression can reduce file size at cost of I/O speed
284
meshio.write("large_mesh.vtu", mesh, compression="lzma")
285
```
286
287
### Memory Efficiency
288
289
```python
290
# Use write_points_cells to avoid creating intermediate Mesh object
291
# for simple export scenarios
292
meshio.write_points_cells("output.stl", points, cells)
293
294
# Instead of:
295
# mesh = meshio.Mesh(points, cells)
296
# meshio.write("output.stl", mesh)
297
```