Python: Reading, Calculate, Write Out

#1

Hello,

I want to read in a VTK file, evaluate some function on it and write the file back, including the function result. All that, using the Python VTK interface.

So far I got:

from vtk import *

reader = vtkDataSetReader()
reader.SetFileName("bunny-0.1.vtk")
reader.ReadAllVectorsOn()
reader.ReadAllScalarsOn()
reader.Update()

data = reader.GetOutput()

calc = vtkArrayCalculator()
calc.SetInputData(data)

calc.SetFunction("5")
calc.SetResultArrayName("MyResults")
calc.Update()

# Gives: AttributeError: 'NoneType' object has no attribute 'GetPointData'
# print(calc.GetPolyDataOutput().GetPointData().GetArray("MyResults").getValue(10))

writer = vtkUnstructuredGridWriter()
writer.SetInputData(data)
writer.SetFileName("Output.vtk")
writer.Write()

It works so far, that it writes out the same geometry to Output.vtk, but without the additional field (here, constant 5).

What is the missing piece?

Thanks!

(Andras Lasso) #2

The problem is that you write the original input to file and not the filter output.

#3

Ok, thanks!

writer.SetInputData(calc.GetOutput())

did the trick.

Another follow up question:

when using the calculator expression: calc.SetFunction("coordsX+coordsY+coordsZ"), which works in interactive Paraview I get:

ERROR: In /build/paraview/src/ParaView-v5.6.0/VTK/Common/Misc/vtkFunctionParser.cxx, line 1244
vtkFunctionParser (0x55eb730b46f0): Syntax error: expecting a variable name;  see position 0

Thanks!

(Andras Lasso) #4

Check documentation of vtkArrayCalculator. If “follow-up” question is unrelated to the original question (as it was in this case) then please post it as a new topic.

Code of Conduct
(Bane Sullivan) #5

Hi @Horus, PyVista might be a tool of interest for you. PyVista provides a Pythonic interface to VTK - so you can focus on what’s important; the task at hand, not the nuances of setting up the VTK pipeline. In PyVista, your task would be:

import pyvista as pv
import numpy as np

mesh = pv.read('bunny-0.1.vtk')
mesh['new array'] = np.full(mesh.n_points, 5)
mesh.save('output.vtk')

Three tasks, three lines of code :wink: .

If you want to get fancier with summing the coordinates like you tried above, you could try:

mesh['new array'] = np.sum(mesh.points, axis=1)
(Cory Quammen (Kitware)) #6

@Horus

ParaView uses a subclass of vtkArrayCalculator to set up some variables to make them available in expressions, including coordsX, coordsY, and coordsZ. To do the same in your VTK program, you can add

calc.AddCoordinateScalarVariable("coordsX", 0)
calc.AddCoordinateScalarVariable("coordsY", 1)
calc.AddCoordinateScalarVariable("coordsZ", 2)

That should do the trick to make your expression work.

As a side note, if you are familiar with NumYy, you may be interested in VTK’s NumPy interface. An excellent tutorial on this interface starts with this blog post by Berk Geveci: Improved VTK – numpy integration.

1 Like