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'
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.
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 = pv.read('bunny-0.1.vtk')
mesh['new array'] = np.full(mesh.n_points, 5)
Three tasks, three lines of code .
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)
ParaView uses a subclass of
vtkArrayCalculator to set up some variables to make them available in expressions, including
coordsZ. To do the same in your VTK program, you can add
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.