numpy数组到非均匀直线网格上的tvtk / vtk向量

时间:2015-12-27 05:46:37

标签: python vtk mayavi

实际上,我的最终任务是绘制非均匀直线数据的流线。

我的现场数据存储在一个巨大的数组myData中,形状为Nx * Ny * Nz * nComponents。我的坐标分别存储在形状为Nx,Ny和Nz的1d阵列中。

我能够使用以下代码绘制标量数据:

from tvtk.api import tvtk
r = tvtk.RectilinearGrid()
# getCoordinates is my custom function
# to get 1d arrays of nonuniform grid coordinates
r.x_coordinates = getCoordinates('x')
r.y_coordinates = getCoordinates('y')
r.z_coordinates = getCoordinates('z')
# get a component, in this case, the density, 'rho'
fldIndex = 0
fldName = 'rho'
s = myData[:, :, :, fldIndex]
# set scalar, I have to pass the parameter 'F' to ravel
r.point_data.scalars = s.ravel(order='F')
r.point_data.scalars.name = fldName
r.dimensions = s.shape
from mayavi import mlab
surf = mlab.pipeline.iso_surface(r, opacity=0.1)

现在我想向r添加一个矢量velocity,以便我可以将它用作

的输入
vnorm = mlab.pipeline.extract_vector_norm(velocity)
vline = mlab.pipeline.streamline(vnorm) # plus many tuning parameters

这里,速度的三个分量存储在myData [:,:,1],myData [:,:,2],myData [:,:3]中。我该如何利用它们?我天真地尝试了以下代码,但无法获得任何流线

# the following code did not lead to correct streamline
u = myData[:,:,:,1].ravel(order='F')
v = myData[:,:,:,2].ravel(order='F')
w = myData[:,:,:,3].ravel(order='F')
import numpy as np
vec = np.array([u,v,w]).T # now vec is NOT contiguous and
                          # NOT accepted by the internal numpy_to_vtk
                          # conversion
r.point_data.vectors = vec
r.point_data.vectors.name = 'velocity'

PS:最初我尝试使用mayavi的vector_field。但是,它取决于vtk.ImageData,即它只支持统一网格。

1 个答案:

答案 0 :(得分:0)

以下代码可以使用

from tvtk.api import tvtk
r = tvtk.RectilinearGrid()
r.x_coordinates = getCoordinates('x')
r.y_coordinates = getCoordinates('y')
r.z_coordinates = getCoordinates('z')
# vec is a numpy array of the right shape and storage layout
import numpy as np
vec = np.zeros([size, 3],dtype='float64') #FIXME: 
vec[:, 0] = myData[:,:,:,1].ravel(order='F')
vec[:, 1] = myData[:,:,:,2].ravel(order='F')
vec[:, 2] = myData[:,:,:,3].ravel(order='F')
# vec from the following code also works;
# the key is to generate a contiguous array, which was done by 'zeros'
# above, and is done by ascontiguousarray below
# vec = np.ascontiguousarray( np.array([
#    myData[:,:,:,1].ravel(order='F'),
#    myData[:,:,:,2].ravel(order='F'),
#    myData[:,:,:,3].ravel(order='F')]).T )
# use numpy_to_vtk to get the vtk array
r.point_data.vectors = vec
r.point_data.vectors.name = 'velocity'
Nx,Ny,Nz,Ncomp = MyData.shape
r.dimensions = (Nx, Ny, Nz)

# make streamline
from mayavi import mlab
magnitude = mlab.pipeline.extract_vector_norm(r)
field_lines = mlab.pipeline.streamline(magnitude) # streamline options neglected