Skip to content

Mesh exchange and visualization

Optional mesh generators, mesh-file exchange and visualization adapters.

All API families

Optional mesh exchange and generation for straight-sided planar triangles.

Dependencies are loaded only when the corresponding operation is requested. Physical curve groups may include material interfaces as well as boundaries.

MeshData dataclass

A triangular mesh with physical groups and optional point/cell fields.

face_tags maps positive physical IDs to mesh face indices; it includes interior interfaces. cell_tags is one nonnegative material ID per cell, with zero meaning unmarked. physical_names uses (dimension, ID) keys. Fields in cell_data refer only to triangles. Input arrays are copied.

boundary_tags: dict[int, tuple[int, ...]] property

Return physical groups restricted to external boundary faces.

__post_init__() -> None

Validate physical IDs, field dimensions and references to faces.

read_mesh(path: str | Path, *, file_format: str | None = None) -> MeshData

Read meshio-supported linear triangles and physical groups.

Point elements are ignored. Quadrilaterals, volume cells, higher-order cells, and nonzero Z coordinates are rejected rather than silently transformed. Arbitrary line fields are not part of the returned triangular cell fields.

write_mesh(path: str | Path, data: TriangleMesh | MeshData, *, point_data: Mapping[str, Any] | None = None, cell_data: Mapping[str, Any] | None = None, file_format: str | None = None) -> None

Export geometry and fields through meshio, preserving physical metadata.

VTU preserves physical IDs, names and numeric fields. Gmsh 2.2 also supports point fields; cell fields combined with tagged lines require VTU because of a meshio 5.3 reader limitation. Other formats are accepted for geometry alone. Multiple physical IDs on the same face cannot be represented by the scalar physical-tag field and are rejected. Existing fields may be replaced explicitly by name in the keyword mappings.

from_gmsh(model: Any | None = None) -> MeshData

Copy the current Gmsh model without modifying its session or mesh.

An explicit model-like object may be passed. Node tags need not be contiguous. Only first-order triangles, lines and points are supported.

unit_square_gmsh(size: float = 0.25) -> MeshData

Generate a triangular unit square with four named boundary groups.

A temporary model is removed afterwards. A caller-owned Gmsh session stays initialized and its previously current model is restored, including on error. Gmsh's process-global API is not safe for concurrent calls from threads.

from_netgen(source: Any) -> MeshData

Copy a two-dimensional first-order Netgen mesh and boundary/material IDs.

unit_square_netgen(maxh: float = 0.25) -> MeshData

Generate a Netgen triangular unit square with its native physical names.

Optional meshio exchange of linear tetrahedra and integer material/boundary tags.

TetraMeshData dataclass

Linear tetrahedral mesh with integer physical IDs and point/volume fields.

face_tags includes interior interfaces as well as external boundaries. Physical name strings and arbitrary surface fields are outside this format.

__post_init__() -> None

Validate lengths, physical IDs and real finite user fields.

read_tetra_mesh(path: str | Path, *, file_format: str | None = None) -> TetraMeshData

Read linear tetrahedra and tagged triangular faces without changing geometry.

Gmsh gmsh:physical IDs and the portable physical_tag field are accepted. Hexahedra, prisms, polyhedra and curved/high-order geometry are rejected. Lines and vertices may accompany a tetrahedral mesh but are not converted into volume elements.

write_tetra_mesh(path: str | Path, data: TetraMeshData | TetraMesh, *, file_format: str | None = None) -> None

Write tetrahedral geometry, tagged triangles and finite nodal/volume fields.

The VTK/VTU physical_tag arrays preserve integer physical IDs. Formats requiring Gmsh-specific model entities can instead be prepared directly through meshio; this writer does not manufacture CAD entity semantics.

Optional linear volume-mesh exchange with explicit native connectivity conventions.

VolumeMeshData dataclass

A native volume mesh with integer cell/face IDs and finite nodal/cell fields.

Geometry is linear tetrahedral, affine wedge, trilinear hexahedral or star-shaped polyhedral with planar faces. Integer face tags can describe internal material interfaces as well as the exterior. Physical-name strings and curved higher-order geometry are outside this exchange contract.

__post_init__() -> None

Validate the actual native geometry and every metadata-array length.

from_meshio(source: Any) -> VolumeMeshData

Import one linear volume family from a meshio-compatible in-memory object.

Wedge6 follows meshio's triangle/translate order, already shared by AffineMixedMesh. Hexahedron8 is explicitly permuted from VTK corner order into native lexicographic (x,y,z). PolyhedronN keeps each polygonal face; it is not replaced by independent triangular macrofaces. Mixed volume families and higher-order geometry are rejected rather than linearized. Triangular/quad/polygon boundary blocks and integer physical IDs are accepted.

read_volume_mesh(path: str | Path, *, file_format: str | None = None) -> VolumeMeshData

Read a linear volume mesh without silently pairing fields with other cells.

VTU polyhedron blocks must be ordered by increasing vertex count. This canonical layout keeps geometry and cell data aligned in meshio 5.3, whose reader sorts polyhedron field blocks independently of geometry blocks. write_volume_mesh emits that layout. In-memory from_meshio accepts any correctly paired block order.

to_meshio(data: VolumeMeshData | VolumeMesh) -> Any

Create a meshio Mesh carrying native linear geometry and lossless integer tags.

Per-cell pymhm_face_tags stores the local native face ordering, with zero padding for polyhedra with different face counts. This avoids adding surface cells to VTU polyhedron grids, which meshio cannot mix with surface blocks. It is an explicit PyMHM metadata convention, not a CAD physical-name model.

write_volume_mesh(path: str | Path, data: VolumeMeshData | VolumeMesh) -> None

