Difference between revisions of "Python Programmable Filter"

From KitwarePublic
Jump to: navigation, search
(Examples)
(Examples: change link to page that was moved to follow naming convention)
(45 intermediate revisions by 7 users not shown)
Line 1: Line 1:
== ParaView3's python programmable filter. ==
+
The python programmable filter is a general purpose filter that the end user can program within the paraview GUI to manipulate datasets as needed. To use the filter, turn the '''PARAVIEW_ENABLE_PYTHON''' cmake option on. This causes the make process to wrap paraview's classes into python callable format.  
 
+
The python programmable filter is a general purpose filter that the end user can program within the paraview GUI to manipulate datasets as needed. To use the filter, turn the PARAVIEW_ENABLE_PYTHON_FILTER cmake option on. This causes the make process to wrap paraview's classes into python callable format. The wrapping process is identical to that for the PARAVIEW_EMBED_PYTHON option and the two share the same sets of libraries at run time.
+
  
 
The filter is a wrapper around VTK's vtkProgrammableFilter class and adds to it:
 
The filter is a wrapper around VTK's vtkProgrammableFilter class and adds to it:
Line 8: Line 6:
 
* the ability to easily change the output dataset type.
 
* the ability to easily change the output dataset type.
  
When the user selects "PythonScript" from the Filters menu, an empty programmable filter is created. The default behavior of the empty script is create a dataset if the same type as its input and to copy through the input dataset's structure. The GUI provides a selection menu where the user can choose from the five primary vtk dataset types for the output. The GUI also provides a text entry area where the user can type, edit or paste in a python script.
+
== Transform the input ==
 +
When the user selects '''Programmable Filter''' from the '''Filters''' menu, an empty programmable filter is created. The default behavior of the empty script is to create a dataset of the same type as its input and to copy through the input dataset's structure. The GUI provides a selection menu where the user can choose from the five primary VTK dataset types for the output. The GUI also provides a text entry area where the user can type, edit or paste in a python script.
  
 
The following figure shows a python script that modifies the geometry of its input dataset.
 
The following figure shows a python script that modifies the geometry of its input dataset.
[[Image:PyScriptFig1.jpg]]
 
  
#reads a poly data and modifies the geometry
+
This result is produced by the following python script set as the '''Script'''
pdi = self.GetPolyDataInput()
+
<table>
pdo = self.GetPolyDataOutput()
+
<tr>
newPts = paraview.vtkPoints()
+
<td valign="top">
numPts = pdi.GetNumberOfPoints()
+
<source lang="python">
for i in range(0, numPts):
+
pdi = self.GetPolyDataInput()
  coord = pdi.GetPoint(i)
+
pdo = self.GetPolyDataOutput()
  x,y,z = coord[:3]
+
newPoints = vtk.vtkPoints()
  x = x * 2
+
numPoints = pdi.GetNumberOfPoints()
  y = y * 0.5
+
for i in range(0, numPoints):
  z = 1
+
    coord = pdi.GetPoint(i)
  newPts.InsertPoint(i, x,y,z)
+
    x, y, z = coord[:3]
pdo.SetPoints(newPts)
+
    x = x * 1
 +
    y = y * 1
 +
    z = 1 + z*0.3
 +
    newPoints.InsertPoint(i, x, y, z)
 +
pdo.SetPoints(newPoints)
 +
</source>
 +
</td>
 +
<td>      </td>
 +
<td valign="top">
 +
[[Image:PyScriptFig1.jpg|400px]]
 +
</td>
 +
</tr>
 +
</table>
 +
 
 +
== Dealing with Composite Datasets==
 +
Readers such as Ensight, Exodus produce multiblock datasets. Here's the above squish script modified to work with multiblock datasets.
 +
 
 +
<table>
 +
<tr>
 +
<td>
 +
<source lang="python">
 +
def flatten(input, output):
 +
    # Copy the cells etc.
 +
    output.ShallowCopy(input)
 +
    newPoints = vtk.vtkPoints()
 +
    numPoints = input.GetNumberOfPoints()
 +
    for i in range(0, numPoints):
 +
        coord = input.GetPoint(i)
 +
        x, y, z = coord[:3]
 +
        x = x * 1
 +
        y = y * 1
 +
        z = 10 + 0.1*z
 +
        newPoints.InsertPoint(i, x, y, z)
 +
    output.SetPoints(newPoints)
 +
 
 +
input = self.GetInputDataObject(0, 0)
 +
output = self.GetOutputDataObject(0)
 +
 
 +
