vtkStringArray not being stored correctly in CellData for vtkPolyData object

Hi VTK community,

In the example below, a simple vtkPolyData object is constructed and two arrays — one numerical and another of strings — is passed to its cells. Upon subsequently retrieving the arrays, only the numerical one has any data in it (printing the string array results in None). Does anyone know why this is happening and how I might resolve the issue?

Best, Robert Collar

import vtk
import vtk.util.numpy_support as vtknumpy


points = vtk.vtkPoints()
points.SetNumberOfPoints(4)
line = vtk.vtkLine()
lines = vtk.vtkCellArray()

# create first line segment
points.SetPoint(0, 0, 0, 0)
line.GetPointIds().SetId(0, 0)

points.SetPoint(1, 1, 1, 1)
line.GetPointIds().SetId(1, 1)

lines.InsertNextCell(line)

# create second line segment
points.SetPoint(2, 1, 1, 1)
line.GetPointIds().SetId(0, 2)

points.SetPoint(3, 2, 2, 2)
line.GetPointIds().SetId(1, 3)

lines.InsertNextCell(line)

linesPolyData = vtk.vtkPolyData()
linesPolyData.SetPoints(points)
linesPolyData.SetLines(lines)

num_ids = vtknumpy.numpy_to_vtk([0,1]) # TODO: change to be a function of number of lines
num_ids.SetName("num id")
num_ids.SetNumberOfComponents(1)
linesPolyData.GetCellData().AddArray(num_ids)

str_ids = vtk.vtkStringArray()
str_ids.SetNumberOfValues(2)
str_ids.InsertValue(0, "a")
str_ids.InsertValue(1, "b")
str_ids.SetName("str id")
str_ids.SetNumberOfComponents(1)

linesPolyData.GetCellData().AddArray(str_ids)
print(linesPolyData.GetCellData().GetArray("num id"))
print(linesPolyData.GetCellData().GetArray("str id"))

Perhaps str_ids.SetNumberOfComponents(1)

Hi Todd, thanks for the suggestion, though adding that unfortunately doesn’t solve the problem. For future viewers, I’ve edited my initial post to include that line!

Use GetAbstractArray().

The GetArray() is restricted to numerical data, it can only return subclasses of vtkDataArray. For everything else it returns NULL

So a vtkStringArray must be added with AddArray(), but retrieved with GetAbstractArray().

This worked, thanks @dgobbi!

That’s intuitive. :thinking: