快速读取部分文件的格式化数据(Gmsh网格格式)

问题描述 投票:4回答:2

我维护a little Python package,它可以在用于网格表示的不同格式之间进行转换

enter image description here

这些文件可能会变得非常大,因此在使用Python阅读它们时,有效地执行它们非常重要。

最常用的格式之一是来自mshGmsh。不幸的是,它的数据布局可能不是最好的。示例文件:

$MeshFormat
2.2 0 8
$EndMeshFormat
$Nodes
8
1 -0.5 -0.5 -0.5
2  0.5 -0.5 -0.5
3 -0.5  0.5 -0.5
4  0.5  0.5 -0.5
5 -0.5 -0.5  0.5
6  0.5 -0.5  0.5
7 -0.5  0.5  0.5
8  0.5  0.5  0.5
$EndNodes
$Elements
2
1 4 2 1 11 1 2 3 5
2 4 2 1 11 2 5 6 8
$EndElements
  • 对于$Nodes: 第一个数字(8)是要遵循的节点数。 在每个节点行中,第一个数字是索引(格式的静止部分实际上不需要,ugh),然后遵循三个空间坐标。 到目前为止,我没有在islice循环中提出任何比fors更好的东西,这非常慢。
# The first line is the number of nodes
line = next(islice(f, 1))
num_nodes = int(line)
#
points = numpy.empty((num_nodes, 3))
for k, line in enumerate(islice(f, num_nodes)):
    points[k, :] = numpy.array(line.split(), dtype=float)[1:]
    line = next(islice(f, 1))
assert line.strip() == '$EndNodes'
  • 对于$Elements: 第一个数字(2)是要遵循的元素数量。 在每个元素行中,第一个数字是索引,然后是元素类型的枚举(4用于四面体)。然后是这个元素的整数标记的数量(在这里每个情况下都是2,即111)。对应于元素类型,此行中的最后几个条目对应于构成元素的$Node索引 - 在四面体的情况下,最后四个条目。 由于标签的数量可以在元素之间变化(即,线到线),就像元素类型和节点索引的数量一样,每条线可以具有不同数量的整数。

对于$Nodes$Elements,我们非常感谢您快速阅读这些数据。

python numpy io mesh
2个回答
5
投票

这是一个基于NumPy的有点奇怪的实现:

f = open('foo.msh')
f.readline() # '$MeshFormat\n'
f.readline() # '2.2 0 8\n'
f.readline() # '$EndMeshFormat\n'
f.readline() # '$Nodes\n'
n_nodes = int(f.readline()) # '8\n'
nodes = numpy.fromfile(f,count=n_nodes*4, sep=" ").reshape((n_nodes,4))
# array([[ 1. , -0.5, -0.5, -0.5],
#   [ 2. ,  0.5, -0.5, -0.5],
#   [ 3. , -0.5,  0.5, -0.5],
#   [ 4. ,  0.5,  0.5, -0.5],
#   [ 5. , -0.5, -0.5,  0.5],
#   [ 6. ,  0.5, -0.5,  0.5],
#   [ 7. , -0.5,  0.5,  0.5],
#   [ 8. ,  0.5,  0.5,  0.5]])
f.readline() # '$EndNodes\n'
f.readline() # '$Elements\n'
n_elems = int(f.readline()) # '2\n'
elems = numpy.fromfile(f,sep=" ")[:-1] # $EndElements read as -1
# This array must be reshaped based on the element type(s)
# array([  1.,   4.,   2.,   1.,  11.,   1.,   2.,   3.,   5.,   2.,   4.,
#    2.,   1.,  11.,   2.,   5.,   6.,   8.])

3
投票

为什么不在Gmsh SDK中使用gmsh python API?例如,使用文件explore.py(位于SDK tarball中)来读取您的示例(我将其命名为test.msh)输出:

Info    : No current model available: creating one
Info    : Reading 'test.msh'...
Info    : 8 vertices
Info    : 2 elements
Info    : Done reading 'test.msh'
6 mesh nodes and 2 mesh elements on entity (3, 11) Discrete volume
 - Element type: Tetrahedron 4, order 1
   with 4 nodes in param coord:  [0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1.]

节点和元素存储为numpy数组。

© www.soinside.com 2019 - 2024. All rights reserved.