1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| class FEDataModel: """有限元数据模型类"""
def __init__(self): self.nodes = [] self.elements = [] self.scalars = {} self.vectors = {} self.ugrid = vtk.vtkUnstructuredGrid() self.ugrid.Allocate(100)
def read_inp(self, filename): with open(filename) as f: node_flag, element_flag = False, False for line in f.readlines(): line = line.replace('\n', '').replace(' ', '') if '*ELEMENT' in line: node_flag, element_flag = False, True continue elif '*NODE' in line: node_flag, element_flag = True, False continue elif '*' in line: node_flag, element_flag = False, False continue if node_flag: self.nodes.append(list(map(lambda x: float(x), line.split(',')))[1:]) elif element_flag: self.elements.append(list(map(lambda x: int(x) - 1, line.split(',')))[1:])
nodes = vtk.vtkPoints() for i in range(0, len(self.nodes)): nodes.InsertPoint(i, self.nodes[i])
for i in range(0, len(self.elements)): if len(self.elements[i]) == 4: self.ugrid.InsertNextCell(vtk.VTK_TETRA, 4, self.elements[i]) elif len(self.elements[i]) == 6: self.ugrid.InsertNextCell(vtk.VTK_POLYGON, 6, self.elements[i]) elif len(self.elements[i]) == 3: self.ugrid.InsertNextCell(vtk.VTK_TRIANGLE, 3, self.elements[i]) else: print("FEDataModel构建中遇到错误单元类型!") self.ugrid.SetPoints(nodes)
def read_ntl(self, filename): with open(filename) as f: lines = f.readlines() attribute_name = ''.join(lines[0].split(' ')[1:-1]) scalar = [] for line in lines[4:]: line = line.replace('\n', '').split(' ') scalar.append(float(line[-1])) self.scalars[attribute_name] = scalar
scalars = vtk.vtkFloatArray() scalars.SetName(attribute_name) for i in range(0, len(scalar)): scalars.InsertTuple1(i, scalar[i]) self.ugrid.GetPointData().SetScalars(scalars)
def display(self): renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin)
colors = vtk.vtkNamedColors() ugridMapper = vtk.vtkDataSetMapper() ugridMapper.SetInputData(self.ugrid)
ugridActor = vtk.vtkActor() ugridActor.SetMapper(ugridMapper) ugridActor.GetProperty().SetColor(colors.GetColor3d("Peacock")) ugridActor.GetProperty().EdgeVisibilityOn()
renderer.AddActor(ugridActor) renderer.SetBackground(colors.GetColor3d("Beige"))
renderer.ResetCamera() renderer.GetActiveCamera().Elevation(60.0) renderer.GetActiveCamera().Azimuth(30.0) renderer.GetActiveCamera().Dolly(1.2) renWin.SetSize(640, 480) renWin.Render() iren.Start()
|