smbinterp/bin/parse_gmsh.py

142 lines
3.3 KiB
Python
Executable File

#!/usr/bin/env python
import atexit
import os
import sys
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
import sys
import pickle
from itertools import combinations
import numpy as np
THREE_NODE_TRIANGLE = 2
class point(object):
def __init__(self, xyz):
self.index = index
self.xyz = xyz
self.faces = []
def __getitem__(self, i):
if isinstance(i, int):
if i == 0:
return self.xyz[0]
elif i == 1:
return self.xyz[1]
elif i == 2:
return self.xyz[2]
else:
raise IndexError("there are only (x,y,z)")
else:
raise TypeError("only point.x and point[0] access allowed")
def _getx(self):
return self.xyz[0]
x = property(_getx)
def _gety(self):
return self.xyz[1]
y = property(_gety)
def _getz(self):
return self.xyz[2]
z = property(_getz)
def __str__(self):
return '%s' % self.xyz
__repr__ = __str__
class face(object):
def __init__(self):
self.neighbors = []
self.points = []
if __name__ == '__main__':
if len(sys.argv) != 2:
print >> sys.stderr, "usage: %s <gmsh file>" % sys.argv[0]
sys.exit(1)
gmsh_file = open(sys.argv[1], 'r')
gmsh_file.readline() # $MeshFormat
format = gmsh_file.readline()
gmsh_file.readline() # $EndMeshFormat
gmsh_file.readline() # $Nodes
node_count = int(gmsh_file.readline())
points = []
nppoints = np.zeros((node_count, 3))
for i in xrange(node_count):
cur_line = gmsh_file.readline()
(index, x,y,z) = cur_line.split()
index = int(index) - 1
x = float(x)
y = float(y)
z = float(z)
nppoints[i][0] = x
nppoints[i][1] = y
nppoints[i][2] = z
points.append(point(nppoints[i]))
gmsh_file.readline() # $EndNodes
gmsh_file.readline() # $Elements
element_count = int(gmsh_file.readline())
faceobjs = {}
neighbors = {}
for i in xrange(element_count):
cur_line = gmsh_file.readline()
cur_line = cur_line.split()
cur_face_index, node_type, rest = (int(cur_line[0]),
int(cur_line[1]),
[int(j) for j in cur_line[2:]])
if(node_type == THREE_NODE_TRIANGLE):
points_for_cur_face = [i-1 for i in rest[rest[0]+1:]]
cur_face = face()
for cur_point in points_for_cur_face:
points[cur_point].faces.append(cur_face_index)
cur_face.points = points_for_cur_face
faceobjs[cur_face_index] = cur_face
edges = [tuple(sorted(i)) for i in combinations(points_for_cur_face, 2)]
# edge is two points
for edge in edges:
if edge in neighbors:
neighbors[edge].append(cur_face_index)
else:
neighbors[edge] = [cur_face_index]
for k,v in neighbors.iteritems():
if len(v) > 1:
faceobjs[v[0]].neighbors.append(v[1])
faceobjs[v[1]].neighbors.append(v[0])
pickle.dump([(p[0], p[1], p[2]) for p in points], open('/tmp/points.p', 'w'))
pickle.dump([f.points for f in faceobjs.itervalues()], open('/tmp/faces.p', 'w'))