1#!/usr/bin/env python
2"""
3This file contains Python code illustrating the creation and manipulation of
4vtkTable objects.
5"""
6
7from __future__ import print_function
8from vtk import *
9
10#------------------------------------------------------------------------------
11# Some Helper Functions
12#------------------------------------------------------------------------------
13
14def add_row_to_vtkTable(vtk_table, new_row=None):
15    """ Python helper function to add a new row of data to a vtkTable object. """
16
17    # Just a couple of sanity checks.
18    if new_row == None:
19        print("ERROR: No data provided for new table row.")
20        return False
21    if len(new_row) != vtk_table.GetNumberOfColumns():
22        print("ERROR: Number of entries in new row does not match # of columns in table.")
23        return False
24
25    for i in range(vtk_table.GetNumberOfColumns()):
26        vtk_table.GetColumn(i).InsertNextValue( new_row[i] )
27    return True
28
29
30def get_vtkTableHeaders(vtk_table):
31    """ Returns the vtkTable headers (column names) as a Python list """
32    headers = []
33    for icol in range( vtk_table.GetNumberOfColumns() ):
34        headers.append( vtk_table.GetColumn(icol).GetName() )
35    return headers
36
37
38def get_vtkTableRow(vtk_table, row_number):
39    """ Returns a row from a vtkTable object as a Python list. """
40    row = []
41    for icol in range( vtk_table.GetNumberOfColumns() ):
42        row.append( vtk_table.GetColumn(icol).GetValue(row_number) )
43    return row
44
45
46def get_vtkTableAsDelimitedText(vtk_table, sep="\t"):
47    """ return a nicely formatted string version of a vtkTable """
48    s    = ""
49    hdrs = get_vtkTableHeaders(vtk_table)
50
51    for i in hdrs:
52        s += "%s%s"%(i,sep)
53    s = s.rstrip(sep)
54    s += "\n"
55
56    for irow in range(vtk_table.GetNumberOfRows()):
57        rowdata = get_vtkTableRow(vtk_table, irow)
58        for i in rowdata:
59            s += "%s%s"%(str(i),sep)
60        s = s.rstrip(sep)
61        s += "\n"
62    return s
63
64
65
66#------------------------------------------------------------------------------
67# Script Entry Point (i.e., main() )
68#------------------------------------------------------------------------------
69
70if __name__ == "__main__":
71    """ Main entry point of this python script """
72
73    #----------------------------------------------------------
74    # Create an empty table
75    T = vtkTable()
76
77    #----------------------------------------------------------
78    # Create Column 1 (IDs)
79    col1 = vtkIntArray()
80    col1.SetName("ID")
81    for i in range(1, 8):
82        col1.InsertNextValue(i)
83    T.AddColumn(col1)
84
85    #----------------------------------------------------------
86    # Create Column 2 (Names)
87    namesList = ['Bob', 'Ann', 'Sue', 'Bill', 'Joe', 'Jill', 'Rick']
88    col2 = vtkStringArray()
89    col2.SetName("Name")
90    for val in namesList:
91        col2.InsertNextValue(val)
92    T.AddColumn(col2)
93
94    #----------------------------------------------------------
95    # Create Column 3 (Ages)
96    agesList = [12, 25, 72, 11, 31, 36, 32]
97    col3 = vtkIntArray()
98    col3.SetName("Age")
99    for val in agesList:
100        col3.InsertNextValue(val)
101    T.AddColumn(col3)
102
103    #----------------------------------------------------------
104    # Add a row to the table
105    new_row = [8, "Luis", 68]
106
107    # we can't really use vtkTable.InsertNextRow() since it takes a vtkVariantArray
108    # as its argument (and the SetValue, etc. methods on that are not wrapped into
109    # Python) We can just append to each of the column arrays.
110
111    if not add_row_to_vtkTable(T, new_row):
112        print("Whoops!")
113
114    #----------------------------------------------------------
115    # Call PrintSelf() on a VTK object is done simply by printing the object
116    print(25*"=")
117    print("Calling PrintSelf():")
118    print(T)
119
120    #----------------------------------------------------------
121
122    # Here are a couple of ways to print out our table in Python using
123    # the helper functions that appear earlier in this script.
124    # The accessor methods used here can be adapted to do more interesting
125    # things with a vtkTable from within Python.
126
127    # print out our table
128    print(25*"=")
129    print("Rows as lists:")
130    print(get_vtkTableHeaders(T))
131    for i in range(T.GetNumberOfRows()):
132        print(get_vtkTableRow(T,i))
133
134    print("")
135    print(25*"=")
136    print("Delimited text:")
137    print(get_vtkTableAsDelimitedText(T))
138
139    print("vtkTable Python Example Completed.")
140