Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a .vtk file with python

Tags:

I've been given a legacy format vtk file (I think its an unstructured grid) and I'd like to read it in with python and output a .npy file instead, since I know how to deal with that.

The file is a dump from ATHENA and so has density, velocity, magnetic field along with the coordinates.

I'm very much a procedural programmer, so all these objects are confusing...

like image 202
Ben Jackel Avatar asked Jul 30 '12 18:07

Ben Jackel


People also ask

How do I visualize a VTK file?

If you cannot open your VTK file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a VTK file directly in the browser: Just drag the file onto this browser window and drop it.

What is a VTK file format?

VTK is a data directory which contains examples of the VTK file format used by the Visualization Toolkit. The Visualization Toolkit includes functions that can read and write graphics information in a variety of formats.


2 Answers

Here is the solution that I came up with, the trick was turning on ReadAllVectorsOn().

import numpy
from vtk import vtkStructuredPointsReader
from vtk.util import numpy_support as VN

reader = vtkStructuredPointsReader()
reader.SetFileName(filename)
reader.ReadAllVectorsOn()
reader.ReadAllScalarsOn()
reader.Update()

data = reader.GetOutput()

dim = data.GetDimensions()
vec = list(dim)
vec = [i-1 for i in dim]
vec.append(3)

u = VN.vtk_to_numpy(data.GetCellData().GetArray('velocity'))
b = VN.vtk_to_numpy(data.GetCellData().GetArray('cell_centered_B'))

u = u.reshape(vec,order='F')
b = b.reshape(vec,order='F')

x = zeros(data.GetNumberOfPoints())
y = zeros(data.GetNumberOfPoints())
z = zeros(data.GetNumberOfPoints())

for i in range(data.GetNumberOfPoints()):
        x[i],y[i],z[i] = data.GetPoint(i)

x = x.reshape(dim,order='F')
y = y.reshape(dim,order='F')
z = z.reshape(dim,order='F')
like image 112
Ben Jackel Avatar answered Sep 19 '22 06:09

Ben Jackel


meshio (a project of mine) knows the VTK format, so you could simply

pip install meshio

and then

import meshio
mesh = meshio.read('file.vtk')
# mesh.points, mesh.cells, ...
like image 27
Nico Schlömer Avatar answered Sep 19 '22 06:09

Nico Schlömer