Python: Reading, Calculate, Write Out


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()

data = reader.GetOutput()

calc = vtkArrayCalculator()


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

writer = vtkUnstructuredGridWriter()

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?


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

Ok, thanks!


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


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.

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 ='bunny-0.1.vtk')
mesh['new array'] = np.full(mesh.n_points, 5)'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)
1 Like


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

thanks Bane, thats a really useful example.

as a pyVista “newbie”…
how would I do the exact same, import vtk, calc function, and export vtk
but I want a new function vnew = mag(U) + 10
where mag U is the velocity magnitude, say