问题描述
我以下列方式在名为Testdata_interpolate.csv"的文件中有 ascii-Data
I have ascii-Data in a file called 'Testdata_interpolate.csv' in the following manner
x,y,z,v
val11,val12,val13,val14
val21,val22,val23,val24
...
其中 x,y,z 表示坐标,v 表示空间中该点的标量值.x,y,z 随机分布.
Where x,y,z are representing coordinates and v a scalar value at this point in space. x,y,z are randomly distributed.
为了进一步计算,v 应作为 V 插值到规则网格 (X,Y,Z) 上.因此,我尝试在该代码中使用 Phytons griddata:
For further calculations v shall be interpolated as V onto a regular grid (X,Y,Z). Therefor I tried to use Phytons griddata in that code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.interpolate import griddata as gd
#read values
f=open('Testdata_interpolate.csv','r')
headers = ["x","y","z","v"]
data = pd.read_csv(f, delimiter = ",",header=1,names=headers)
x=data.x
y=data.y
z=data.z
v=data.v
#generate new grid
X,Y,Z=np.mgrid[0:1:10j, 0:1:10j, 0:1:10j]
#interpolate "data.v" on new grid "inter_mesh"
V = gd((x,y,z), v, (X,Y,Z), method='nearest')
#Plot values
fig = plt.figure()
ax=fig.gca(projection='3d')
sc=ax.scatter(X, Y, Z, c=V, cmap=plt.hot())
plt.colorbar(sc)
plt.show()
尝试这个会导致错误.
ValueError: Buffer has wrong number of dimensions (expected 1, got 3)
由于那次失败,我试图用
Because of that failure i tried to generate the new grid with
X=np.linspace(0,1,10)
Y=np.linspace(0,1,10)
Z=np.linspace(0,1,10)
使用这种表示法执行插值,但我只有一条从体积的一个角到另一个角的(正确)内插值的直线.
Using this notation performs the interpolation but I have only a straight line of (correctly) interpolated values from one corner of the volume to the other.
要插入的 X、Y、Z 网格的正确生成应该是什么?
What should be the correct generation of the X,Y,Z-grid to interpolate on?
编辑 1:我找到了一个对我有用的解决方法.新网格 X,Y,Z 的生成通过以下代码完成:
I have found a work around, that works for me. The generation of the new grid X,Y,Z is done with this code:
xi,yi,zi=np.ogrid[0:1:10j, 0:1:10j, 0:1:20j]
X1=xi.reshape(xi.shape[0],)
Y1=yi.reshape(yi.shape[1],)
Z1=zi.reshape(zi.shape[2],)
ar_len=len(X1)*len(Y1)*len(Z1)+1
X=np.arange(ar_len,dtype=float)
Y=np.arange(ar_len,dtype=float)
Z=np.arange(ar_len,dtype=float)
l=0
for i in range(0,len(X1)):
for j in range(0,len(Y1)):
for k in range(0,len(Z1)):
l=l+1
X[l]=X1[i]
Y[l]=Y1[j]
Z[l]=Z1[k]
有人知道这是否可以简化和/或如何以良好的 Python 风格编写?
Does someone know if this could be simplified and/or how to write in a good python-style?
推荐答案
据我所知,您只需要将新网格转换为 1D.
As I understand, you just need to transform the new grid into 1D.
# generate new grid
X, Y, Z=np.mgrid[0:1:10j, 0:1:10j, 0:1:10j]
# interpolate "data.v" on new grid "inter_mesh"
V = gd((x,y,z), v, (X.flatten(),Y.flatten(),Z.flatten()), method='nearest')
这篇关于如何使用pythons griddata插入3d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!