我想编写一个Python脚本,以生成类似于Paraview的下一个屏幕快照中右侧所示的图:
我有使用命令foamToVTK
生成的一系列文件:
VTK中是否有类似于Paraview的PlotOverLine
方法的功能?
PlotOverLine
在vtk中作为vtkProbeFilter
。最小工作示例:
import vtk
# Original data
source = vtk.vtkRTAnalyticSource()
# the line to plot over
line = vtk.vtkLineSource()
# filter
probeFilter = vtk.vtkProbeFilter()
probeFilter.SetInputConnection(line.GetOutputPort())
probeFilter.SetSourceConnection(source.GetOutputPort())
# rendering
plot = vtk.vtkXYPlotActor()
plot.AddDataSetInputConnection(probeFilter.GetOutputPort())
plot.SetTitle("My plot")
window = vtk.vtkRenderWindow()
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(window)
renderer = vtk.vtkRenderer()
renderer.AddActor2D(plot)
window.AddRenderer(renderer)
window.Render()
interactor.Start()
您可以在此处找到更复杂的(多图,颜色...)c ++示例:https://lorensen.github.io/VTKExamples/site/Cxx/Annotation/XYPlot/python API相同。
vtkUnstructuredGrid
(在这种情况下,使用256点的分辨率。)下面我附上我用来执行此操作的代码:
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import numpy as np
import vtk
from vtk.util.numpy_support import vtk_to_numpy
from os import walk, path, system
import pandas as pd
### Create the VTK files
system("foamToVTK")
### Initialization of variables
cnt=1
fig= plt.figure()
npts = 256 #dimensions of the grid
### Get the file names of each step of the simulation
(dirpath, dirnames, filenames) = next(walk('VTK'))
ids=[]
for dir in dirnames:
ids.append(int(dir.split("_")[1]))
ids = sorted(ids)
basename = dirnames[0].split("_")[0]
### Iteration of time steps
for id in ids[1:]:
### Read values from the file of this time step
filename = "%s/%s_%d/internal.vtu" % (dirpath, basename, id)
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName(filename)
reader.Update()
### Get the coordinates of nodes in the mesh using VTK methods
nodes_vtk_array= reader.GetOutput().GetPoints().GetData()
vtk_array = reader.GetOutput().GetPointData().GetArray('U') #Velocity (3 dimensions)
numpy_array = vtk_to_numpy(vtk_array)
nodes_nummpy_array = vtk_to_numpy(nodes_vtk_array)
x,y,z= nodes_nummpy_array[:,0] , nodes_nummpy_array[:,1] , nodes_nummpy_array[:,2]
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
### Define grid
xi = np.linspace(xmin, xmax, npts)
yi = np.linspace(ymin, ymax, npts)
### Grid the data
interpolated = griddata((x, y), numpy_array, (xi[None,:], yi[:,None]), method='cubic')
### Create the list of points
plotOverLine=[]
for point in range(len(interpolated[0])):
plotOverLine.append(interpolated[127][point])
### Update and plot the chart for this time step
df = pd.DataFrame(plotOverLine, columns=['X', 'Y', 'Z'])
plt.clf()
plt.title('Frame %d' % cnt)
plt.plot(df)
plt.legend(df.columns)
axes = plt.gca()
axes.set_ylim([-15,10])
plt.draw()
plt.pause(.05)
对于每个时间步,它都会更新并显示如下图: