Search code examples
vtkparaview

Using paraview filters in Python, Paraview python api


I have been using Paraview to visualize and analyse VTU files. I find the calculate gradient filter quite useful. I would like to know if there is a python API for Paraview which I can use to use this filter.

I'm looking for something like this.

import paraview as pv

MyFile = "Myfile0001.vtu"

Divergence = pv.filters.GradientOfUnstructuredDataset.(Myfile)


Solution

  • ParaView is fully scriptable in python. Each part of this doc has a 'do it in python' version.

    Whereas API doc does not necessary exist, you can use the Python Trace (in Tool menu), that records action from the GUI and save it as a python script.

    EDIT

    To get back data as an array, it needs some additional steps as ParaView works on a client/server mode. You should Fetch the data and then you can manipulate the vtkObject, extract the array and convert it to numpy.

    Something like

    from paraview.simple import *
    from vtk.numpy_interface import dataset_adapter as dsa
    
    gridvtu = XMLUnstructuredGridReader(registrationName='grid', FileName=['grid.vtu'])
    gradient = GradientOfUnstructuredDataSet(registrationName='Gradient', Input=gridvtu)
    vtk_grid = servermanager.Fetch(gradient)
    wraped_grid = dsa.WrapObject(vtk_grid)
    divergence_array = wraped_grid.PointData["Divergence"]
    

    Note that divergence_array is a numpy.ndarray

    You also can write pure vtk code, as in this example on SO