Vector field from three scalar components

Hello,

I have three vtkDoubleArray 3D scalar fields in my Python VTK pipeline:

bx = resample.GetOutput().GetPointData().GetArray("Bx")
by = resample.GetOutput().GetPointData().GetArray("By")
bz = resample.GetOutput().GetPointData().GetArray("Bz")

How do I create a single vector field from these three components, without cycling through all data points explicitly (these arrays are large)? I assume I would start with

vector = vtk.vtkFloatArray()
vector.SetName("B")
vector.SetNumberOfComponents(3)

How do I specify the components?

Thank you.

Probably you can use vtkImageAppendComponents.

You can also do this using numpy: get the 3 arrays as numpy arrays, concatenate them using numpy, and then use that to update a VTK array.

These vector operations are generally about 100x faster than iterating through elements one by one in Python.

Thank you, Andras. I went the numpy route:

... some code to read data from file ...

data = tableToPoints.GetOutput().GetPointData()
bx = data.GetArray("Bx")
by = data.GetArray("By")
bz = data.GetArray("Bz")

ax = vtk_to_numpy(bx).reshape(nx, ny, nz, order='F')
ay = vtk_to_numpy(by).reshape(nx, ny, nz, order='F')
az = vtk_to_numpy(bz).reshape(nx, ny, nz, order='F')

vtype = vtk.util.numpy_support.get_vtk_array_type(ax.dtype)
vcomponents = 3

imageData = vtk.vtkImageData()
imageData.SetSpacing(1.0, 1.0, 1.0)
imageData.SetOrigin(0.0, 0.0, 0.0)
imageData.SetDimensions(nz, ny, nx)
imageData.AllocateScalars(vtype, vcomponents)

aaa = np.array([ax,ay,az]).transpose()
vtk_data_array = numpy_to_vtk(num_array=aaa.ravel(), deep=True, array_type=vtype)
vtk_data_array.SetNumberOfComponents(3)
vtk_data_array.SetName("B")
imageData.GetPointData().SetScalars(vtk_data_array)

writer = vtk.vtkXMLImageDataWriter()
writer.SetInputData(imageData)
writer.SetFileName(fileout)
writer.Write()
2 Likes