0
# Mesh Data Structures
1
2
Core classes for representing mesh geometry, topology, and associated data with methods for manipulation and data conversion.
3
4
## Capabilities
5
6
### Mesh Class
7
8
Primary class representing an unstructured mesh with points, cells, and associated data arrays.
9
10
```python { .api }
11
class Mesh:
12
"""
13
Central mesh representation with points, cells, and associated data.
14
15
Constructor:
16
Mesh(points, cells, point_data=None, cell_data=None, field_data=None,
17
point_sets=None, cell_sets=None, gmsh_periodic=None, info=None)
18
19
Parameters:
20
- points: ArrayLike - Array of vertex coordinates with shape (n_points, dim)
21
Typically 2D or 3D coordinates as numpy array
22
- cells: Dict[str, ArrayLike] | List[Tuple[str, ArrayLike] | CellBlock]
23
Cell connectivity data. Can be:
24
* Dictionary: {"triangle": triangles, "quad": quads}
25
* List of tuples: [("triangle", triangles), ("quad", quads)]
26
* List of CellBlock objects
27
- point_data: Dict[str, ArrayLike] | None - Point-associated data arrays
28
Keys are data names, values are arrays with shape (n_points,) or (n_points, n_components)
29
- cell_data: Dict[str, List[ArrayLike]] | None - Cell-associated data arrays
30
Keys are data names, values are lists of arrays (one per cell block)
31
- field_data: Dict[str, Any] | None - Global field data and metadata
32
- point_sets: Dict[str, ArrayLike] | None - Named collections of point indices
33
Used for boundary conditions, material definitions
34
- cell_sets: Dict[str, List[ArrayLike]] | None - Named collections of cell indices
35
Keys are set names, values are lists of arrays (one per cell block)
36
- gmsh_periodic: Any | None - GMSH-specific periodic boundary data
37
- info: Any | None - Additional mesh information and metadata
38
39
Attributes:
40
- points: np.ndarray - Vertex coordinates array
41
- cells: List[CellBlock] - List of cell blocks
42
- point_data: Dict[str, np.ndarray] - Point-associated data
43
- cell_data: Dict[str, List[np.ndarray]] - Cell-associated data
44
- field_data: Dict[str, Any] - Field data
45
- point_sets: Dict[str, np.ndarray] - Point sets
46
- cell_sets: Dict[str, List[np.ndarray]] - Cell sets
47
- gmsh_periodic: Any - GMSH periodic data
48
- info: Any - Additional information
49
"""
50
51
def write(self, path_or_buf, file_format=None, **kwargs):
52
"""
53
Write mesh to file or buffer.
54
55
Parameters:
56
- path_or_buf: str | Path | Buffer - Output destination
57
- file_format: str | None - Optional format specification
58
- **kwargs: dict - Format-specific options
59
60
Examples:
61
>>> mesh.write("output.vtk")
62
>>> mesh.write("mesh.stl", binary=True)
63
"""
64
65
def copy(self):
66
"""
67
Create deep copy of mesh object.
68
69
Returns:
70
- Mesh - Independent copy of the mesh
71
72
Examples:
73
>>> mesh_copy = mesh.copy()
74
>>> mesh_copy.points[0] = [999, 999, 999] # Won't affect original
75
"""
76
77
def get_cells_type(self, cell_type):
78
"""
79
Get all cells of specified type concatenated into single array.
80
81
Parameters:
82
- cell_type: str - Cell type identifier (e.g., "triangle", "quad", "tetra")
83
84
Returns:
85
- np.ndarray - Concatenated connectivity array for all cells of given type
86
Shape: (n_cells_of_type, nodes_per_cell)
87
Returns empty array if no cells of that type exist
88
89
Examples:
90
>>> triangles = mesh.get_cells_type("triangle")
91
>>> print(f"Triangle connectivity shape: {triangles.shape}")
92
"""
93
94
def get_cell_data(self, name, cell_type):
95
"""
96
Get cell data for specific cell type.
97
98
Parameters:
99
- name: str - Name of cell data array
100
- cell_type: str - Cell type to extract data for
101
102
Returns:
103
- np.ndarray - Concatenated data array for specified cell type
104
105
Examples:
106
>>> material_ids = mesh.get_cell_data("material", "tetra")
107
>>> temperatures = mesh.get_cell_data("temperature", "triangle")
108
"""
109
110
@property
111
def cells_dict(self):
112
"""
113
Dictionary view of cells organized by type.
114
115
Returns:
116
- Dict[str, np.ndarray] - Cell connectivity arrays keyed by cell type
117
All cells of same type are concatenated into single array
118
119
Examples:
120
>>> for cell_type, connectivity in mesh.cells_dict.items():
121
... print(f"{cell_type}: {connectivity.shape}")
122
"""
123
124
@property
125
def cell_data_dict(self):
126
"""
127
Dictionary view of cell data organized by name and type.
128
129
Returns:
130
- Dict[str, Dict[str, np.ndarray]] - Nested dictionary structure
131
Outer key: data name, Inner key: cell type, Value: data array
132
133
Examples:
134
>>> materials = mesh.cell_data_dict["material"]["tetra"]
135
>>> tri_temps = mesh.cell_data_dict["temperature"]["triangle"]
136
"""
137
138
@property
139
def cell_sets_dict(self):
140
"""
141
Dictionary view of cell sets organized by set name and cell type.
142
143
Returns:
144
- Dict[str, Dict[str, np.ndarray]] - Nested dictionary structure
145
Outer key: set name, Inner key: cell type, Value: indices array
146
147
Examples:
148
>>> boundary_tris = mesh.cell_sets_dict["boundary"]["triangle"]
149
>>> material_tets = mesh.cell_sets_dict["steel"]["tetra"]
150
"""
151
152
def cell_sets_to_data(self, data_name=None):
153
"""
154
Convert cell sets to integer cell data arrays.
155
156
Converts named cell sets into integer data where each cell gets
157
an integer ID corresponding to its set membership.
158
159
Parameters:
160
- data_name: str | None - Name for resulting cell data
161
If None, uses joined names of all cell sets
162
163
Side Effects:
164
- Adds integer array(s) to cell_data
165
- Clears cell_sets dictionary
166
167
Examples:
168
>>> mesh.cell_sets_to_data("regions")
169
>>> # Creates mesh.cell_data["regions"] with integer IDs
170
"""
171
172
def point_sets_to_data(self, join_char="-"):
173
"""
174
Convert point sets to integer point data array.
175
176
Parameters:
177
- join_char: str - Character used to join set names for data name
178
179
Side Effects:
180
- Adds integer array to point_data
181
- Clears point_sets dictionary
182
183
Examples:
184
>>> mesh.point_sets_to_data()
185
>>> # Creates point data with name like "boundary-inlet-outlet"
186
"""
187
188
def cell_data_to_sets(self, key):
189
"""
190
Convert integer cell data to cell sets.
191
192
Parameters:
193
- key: str - Name of integer cell data to convert
194
195
Side Effects:
196
- Creates cell sets based on unique integer values
197
- Removes the cell data array
198
199
Raises:
200
- RuntimeError - If cell data is not integer type
201
202
Examples:
203
>>> mesh.cell_data_to_sets("material_ids")
204
>>> # Creates cell sets like "material-1", "material-2", etc.
205
"""
206
207
def point_data_to_sets(self, key):
208
"""
209
Convert integer point data to point sets.
210
211
Parameters:
212
- key: str - Name of integer point data to convert
213
214
Side Effects:
215
- Creates point sets based on unique integer values
216
- Removes the point data array
217
218
Raises:
219
- RuntimeError - If point data is not integer type
220
221
Examples:
222
>>> mesh.point_data_to_sets("boundary_ids")
223
>>> # Creates point sets like "boundary-1", "boundary-2", etc.
224
"""
225
226
@classmethod
227
def read(cls, path_or_buf, file_format=None):
228
"""
229
Read mesh from file (deprecated).
230
231
Note: This method is deprecated. Use meshio.read() instead.
232
233
Parameters:
234
- path_or_buf: str | Path | Buffer - Input source
235
- file_format: str | None - Optional format specification
236
237
Returns:
238
- Mesh - Loaded mesh object
239
"""
240
```
241
242
### CellBlock Class
243
244
Container class representing a block of cells of the same topological type.
245
246
```python { .api }
247
class CellBlock:
248
"""
249
Represents a block of cells of the same type with connectivity data.
250
251
Constructor:
252
CellBlock(cell_type, data, tags=None)
253
254
Parameters:
255
- cell_type: str - Cell type identifier
256
Examples: "triangle", "quad", "tetra", "hexahedron", "line", "vertex"
257
Also supports higher-order elements: "triangle6", "tetra10", etc.
258
- data: List | np.ndarray - Cell connectivity data
259
For regular cells: 2D array with shape (n_cells, nodes_per_cell)
260
For polyhedron: list of variable-length sublists
261
- tags: List[str] | None - Optional list of string tags for the cell block
262
263
Attributes:
264
- type: str - Cell type string identifier
265
- data: np.ndarray | List - Connectivity data array or list
266
- dim: int - Topological dimension (0=vertex, 1=line, 2=surface, 3=volume)
267
- tags: List[str] - List of associated tags
268
"""
269
270
def __len__(self):
271
"""
272
Get number of cells in the block.
273
274
Returns:
275
- int - Number of cells
276
277
Examples:
278
>>> num_triangles = len(triangle_block)
279
"""
280
281
def __repr__(self):
282
"""
283
String representation showing cell block information.
284
285
Returns:
286
- str - Descriptive string with type, count, and tags
287
288
Examples:
289
>>> print(cell_block)
290
<meshio CellBlock, type: triangle, num cells: 1000, tags: ['boundary']>
291
"""
292
```
293
294
### Topological Dimension Mapping
295
296
Dictionary mapping cell type names to their topological dimensions.
297
298
```python { .api }
299
topological_dimension: Dict[str, int]
300
"""
301
Dictionary mapping cell type names to topological dimensions.
302
303
Keys include:
304
- 0D elements: "vertex"
305
- 1D elements: "line", "line3", "line4", ..., "line11"
306
- 2D elements: "triangle", "triangle6", "triangle10", "quad", "quad8", "polygon"
307
- 3D elements: "tetra", "tetra10", "hexahedron", "hexahedron20", "wedge", "pyramid"
308
- VTK Lagrange elements: "VTK_LAGRANGE_CURVE", "VTK_LAGRANGE_TRIANGLE", etc.
309
310
Examples:
311
>>> from meshio import topological_dimension
312
>>> print(topological_dimension["triangle"]) # 2
313
>>> print(topological_dimension["tetra"]) # 3
314
>>> print(topological_dimension["line"]) # 1
315
"""
316
```
317
318
## Usage Examples
319
320
### Creating Meshes
321
322
```python
323
import meshio
324
import numpy as np
325
326
# Simple triangle mesh
327
points = np.array([
328
[0.0, 0.0, 0.0],
329
[1.0, 0.0, 0.0],
330
[0.0, 1.0, 0.0],
331
[1.0, 1.0, 0.0]
332
])
333
334
cells = [
335
("triangle", [[0, 1, 2], [1, 3, 2]])
336
]
337
338
mesh = meshio.Mesh(points, cells)
339
340
# With associated data
341
point_data = {
342
"temperature": np.array([20.0, 25.0, 22.0, 27.0]),
343
"velocity": np.random.rand(4, 3)
344
}
345
346
cell_data = {
347
"material": [np.array([1, 2])], # One value per triangle
348
"density": [np.array([2.5, 3.1])]
349
}
350
351
mesh_with_data = meshio.Mesh(
352
points, cells,
353
point_data=point_data,
354
cell_data=cell_data
355
)
356
```
357
358
### Working with Multiple Cell Types
359
360
```python
361
# Mixed element mesh
362
points = np.random.rand(20, 3)
363
364
cells = [
365
("triangle", [[0, 1, 2], [1, 3, 2]]),
366
("quad", [[4, 5, 6, 7], [8, 9, 10, 11]]),
367
("tetra", [[12, 13, 14, 15]])
368
]
369
370
mesh = meshio.Mesh(points, cells)
371
372
# Access cells by type
373
triangles = mesh.get_cells_type("triangle")
374
quads = mesh.get_cells_type("quad")
375
tetras = mesh.get_cells_type("tetra")
376
377
print(f"Triangles shape: {triangles.shape}") # (2, 3)
378
print(f"Quads shape: {quads.shape}") # (2, 4)
379
print(f"Tetras shape: {tetras.shape}") # (1, 4)
380
381
# Dictionary access
382
cells_dict = mesh.cells_dict
383
for cell_type, connectivity in cells_dict.items():
384
print(f"{cell_type}: {len(connectivity)} cells")
385
```
386
387
### Cell and Point Sets
388
389
```python
390
# Define material regions and boundary conditions
391
cell_sets = {
392
"material_steel": [np.array([0, 2, 4]), np.array([])], # Triangle indices, no quads
393
"material_aluminum": [np.array([1, 3]), np.array([0, 1])] # Both triangles and quads
394
}
395
396
point_sets = {
397
"boundary": np.array([0, 1, 2, 3]),
398
"inlet": np.array([0, 1]),
399
"outlet": np.array([2, 3])
400
}
401
402
mesh = meshio.Mesh(
403
points, cells,
404
cell_sets=cell_sets,
405
point_sets=point_sets
406
)
407
408
# Convert sets to integer data
409
mesh.cell_sets_to_data("regions")
410
mesh.point_sets_to_data()
411
412
print("Cell data:", list(mesh.cell_data.keys()))
413
print("Point data:", list(mesh.point_data.keys()))
414
```
415
416
### Cell Data Manipulation
417
418
```python
419
# Create mesh with integer cell data
420
cell_data = {
421
"material_id": [np.array([1, 1, 2, 2]), np.array([3, 3])] # Per cell type
422
}
423
424
mesh = meshio.Mesh(points, cells, cell_data=cell_data)
425
426
# Convert back to sets
427
mesh.cell_data_to_sets("material_id")
428
print("Cell sets:", list(mesh.cell_sets.keys()))
429
430
# Get data for specific cell type
431
if mesh.cell_data:
432
steel_temps = mesh.get_cell_data("temperature", "triangle")
433
```
434
435
### Working with CellBlocks
436
437
```python
438
# Create CellBlock objects directly
439
triangle_block = meshio.CellBlock(
440
"triangle",
441
[[0, 1, 2], [1, 3, 2]],
442
tags=["boundary", "surface"]
443
)
444
445
quad_block = meshio.CellBlock(
446
"quad",
447
[[4, 5, 6, 7], [8, 9, 10, 11]],
448
tags=["volume"]
449
)
450
451
mesh = meshio.Mesh(points, [triangle_block, quad_block])
452
453
# Access CellBlock properties
454
for cell_block in mesh.cells:
455
print(f"Type: {cell_block.type}")
456
print(f"Count: {len(cell_block)}")
457
print(f"Dimension: {cell_block.dim}")
458
print(f"Tags: {cell_block.tags}")
459
```
460
461
### Field Data and Metadata
462
463
```python
464
# Add global field data
465
field_data = {
466
"simulation_time": 1.5,
467
"solver_version": "2.1.0",
468
"units": {"length": "meters", "time": "seconds"},
469
"constants": np.array([9.81, 1.0e-6]) # gravity, viscosity
470
}
471
472
mesh = meshio.Mesh(
473
points, cells,
474
field_data=field_data,
475
info={"created_by": "simulation_script.py", "date": "2024-01-01"}
476
)
477
```
478
479
### Mesh Inspection and Summary
480
481
```python
482
# Print mesh summary
483
print(mesh)
484
# Output:
485
# <meshio mesh object>
486
# Number of points: 20
487
# Number of cells:
488
# triangle: 2
489
# quad: 2
490
# tetra: 1
491
# Point data: temperature, velocity
492
# Cell data: material, density
493
# Field data: simulation_time, solver_version, units, constants
494
495
# Detailed inspection
496
print(f"Points shape: {mesh.points.shape}")
497
print(f"Number of cell blocks: {len(mesh.cells)}")
498
499
for i, cell_block in enumerate(mesh.cells):
500
print(f"Block {i}: {cell_block}")
501
```
502
503
### Data Validation
504
505
Meshio automatically validates data consistency during mesh construction:
506
507
```python
508
try:
509
# This will raise ValueError - mismatched point data length
510
bad_mesh = meshio.Mesh(
511
points=np.random.rand(10, 3), # 10 points
512
cells=[("triangle", [[0, 1, 2]])],
513
point_data={"temp": np.array([1, 2, 3])} # Only 3 values
514
)
515
except ValueError as e:
516
print(f"Validation error: {e}")
517
518
try:
519
# This will raise ValueError - mismatched cell data
520
bad_mesh = meshio.Mesh(
521
points=points,
522
cells=[("triangle", [[0, 1, 2]])], # 1 cell
523
cell_data={"material": [np.array([1, 2])]} # 2 values
524
)
525
except ValueError as e:
526
print(f"Validation error: {e}")
527
```