繁体   English   中英

在python中将vtk UnstrucutredGrid写入文件

[英]writing vtk UnstrucutredGrid to file in python

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

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

我遵循了在此处使用 PolyVertex 对象可以找到的唯一示例。

并提出了以下课程:

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 没有响应,然后崩溃。

一个可以说更简单的方法是使用meshio (我的一个项目)。 您可以轻松编写各种格式的非结构化网格,例如 VTK/VTU。 安装

pip3 install meshio [--user]

(甚至不依赖于 vtk)并像使用它一样使用它

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
    )

我正在使用meshio模块的写入功能,但是“点”打印在单行而不是三列中。 有什么建议吗? 谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM