将vtk UnstrucutredGrid写入python

时间:2017-08-16 15:41:14

标签: python vtk paraview

我想将3D标量数据写入* .vtu文件(使用python)以便稍后在Paraview中拾取并以体积方式查看。我可以编写* .vtu文件,但Paraview在加载时会崩溃。我是否错误地使用了vtk API?

我的方法: (Python 2.7.12,VTK_MAJOR_VERSION 6,Paraview 5.0.1)

我遵循了使用PolyVertex对象here找到的唯一示例。

并提出以下课程:

import vtk
import numpy as np

class VtkPolyVertCloud(object):

    def __init__(self):

        self.points= vtk.vtkPoints()
        self.grid = vtk.vtkUnstructuredGrid()
        self.values = vtk.vtkDoubleArray()
        self.values.SetName('point_values_array')
        self.grid.SetPoints(self.points)
        self.grid.GetPointData().SetScalars(self.values)

    def add_polyVertex_cell(self, points, data):
        """
        adds points according to user-supplied numpy arrays

        @param points: numpy array of 3d point coords -- points.shape = (npoints, 3)
        @param data: scalar-valued data belonging to each point -- data.shape = (npoints,)
        """
        npts = points.shape[0]

        pv = vtk.vtkPolyVertex()
        pv.GetPointIds().SetNumberOfIds(npts)
        for idx, point in enumerate(points):
            pointID = self.points.InsertNextPoint(point)
            pv.GetPointIds().SetId(idx, pointID)
            self.values.InsertNextValue(data[idx])

        self.grid.InsertNextCell(pv.GetCellType(), pv.GetPointIds())

我实例化该类并尝试将简单的随机PolyVertex单元写入XML文件:

def test_vtkPolyVertexCloud_writeToFile():
    """ adds a set of polyvertices meant to represent a finite element """
    pc = vtku.VtkPolyVertCloud()
    points, data = np.random.rand(10, 3), np.random.rand(10)
    pc.add_polyVertex_cell(points, data)

    # write
    fn = 'test_PolyVertexCloud.vtu'
    writer = vtk.vtkUnstructuredGridWriter()
    writer.SetFileName(fn)
    writer.SetInputData(pc.grid)
    writer.Write()

在Paraview中打开文件时,Paraview Gui没有响应,然后崩溃。

1 个答案:

答案 0 :(得分:0)

使用meshio(属于我的项目)可能是一种更简单的方法。您可以轻松地以多种格式编写非结构化网格,例如VTK / VTU。使用

安装
pip3 install meshio [--user]

并像使用它

import meshio
import numpy

points = numpy.array([
    [0.0, 0.0, 0.0],
    [0.0, 1.0, 0.0],
    [0.0, 0.0, 1.0],
    ])
cells = {
    "triangle": numpy.array([
        [0, 1, 2]
        ])
    }
meshio.write_points_cells(
    "foo.vtu",
    points,
    cells,
    # Optionally provide extra data on points, cells, etc.
    # point_data=point_data,
    # cell_data=cell_data,
    # field_data=field_data
    )