if input.IsA("vtkMultiBlockDataSet"):
 +
    output.CopyStructure(input)
 +
    iter = input.NewIterator()
 +
    iter.UnRegister(None)
 +
    iter.InitTraversal()
 +
    while not iter.IsDoneWithTraversal():
 +
        curInput = iter.GetCurrentDataObject()
 +
        curOutput = curInput.NewInstance()
 +
        curOutput.UnRegister(None)
 +
        output.SetDataSet(iter, curOutput)
 +
        flatten(curInput, curOutput)
 +
        iter.GoToNextItem();
 +
else:
 +
  flatten(input, output)
 +
</source>
 +
</td>
 +
<td valign="top">
 +
[[Image:PythonProgrammableFIlterMultiBlock.png|400px]]
 +
</td>
 +
</tr>
 +
</table>
  
 +
==Changing Data Type==
 +
Here we are taking in vtkPolyData and producing a vtkImageData from it. Note that the '''"Output Data Set Type"''' combo-box in the GUI has been changed to '''vtkImageData''' before hitting the ''Apply'' button.
  
 
The following figure shows a python script that produces an image data output with one cell per point in its input polygonal dataset.
 
The following figure shows a python script that produces an image data output with one cell per point in its input polygonal dataset.
[[Image:PyScriptFig2.jpg]]
+
<table>
 +
<tr>
 +
<td valign="top">
 +
<source lang="python">
 +
#this example creates an Nx1x1 imagedata output
 +
#and populates its cells with the point centered
 +
#scalars of the input dataset
  
#this example creates an Nx1x1 imagedata output
+
#get a hold of the input
#and populates its cells with the point centered
+
pdi = self.GetInput()
#scalars of the input dataset
+
numPts = pdi.GetNumberOfPoints()
 
   
 
   
#get a hold of the input
+
#create the output dataset with one cell per point
pdi = self.GetInput()
+
ido = self.GetOutput()
numPts = pdi.GetNumberOfPoints()
+
ido.SetDimensions(numPts+1,2,2)
+
ido.SetOrigin(-1,-1,-1)
#create the output dataset with one cell per point
+
ido.SetSpacing(.1,.1,.1)
ido = self.GetOutput()
+
ido.SetWholeExtent(0,numPts,0,1,0,1)
ido.SetDimensions(numPts 1,2,2)
+
ido.AllocateScalars()
ido.SetOrigin(-1,-1,-1)
+
 
ido.SetSpacing(.1,.1,.1)
+
#choose an input point data array to copy
ido.SetWholeExtent(0,numPts,0,1,0,1)
+
ivals = pdi.GetPointData().GetScalars()
ido.AllocateScalars()
+
ca = vtk.vtkFloatArray()
+
ca.SetName(ivals.GetName())
#choose an input point data array to copy
+
ca.SetNumberOfComponents(1)
ivals = pdi.GetPointData().GetScalars()
+
ca.SetNumberOfTuples(numPts)
ca = paraview.vtkFloatArray()
+
 
ca.SetName(ivals.GetName())
+
#add the new array to the output
ca.SetNumberOfComponents(1)
+
ido.GetCellData().AddArray(ca)
ca.SetNumberOfTuples(numPts)
+
 
#add the new array to the output
+
#copy the values over element by element
ido.GetCellData().AddArray(ca)
+
for i in range(0, numPts):
+
  ca.SetValue(i, ivals.GetValue(i))
#copy the values over element by element
+
 
for i in range(0, numPts):
+
</source>
  ca.SetValue(i, ivals.GetValue(i))
+
</td>
 +
<td valign="top">
 +
[[Image:PyScriptFig2.jpg|400px]]
 +
</td>
 +
</tr>
 +
</table>
 +
 
 +
==Generating Data (Programmable Source)==
 +
Along with processing data, python can be used to produce data i.e. act as a data source. Under the '''Sources''' menu, we have the '''Programmable Source''' which can be used to produce data using Python.
  
 +
