Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/meshio/gmsh/_gmsh40.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ def _read_nodes(f, is_ascii):
points[idx] = [float(x), float(y), float(z)]
tags[idx] = tag
idx += 1
# Only return the nodes that were actually read; the declared
# total_num_nodes can exceed the number of nodes in the blocks
# (cf. https://github.com/nschloe/meshio/issues/1562).
points = points[:idx]
tags = tags[:idx]
else:
# numEntityBlocks(unsigned long) numNodes(unsigned long)
num_entity_blocks, _ = np.fromfile(f, count=2, dtype=c_ulong)
Expand Down
7 changes: 6 additions & 1 deletion src/meshio/gmsh/_gmsh41.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,12 @@ def _read_nodes(f, is_ascii: bool, data_size):

_fast_forward_to_end_block(f, "Nodes")

return points, tags, dim_tags
# The declared total_num_nodes is not always trustworthy (see
# https://github.com/nschloe/meshio/issues/1562): the entity blocks can
# contain fewer nodes than declared. Only return the nodes that were
# actually read; the rest of the preallocated arrays is uninitialised
# memory whose garbage tags make _read_elements allocate absurd arrays.
return points[:idx], tags[:idx], dim_tags[:idx]


def _read_elements(
Expand Down
39 changes: 39 additions & 0 deletions tests/test_gmsh.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,45 @@ def test_gmsh41(mesh, binary, tmp_path):
helpers.write_read(tmp_path, writer, meshio.gmsh.read, mesh, 1.0e-15)


def test_gmsh41_overdeclared_num_nodes(tmp_path):
# Regression test for https://github.com/nschloe/meshio/issues/1562:
# the $Nodes header declares 10 nodes, but the entity block only
# contains 4. The reader must return exactly those 4 nodes instead of
# padding the mesh with uninitialised memory (whose garbage tags made
# _read_elements try to allocate absurdly large arrays).
msh = """$MeshFormat
4.1 0 8
$EndMeshFormat
$Nodes
1 10 1 4
0 1 0 4
1
2
3
4
0.0 0.0 0.0
1.0 0.0 0.0
1.0 1.0 0.0
0.0 1.0 0.0
$EndNodes
$Elements
1 1 1 1
0 1 15 1
1 1
$EndElements
"""
filepath = tmp_path / "overdeclared.msh"
filepath.write_text(msh)
mesh = meshio.read(filepath)
assert mesh.points.shape == (4, 3)
np.testing.assert_allclose(
mesh.points,
[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]],
)
assert len(mesh.cells) == 1
np.testing.assert_array_equal(mesh.cells[0].data, [[0]])


def test_generic_io(tmp_path):
helpers.generic_io(tmp_path / "test.msh")
# With additional, insignificant suffix:
Expand Down