This Python script:
import numpy as np
import vtk
from vtk.util.numpy_support import numpy_to_vtk
# Open a file, and create an unstructured grid.
filename = 'example.vtk'
writer = vtk.vtkUnstructuredGridWriter()
writer.SetFileName(filename)
grid = vtk.vtkUnstructuredGrid()
# Create 3 points
A,B,C = (0,0,0), (0,1,0), (1,0,0)
points = np.array( (A,B,C) )
vtk_points = vtk.vtkPoints()
vtk_points.SetData( numpy_to_vtk(points) )
grid.SetPoints(vtk_points)
# Cells: just 1 triangle
ntriangles = 1
npoints_per_triangle = 3
cells = np.array( [npoints_per_triangle, 0, 1, 2] )
vtk_cells = vtk.vtkCellArray()
id_array = vtk.vtkIdTypeArray()
id_array.SetVoidArray(cells, len(cells), 1)
vtk_cells.SetCells(ntriangles, id_array)
# Cell types: just 1 triangle.
cell_types = np.array( [vtk.VTK_TRIANGLE] , 'B')
vtk_cell_types = numpy_to_vtk(cell_types)
# Cell locations: the triangle is in `cells` at index 0.
cell_locations = np.array( [0,])
vtk_cell_locations = numpy_to_vtk(cell_locations, deep=1,
array_type=vtk.VTK_ID_TYPE)
# Cells: add to grid
grid.SetCells(vtk_cell_types, vtk_cell_locations, vtk_cells)
data = grid.GetCellData()
# Add scalar data to the triangle
data.SetActiveScalars('foo')
foo = np.array( [11.,] )
vtk_foo = numpy_to_vtk(foo)
vtk_foo.SetName("foo")
data.SetScalars(vtk_foo)
# Add other scalar data to the triangle
data.SetActiveScalars('bar')
bar = np.array( [12.,] )
vtk_bar = numpy_to_vtk(bar)
vtk_bar.SetName("bar")
data.SetScalars(vtk_bar)
# Write to file.
writer.SetInput(grid)
writer.Write()
print open(filename).read()
Produce the file:
# vtk DataFile Version 3.0
vtk output
ASCII
DATASET UNSTRUCTURED_GRID
POINTS 3 long
0 0 0 0 1 0 1 0 0
CELLS 1 4
3 0 1 2
CELL_TYPES 1
5
CELL_DATA 1
SCALARS bar double
LOOKUP_TABLE default
12
FIELD FieldData 1
foo 1 1 double
11
But I want CELL_DATA section to be:
CELL_DATA 1
SCALARS foo double
LOOKUP_TABLE default
11
SCALARS bar double
LOOKUP_TABLE default
12
Edit
Looking at the source code (WriteCellData, WriteScalarData and deeper), it seems impossible.