Here's an example that generates a helix. Similar to the programmable filter, the output type must be choosen using the '''"Output Data Set Type"''' combo-box before hitting ''Apply''.
  
 
The following is a 'Programmable Source' example that generates a Helix curve.
 
The following is a 'Programmable Source' example that generates a Helix curve.
[[Image:HelixExample.jpg]]
+
<table>
 +
<tr>
 +
<td>
 +
<source lang="python">
 +
#This script generates a helix curve.
 +
#This is intended as the script of a 'Programmable Source'
 +
import math
  
#This script generates a helix curve.
+
numPts = 80.0 # Points along Helix
#This is intended as the script of a 'Programmable Source'
+
length = 8.0 # Length of Helix
import math
+
rounds = 3.0 # Number of times around
+
numPts = 80.0 # Points along Helix
+
length = 8.0 # Length of Helix
+
rounds = 3.0 # Number of times around
+
+
#Get a paraview.vtk.PolyData object for the output
+
pdo = self.GetPolyDataOutput()
+
+
#This will store the points for the Helix
+
newPts = paraview.vtkPoints()
+
for i in range(0, numPts):
+
    #Generate the Points along the Helix
+
    x = i*length/numPts
+
    y = math.sin(i*rounds*2*math.pi/numPts)
+
    z = math.cos(i*rounds*2*math.pi/numPts)
+
    #Insert the Points into the vtkPoints object
+
    #The first parameter indicates the reference.
+
    #value for the point. Here we add the sequentially.
+
    #Note that the first point is at index 0 (not 1).
+
    newPts.InsertPoint(i, x,y,z)
+
+
#Add the points to the vtkPolyData object
+
#Right now the points are not associated with a line -
+
#it is just a set of unconnected points. We need to
+
#create a 'cell' object that ties points together
+
#to make, in this case, a curve. This is done below.
+
#A 'cell' is just an object that tell how points are
+
#connected to make a 1D, 2D, or 3D object.
+
pdo.SetPoints(newPts)
+
+
#Make a vtkPolyLine which holds the info necessary
+
#to create a curve composed of line segments. This
+
#really just hold constructor data that will be passed
+
#to vtkPolyData to add a new line.
+
aPolyLine = paraview.vtkPolyLine()
+
+
#Indicate the number of points along the line
+
aPolyLine.GetPointIds().SetNumberOfIds(numPts)
+
for i in range(0,numPts):
+
    #Add the points to the line. The first value indicates
+
    #the order of the point on the line. The second value
+
    #is a reference to a point in a vtkPoints object. Depends
+
    #on the order that Points were added to vtkPoints object.
+
    #Note that this will not be associated with actual points
+
    #until it is added to a vtkPolyData object which holds a
+
    #vtkPoints object.
+
    aPolyLine.GetPointIds().SetId(i, i)
+
+
#Allocate the number of 'cells' that will be added. We are just
+
#adding one vtkPolyLine 'cell' to the vtkPolyData object.
+
pdo.Allocate(1, 1)
+
+
#Add the poly line 'cell' to the vtkPolyData object.
+
pdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
+
+
#The Helix is ready to plot! Click 'Apply'.
+
  
 +
#Get a vtk.PolyData object for the output
 +
pdo = self.GetPolyDataOutput()
  
An example that draws a double helix with connecting lines (like DNA). Provides an example of using multiple drawing objects 'cells' in the same vtkPolyData output object.
+
#This will store the points for the Helix
 +
newPts = vtk.vtkPoints()
 +
for i in range(0, numPts):
 +
  #Generate the Points along the Helix
 +
  x = i*length/numPts
 +
  y = math.sin(i*rounds*2*math.pi/numPts)
 +
  z = math.cos(i*rounds*2*math.pi/numPts)
 +
  #Insert the Points into the vtkPoints object
 +
  #The first parameter indicates the reference.
 +
  #value for the point. Here we add them sequentially.
 +
  #Note that the first point is at index 0 (not 1).
 +
  newPts.InsertPoint(i, x,y,z)
  
#This script generates a helix double.
+
#Add the points to the vtkPolyData object
#This is intended as the script of a 'Programmable Source'
+
#Right now the points are not associated with a line -
import math
+
#it is just a set of unconnected points. We need to
+
#create a 'cell' object that ties points together
numPts = 80.0 # Points along each Helix
+
#to make a curve (in this case). This is done below.
length = 8.0 # Length of each Helix
+
#A 'cell' is just an object that tells how points are
rounds = 3.0 # Number of times around
+
#connected to make a 1D, 2D, or 3D object.
phase_shift = math.pi/1.5 # Phase shift between Helixes
+
pdo.SetPoints(newPts)
+
 
#Get a paraview.vtk.PolyData object for the output
+
#Make a vtkPolyLine which holds the info necessary
pdo = self.GetPolyDataOutput()
+
#to create a curve composed of line segments. This
+
#really just hold constructor data that will be passed
#This will store the points for the Helix
+
#to vtkPolyData to add a new line.
newPts = paraview.vtkPoints()
+
aPolyLine = vtk.vtkPolyLine()
for i in range(0, numPts):
+
 
    #Generate Points for first Helix
+
#Indicate the number of points along the line
    x = i*length/numPts
+
aPolyLine.GetPointIds().SetNumberOfIds(numPts)
    y = math.sin(i*rounds*2*math.pi/numPts)
+
for i in range(0,numPts):
    z = math.cos(i*rounds*2*math.pi/numPts)
+
  #Add the points to the line. The first value indicates
    newPts.InsertPoint(i, x,y,z)
+
  #the order of the point on the line. The second value
   
+
  #is a reference to a point in a vtkPoints object. Depends
    #Generate Points for second Helix. Add a phase offset to y and z.
+
  #on the order that Points were added to vtkPoints object.
    y = math.sin(i*rounds*2*math.pi/numPts+phase_shift)
+
  #Note that this will not be associated with actual points
    z = math.cos(i*rounds*2*math.pi/numPts+phase_shift)
+
  #until it is added to a vtkPolyData object which holds a
    #Offset Helix 2 pts by 'numPts' to keep separate from Helix 1 Pts
+
  #vtkPoints object.
    newPts.InsertPoint(i+numPts, x,y,z)
+
  aPolyLine.GetPointIds().SetId(i, i)
+
 
#Add the points to the vtkPolyData object
+
#Allocate the number of 'cells' that will be added. We are just
pdo.SetPoints(newPts)
+
#adding one vtkPolyLine 'cell' to the vtkPolyData object.
+
pdo.Allocate(1, 1)
#Make two vtkPolyLine objects to hold curve construction data
+
 
aPolyLine1 = paraview.vtkPolyLine()
+
#Add the poly line 'cell' to the vtkPolyData object.
aPolyLine2 = paraview.vtkPolyLine()
+
pdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
+
 
#Indicate the number of points along the line
+
#The Helix is ready to plot! Click 'Apply'.
aPolyLine1.GetPointIds().SetNumberOfIds(numPts)
+
</source>
aPolyLine2.GetPointIds().SetNumberOfIds(numPts)
+
</td>
for i in range(0,numPts):
+
<td valign="top">
    #First Helix - use the first set of points
+
[[Image:HelixExample.jpg|400px]]
    aPolyLine1.GetPointIds().SetId(i, i)
+
</td>
    #Second Helix - use the second set of points
+
</tr>
    #(Offset the point reference by 'numPts').
+
</table>
    aPolyLine2.GetPointIds().SetId(i,i+numPts)
+
 
+
==Programmable Source: Double Helix==
#Allocate the number of 'cells' that will be added.  
+
An example that draws a double helix with connecting lines (like DNA). Provides an example of using multiple drawing objects 'cells' in the same vtkPolyData output object. The 'Output Data Set Type' should be set of 'vtkPolyData'.
#Two 'cells' for the Helix curves, and one 'cell'
+
 
#for every 3rd point along the Helixes.
+
<table>
links = range(0,numPts,3)
+
<tr>
pdo.Allocate(2+len(links), 1)
+
<td>
+
<source lang="python">
#Add the poly line 'cell' to the vtkPolyData object.
+
#This script generates a helix double.
pdo.InsertNextCell(aPolyLine1.GetCellType(), aPolyLine1.GetPointIds())
+
#This is intended as the script of a 'Programmable Source'
pdo.InsertNextCell(aPolyLine2.GetCellType(), aPolyLine2.GetPointIds())
+
import math
+
 
for i in links:
+
numPts = 80.0 # Points along each Helix
    #Add a line connecting the two Helixes.
+
length = 8.0 # Length of each Helix
    aLine = paraview.vtkLine()
+
rounds = 3.0 # Number of times around
    aLine.GetPointIds().SetId(0, i)
+
phase_shift = math.pi/1.5 # Phase shift between Helixes
    aLine.GetPointIds().SetId(1, i+numPts)
+
 
    pdo.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())
+
#Get a vtk.PolyData object for the output
 +
pdo = self.GetPolyDataOutput()
 +
 
 +
#This will store the points for the Helix
 +
newPts = vtk.vtkPoints()
 +
for i in range(0, numPts):
 +
  #Generate Points for first Helix
 +
  x = i*length/numPts
 +
  y = math.sin(i*rounds*2*math.pi/numPts)
 +
  z = math.cos(i*rounds*2*math.pi/numPts)
 +
  newPts.InsertPoint(i, x,y,z)
 +
 
 +
  #Generate Points for second Helix. Add a phase offset to y and z.
 +
  y = math.sin(i*rounds*2*math.pi/numPts+phase_shift)
 +
  z = math.cos(i*rounds*2*math.pi/numPts+phase_shift)
 +
  #Offset Helix 2 pts by 'numPts' to keep separate from Helix 1 Pts
 +
  newPts.InsertPoint(i+numPts, x,y,z)
 +
 
 +
#Add the points to the vtkPolyData object
 +
pdo.SetPoints(newPts)
 +
 
 +
#Make two vtkPolyLine objects to hold curve construction data
 +
aPolyLine1 = vtk.vtkPolyLine()
 +
aPolyLine2 = vtk.vtkPolyLine()
 +
 
 +
#Indicate the number of points along the line
 +
aPolyLine1.GetPointIds().SetNumberOfIds(numPts)
 +
aPolyLine2.GetPointIds().SetNumberOfIds(numPts)
 +
for i in range(0,numPts):
 +
  #First Helix - use the first set of points
 +
  aPolyLine1.GetPointIds().SetId(i, i)
 +
  #Second Helix - use the second set of points
 +
  #(Offset the point reference by 'numPts').
 +
  aPolyLine2.GetPointIds().SetId(i,i+numPts)
 +
 
 +
#Allocate the number of 'cells' that will be added.  
 +
#Two 'cells' for the Helix curves, and one 'cell'
 +
#for every 3rd point along the Helixes.
 +
links = range(0,numPts,3)
 +
pdo.Allocate(2+len(links), 1)
 +
 
 +
#Add the poly line 'cell' to the vtkPolyData object.
 +
pdo.InsertNextCell(aPolyLine1.GetCellType(), aPolyLine1.GetPointIds())
 +
pdo.InsertNextCell(aPolyLine2.GetCellType(), aPolyLine2.GetPointIds())
 +
 
 +
for i in links:
 +
  #Add a line connecting the two Helixes.
 +
  aLine = vtk.vtkLine()
 +
  aLine.GetPointIds().SetId(0, i)
 +
  aLine.GetPointIds().SetId(1, i+numPts)
 +
  pdo.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())
 +
 
 +
</source>
 +
</td>
 +
<td valign="top">
 +
[[Image:DoubleHelix.jpg|400px]]
 +
</td>
 +
</tr>
 +
</table>
  
 
== Examples ==
 
== Examples ==
  
[[Here are some more examples of simple ParaView 3 python filters.]]
+
[[ParaView/Simple ParaView 3 Python Filters|Here are some more examples of simple ParaView 3 python filters.]]
  
 
Paraview is built from VTK, and the python bindings for Paraview mirror the python bindings for VTK although the package names seem to be different. For example, there is a vtk.vtkLine in VTK which seems to behave the same as paraview.vtkLine in Paraview. While the online documentation for Paraview seems to be pretty limited, there is more extensive documentation with examples on the VTK documentation site. Examples are organized by class name and often include Python examples along with c++ and TCL examples:
 
Paraview is built from VTK, and the python bindings for Paraview mirror the python bindings for VTK although the package names seem to be different. For example, there is a vtk.vtkLine in VTK which seems to behave the same as paraview.vtkLine in Paraview. While the online documentation for Paraview seems to be pretty limited, there is more extensive documentation with examples on the VTK documentation site. Examples are organized by class name and often include Python examples along with c++ and TCL examples:
  
[[http://www.vtk.org/doc/release/5.0/html/c2_vtk_e_0.html VTK Example Code]]
+
[http://www.vtk.org/doc/release/5.0/html/c2_vtk_e_0.html VTK Example Code]
  
 
The examples list is a little hard to navigate. Perhaps an easier way to find examples is to go to the class list, look up the class you are interested in, and click on the class name which brings up the documentation for that class. Many of the class pages include an 'examples' section that links to code examples for the class. From the examples page you can choose the 'Python' example associated with the particular class (not every class has a Python example). The VTK class index can be found here:
 
The examples list is a little hard to navigate. Perhaps an easier way to find examples is to go to the class list, look up the class you are interested in, and click on the class name which brings up the documentation for that class. Many of the class pages include an 'examples' section that links to code examples for the class. From the examples page you can choose the 'Python' example associated with the particular class (not every class has a Python example). The VTK class index can be found here:
  
[[http://www.vtk.org/doc/release/5.0/html/annotated.html VTK Class Descriptions]]
+
[http://www.vtk.org/doc/release/5.0/html/annotated.html VTK Class Descriptions]
  
 
NOTE: You may not be able to directly copy the examples from the VTK documentation because the package names may not match Paraview package names, but with a little modification I have been able to get examples from VTK to work in Paraview.
 
NOTE: You may not be able to directly copy the examples from the VTK documentation because the package names may not match Paraview package names, but with a little modification I have been able to get examples from VTK to work in Paraview.
 +
 +
===Add Colors to a PolyData===
 +
<source lang="python">
 +
input = self.GetPolyDataInput();
 +
output =  self.GetPolyDataOutput();
 +
 +
colors = vtk.vtkUnsignedCharArray();
 +
colors.SetNumberOfComponents(3);
 +
colors.SetName("Colors");
 +
 +
numPoints = input.GetNumberOfPoints()
 +
for i in range(0, numPoints):
 +
    colors.InsertNextTuple3(255,0,0);
 +
 +
output=input
 +
output.GetPointData().AddArray(colors)
 +
</source>
 +
 +
===Center Data===
 +
<source lang="python">
 +
input = self.GetPolyDataInput()
 +
ooutput =  self.GetPolyDataOutput()
 +
 +
numPoints = input.GetNumberOfPoints()
 +
sumx = 0
 +
sumy = 0
 +
sumz = 0
 +
for i in range(0, numPoints):
 +
    coord = input.GetPoint(i)
 +
    x, y, z = coord[:3]
 +
    sumx = sumx + x
 +
    sumy = sumy + y
 +
    sumz = sumz + z
 +
 +
tx = -sumx/numPoints
 +
ty = -sumy/numPoints
 +
tz = -sumz/numPoints
 +
 +
transform = vtk.vtkTransform()
 +
transform.Translate(tx,ty,tz)
 +
transformFilter=vtk.vtkTransformPolyDataFilter()
 +
transformFilter.SetTransform(transform)
 +
transformFilter.SetInputConnection(input.GetProducerPort())
 +
transformFilter.Update()
 +
 +
output.ShallowCopy(transformFilter.GetOutput())
 +
</source>
 +
 +
===Center Data using numpy===
 +
<source lang="python">
 +
from paraview.vtk import dataset_adapter as DA
 +
 +
pdi = self.GetInputDataObject(0,0)
 +
pdo = self.GetOutputDataObject(0)
 +
pdo.CopyAttributes(pdi)
 +
 +
old_pts = inputs[0].Points
 +
new_pts = old_pts - mean(old_pts,axis=0)
 +
arr = DA.numpyTovtkDataArray(new_pts, 'newpts')
 +
pdo.GetPoints().SetData(arr)
 +
</source>
 +
{{ParaView/Template/Footer}}

Revision as of 09:30, 20 November 2011

The python programmable filter is a general purpose filter that the end user can program within the paraview GUI to manipulate datasets as needed. To use the filter, turn the PARAVIEW_ENABLE_PYTHON cmake option on. This causes the make process to wrap paraview's classes into python callable format.

The filter is a wrapper around VTK's vtkProgrammableFilter class and adds to it:

  • a string containing the user's script for the filter to execute
  • an instance of the python interpreter with the wrapped paraview libraries imported
  • the ability to easily change the output dataset type.

Transform the input

When the user selects Programmable Filter from the Filters menu, an empty programmable filter is created. The default behavior of the empty script is to create a dataset of the same type as its input and to copy through the input dataset's structure. The GUI provides a selection menu where the user can choose from the five primary VTK dataset types for the output. The GUI also provides a text entry area where the user can type, edit or paste in a python script.

The following figure shows a python script that modifies the geometry of its input dataset.

This result is produced by the following python script set as the Script

pdi = self.GetPolyDataInput()
pdo =  self.GetPolyDataOutput()
newPoints = vtk.vtkPoints()
numPoints = pdi.GetNumberOfPoints()
for i in range(0, numPoints):
    coord = pdi.GetPoint(i)
    x, y, z = coord[:3]
    x = x * 1
    y = y * 1
    z = 1 + z*0.3
    newPoints.InsertPoint(i, x, y, z)
pdo.SetPoints(newPoints)

PyScriptFig1.jpg

Dealing with Composite Datasets

Readers such as Ensight, Exodus produce multiblock datasets. Here's the above squish script modified to work with multiblock datasets.

def flatten(input, output):
    # Copy the cells etc.
    output.ShallowCopy(input)
    newPoints = vtk.vtkPoints()
    numPoints = input.GetNumberOfPoints()
    for i in range(0, numPoints):
        coord = input.GetPoint(i)
        x, y, z = coord[:3]
        x = x * 1
        y = y * 1
        z = 10 + 0.1*z
        newPoints.InsertPoint(i, x, y, z)
    output.SetPoints(newPoints)
 
input = self.GetInputDataObject(0, 0)
output = self.GetOutputDataObject(0)
 
if input.IsA("vtkMultiBlockDataSet"):
    output.CopyStructure(input)
    iter = input.NewIterator()
    iter.UnRegister(None)
    iter.InitTraversal()
    while not iter.IsDoneWithTraversal():
        curInput = iter.GetCurrentDataObject()
        curOutput = curInput.NewInstance()
        curOutput.UnRegister(None)
        output.SetDataSet(iter, curOutput)
        flatten(curInput, curOutput)
        iter.GoToNextItem();
else:
  flatten(input, output)

PythonProgrammableFIlterMultiBlock.png

Changing Data Type

Here we are taking in vtkPolyData and producing a vtkImageData from it. Note that the "Output Data Set Type" combo-box in the GUI has been changed to vtkImageData before hitting the Apply button.

The following figure shows a python script that produces an image data output with one cell per point in its input polygonal dataset.

#this example creates an Nx1x1 imagedata output
#and populates its cells with the point centered
#scalars of the input dataset
 
#get a hold of the input
pdi = self.GetInput()
numPts = pdi.GetNumberOfPoints()
 
#create the output dataset with one cell per point
ido = self.GetOutput()
ido.SetDimensions(numPts+1,2,2)
ido.SetOrigin(-1,-1,-1)
ido.SetSpacing(.1,.1,.1)
ido.SetWholeExtent(0,numPts,0,1,0,1)
ido.AllocateScalars()
 
#choose an input point data array to copy
ivals = pdi.GetPointData().GetScalars()
ca = vtk.vtkFloatArray()
ca.SetName(ivals.GetName())
ca.SetNumberOfComponents(1)
ca.SetNumberOfTuples(numPts)
 
#add the new array to the output
ido.GetCellData().AddArray(ca)
 
#copy the values over element by element
for i in range(0, numPts):
  ca.SetValue(i, ivals.GetValue(i))

PyScriptFig2.jpg

Generating Data (Programmable Source)

Along with processing data, python can be used to produce data i.e. act as a data source. Under the Sources menu, we have the Programmable Source which can be used to produce data using Python.

Here's an example that generates a helix. Similar to the programmable filter, the output type must be choosen using the "Output Data Set Type" combo-box before hitting Apply.

The following is a 'Programmable Source' example that generates a Helix curve.

#This script generates a helix curve.
#This is intended as the script of a 'Programmable Source'
import math
 
numPts = 80.0 # Points along Helix
length = 8.0 # Length of Helix
rounds = 3.0 # Number of times around
 
#Get a vtk.PolyData object for the output
pdo = self.GetPolyDataOutput()
 
#This will store the points for the Helix
newPts = vtk.vtkPoints()
for i in range(0, numPts):
   #Generate the Points along the Helix
   x = i*length/numPts
   y = math.sin(i*rounds*2*math.pi/numPts)
   z = math.cos(i*rounds*2*math.pi/numPts)
   #Insert the Points into the vtkPoints object
   #The first parameter indicates the reference.
   #value for the point. Here we add them sequentially.
   #Note that the first point is at index 0 (not 1).
   newPts.InsertPoint(i, x,y,z)
 
#Add the points to the vtkPolyData object
#Right now the points are not associated with a line - 
#it is just a set of unconnected points. We need to
#create a 'cell' object that ties points together
#to make a curve (in this case). This is done below.
#A 'cell' is just an object that tells how points are
#connected to make a 1D, 2D, or 3D object.
pdo.SetPoints(newPts)
 
#Make a vtkPolyLine which holds the info necessary
#to create a curve composed of line segments. This
#really just hold constructor data that will be passed
#to vtkPolyData to add a new line.
aPolyLine = vtk.vtkPolyLine()
 
#Indicate the number of points along the line
aPolyLine.GetPointIds().SetNumberOfIds(numPts)
for i in range(0,numPts):
   #Add the points to the line. The first value indicates
   #the order of the point on the line. The second value
   #is a reference to a point in a vtkPoints object. Depends
   #on the order that Points were added to vtkPoints object.
   #Note that this will not be associated with actual points
   #until it is added to a vtkPolyData object which holds a
   #vtkPoints object.
   aPolyLine.GetPointIds().SetId(i, i)
 
#Allocate the number of 'cells' that will be added. We are just
#adding one vtkPolyLine 'cell' to the vtkPolyData object.
pdo.Allocate(1, 1)
 
#Add the poly line 'cell' to the vtkPolyData object.
pdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
 
#The Helix is ready to plot! Click 'Apply'.

HelixExample.jpg

Programmable Source: Double Helix

An example that draws a double helix with connecting lines (like DNA). Provides an example of using multiple drawing objects 'cells' in the same vtkPolyData output object. The 'Output Data Set Type' should be set of 'vtkPolyData'.

#This script generates a helix double.
#This is intended as the script of a 'Programmable Source'
import math
 
numPts = 80.0 # Points along each Helix
length = 8.0 # Length of each Helix
rounds = 3.0 # Number of times around
phase_shift = math.pi/1.5 # Phase shift between Helixes
 
#Get a vtk.PolyData object for the output
pdo = self.GetPolyDataOutput()
 
#This will store the points for the Helix
newPts = vtk.vtkPoints()
for i in range(0, numPts):
   #Generate Points for first Helix
   x = i*length/numPts
   y = math.sin(i*rounds*2*math.pi/numPts)
   z = math.cos(i*rounds*2*math.pi/numPts)
   newPts.InsertPoint(i, x,y,z)
 
   #Generate Points for second Helix. Add a phase offset to y and z.
   y = math.sin(i*rounds*2*math.pi/numPts+phase_shift)
   z = math.cos(i*rounds*2*math.pi/numPts+phase_shift)
   #Offset Helix 2 pts by 'numPts' to keep separate from Helix 1 Pts
   newPts.InsertPoint(i+numPts, x,y,z)
 
#Add the points to the vtkPolyData object
pdo.SetPoints(newPts)
 
#Make two vtkPolyLine objects to hold curve construction data
aPolyLine1 = vtk.vtkPolyLine()
aPolyLine2 = vtk.vtkPolyLine()
 
#Indicate the number of points along the line
aPolyLine1.GetPointIds().SetNumberOfIds(numPts)
aPolyLine2.GetPointIds().SetNumberOfIds(numPts)
for i in range(0,numPts):
   #First Helix - use the first set of points
   aPolyLine1.GetPointIds().SetId(i, i)
   #Second Helix - use the second set of points
   #(Offset the point reference by 'numPts').
   aPolyLine2.GetPointIds().SetId(i,i+numPts)
 
#Allocate the number of 'cells' that will be added. 
#Two 'cells' for the Helix curves, and one 'cell'
#for every 3rd point along the Helixes.
links = range(0,numPts,3)
pdo.Allocate(2+len(links), 1)
 
#Add the poly line 'cell' to the vtkPolyData object.
pdo.InsertNextCell(aPolyLine1.GetCellType(), aPolyLine1.GetPointIds())
pdo.InsertNextCell(aPolyLine2.GetCellType(), aPolyLine2.GetPointIds())
 
for i in links:
   #Add a line connecting the two Helixes.
   aLine = vtk.vtkLine()
   aLine.GetPointIds().SetId(0, i)
   aLine.GetPointIds().SetId(1, i+numPts)
   pdo.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())

DoubleHelix.jpg

Examples

Here are some more examples of simple ParaView 3 python filters.

Paraview is built from VTK, and the python bindings for Paraview mirror the python bindings for VTK although the package names seem to be different. For example, there is a vtk.vtkLine in VTK which seems to behave the same as paraview.vtkLine in Paraview. While the online documentation for Paraview seems to be pretty limited, there is more extensive documentation with examples on the VTK documentation site. Examples are organized by class name and often include Python examples along with c++ and TCL examples:

VTK Example Code

The examples list is a little hard to navigate. Perhaps an easier way to find examples is to go to the class list, look up the class you are interested in, and click on the class name which brings up the documentation for that class. Many of the class pages include an 'examples' section that links to code examples for the class. From the examples page you can choose the 'Python' example associated with the particular class (not every class has a Python example). The VTK class index can be found here:

VTK Class Descriptions

NOTE: You may not be able to directly copy the examples from the VTK documentation because the package names may not match Paraview package names, but with a little modification I have been able to get examples from VTK to work in Paraview.

Add Colors to a PolyData

input = self.GetPolyDataInput();
output =  self.GetPolyDataOutput();
 
colors = vtk.vtkUnsignedCharArray();
colors.SetNumberOfComponents(3);
colors.SetName("Colors");
 
numPoints = input.GetNumberOfPoints()
for i in range(0, numPoints):
    colors.InsertNextTuple3(255,0,0);
 
output=input
output.GetPointData().AddArray(colors)

Center Data

input = self.GetPolyDataInput()
ooutput =  self.GetPolyDataOutput()
 
numPoints = input.GetNumberOfPoints()
sumx = 0
sumy = 0
sumz = 0
for i in range(0, numPoints):
    coord = input.GetPoint(i)
    x, y, z = coord[:3]
    sumx = sumx + x
    sumy = sumy + y
    sumz = sumz + z
 
tx = -sumx/numPoints
ty = -sumy/numPoints
tz = -sumz/numPoints
 
transform = vtk.vtkTransform()
transform.Translate(tx,ty,tz)
transformFilter=vtk.vtkTransformPolyDataFilter()
transformFilter.SetTransform(transform)
transformFilter.SetInputConnection(input.GetProducerPort())
transformFilter.Update()
 
output.ShallowCopy(transformFilter.GetOutput())

Center Data using numpy

from paraview.vtk import dataset_adapter as DA
 
pdi = self.GetInputDataObject(0,0)
pdo = self.GetOutputDataObject(0)
pdo.CopyAttributes(pdi)
 
old_pts = inputs[0].Points
new_pts = old_pts - mean(old_pts,axis=0)
arr = DA.numpyTovtkDataArray(new_pts, 'newpts')
pdo.GetPoints().SetData(arr)



ParaView: [Welcome | Site Map]