Write VTU geometry and finite fields without discarding internal face tags.

VTU is required because other meshio formats do not uniformly preserve arbitrary-component per-face tag arrays and polyhedral connectivity.

Lazy native Gmsh and Netgen importers for supported three-dimensional geometry.

from_gmsh_3d(model: Any | None = None) -> VolumeMeshData

Copy first-order tetrahedra, wedges or hexahedra from a live Gmsh model.

Noncontiguous node/element tags and integer volume/surface physical IDs are resolved explicitly. Overlapping physical groups with conflicting IDs are rejected. Wedges must be affine; hexahedra use the native trilinear validity checks. A single volume family is required. The model/session is not modified.

unit_cube_gmsh(size: float = 0.35) -> VolumeMeshData

Generate a tetrahedral unit cube, material one and side IDs x0/x1/y0/y1/z0/z1=1..6.

The function owns only its temporary model. An existing Gmsh session and previously current model are preserved, including when import raises.

from_netgen_3d(source: Any) -> VolumeMeshData

Copy first-order Netgen tetrahedra and face-descriptor boundary/material IDs.

Element2D.index identifies a Netgen face descriptor; its bc value, rather than the descriptor index, is the exported physical boundary ID. Higher-order volume/surface geometry is rejected instead of dropping nodes.

unit_cube_netgen(maxh: float = 0.35) -> VolumeMeshData

Generate a Netgen tetrahedral unit cube and preserve its native integer IDs.

Optional PyVista conversion without merging broken finite-element fields.

The numerical core never imports PyVista. Converters return ordinary PyVista objects, so slicing, glyphs, export and interactive views use its native API. Structured arrays use explicit cell shapes and x-fastest (Fortran) ordering.

triangle_grid(mesh: TriangleMesh, *, point_data: Mapping[str, Any] | None = None, cell_data: Mapping[str, Any] | None = None) -> Any

Convert a planar triangular mesh and explicitly associated scalar/vector data.

Point arrays have shape (npoints,) or (npoints, 2|3). Cell arrays have the analogous cell shape. Two-component vectors receive a zero z component. Cell values remain cell data; no cell-to-point averaging occurs. Input geometry and fields are copied into the returned UnstructuredGrid.

broken_triangle_grid(local_meshes: Sequence[TriangleMesh], fields: Sequence[Any], degree: int = 1, *, name: str = 'field', subdivision: int | None = None, macro_mesh: TriangleMesh | None = None) -> Any

Sample broken P0–P4 scalar/vector fields without identifying coincident points.

For degree zero, each local array has one value per fine triangle. Higher degrees use :func:pymhm.fem.scalar.triangle.nodal_space ordering. Every fine triangle gets a separate display triangulation, preserving both macro and fine-cell jumps. Values are exact at sample points; straight display triangles are a visualization approximation of higher-order fields, not an error norm. subdivision defaults to twice the degree, or one for P0. Supplying the macro mesh stores its actual geometry for automatic overlays in plot_field.

macro_edges(mesh: TriangleMesh) -> Any

Return each actual macroface once as a planar PyVista PolyData line.

structured_cell_grid(cell_shape: Sequence[int], *, cell_data: Mapping[str, Any], spacing: Sequence[float] = (1.0, 1.0, 1.0), origin: Sequence[float] = (0.0, 0.0, 0.0)) -> Any

Create a uniform 2D/3D cell-centered image with unambiguous array ordering.

cell_shape=(nx, ny) or (nx, ny, nz) explicitly specifies geometry. Scalar fields have that shape; vectors append an axis of size two or three. The x/I index varies fastest in VTK storage (Fortran array order). No axis is reversed, no physical unit is converted, and no cell field is smoothed. A 2D grid has one plane of points, not a fictitious layer of volume cells. origin denotes the lower cell corner and spacing the physical cell widths. Both accept triples; XY pairs are also accepted for 2D grids.

plot_field(grid: Any, scalars: str, *, macro_mesh: TriangleMesh | None = None, off_screen: bool = False, window_size: tuple[int, int] = (1000, 700), **mesh_options: Any) -> Any

Create a composable Plotter with field colors and an actual macro overlay.

Return the open plotter; the caller owns show, screenshot and close. Embedded macro geometry from broken_triangle_grid is used unless macro_mesh overrides it. Scalar association defaults to cell data when both associations contain the same name; pass preference='point' to choose nodal data. Two-dimensional data use an XY camera. Rendering uses no geometry cleaning, point merging or cell-to-point conversion.

Source fingerprints for fresh acquisitions, independent of archived result manifests.

current_source_manifest(entries: Mapping[str, str], *, packages: Iterable[str] = ('pymhm',)) -> dict[str, str]

Include every imported-package owner when producing a fresh source manifest.

New labels describe actual current paths and bytes, including reference basis, local elimination and execution owners. Existing acquisition manifests must be validated separately and must never be relabeled through this producer.

file_digest(path: Path) -> str

Hash a source or archive in bounded memory, including large field files.

optional_file_digest(path: str | Path) -> str | None

Return SHA256 for an existing file, or None for unavailable metadata.

Use this for optional installation/development metadata such as a Pixi lockfile. Required scientific inputs must continue to use file_digest and its explicit filesystem errors. No placeholder digest is manufactured.

workspace_revision(directory: str | Path) -> str | None

Return the selected repository's actual HEAD, or None outside a repository.

A pip installation does not carry a Git checkout. This optional observation describes the workspace, not the identity of the installed numerical sources; source manifests retain the latter independently through their literal bytes.

workspace_git_dirty(directory: str | Path) -> bool | None

Report tracked/untracked workspace changes, or None without repository metadata.