gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:08:41 30 4
gpt4 key购买 nike

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

enter image description here

这些文件可能会变得很大,因此在使用 Python 读取它们时,高效地读取它们很重要。

最常用的格式之一是 msh来自 Gmsh .不幸的是,它的数据布局可以说不是最好的。示例文件:

$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) 是要跟随的节点数。

    在每个节点行中,第一个数字是索引(格式的一部分实际上不需要,呃),然后是三个空间坐标

    到目前为止,我还没有想出比 for 循环中的 islice 更好的东西,它非常慢。

# 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,如果能帮助我们快速读取这些数据,我们将不胜感激。

最佳答案

这是一个基于 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.])

关于python - 从文件的一部分快速读取格式化数据(Gmsh 网格格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41641505/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com