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
...
Where x,y,z are representing coordinates and v a scalar value at this point in space. x,y,z are randomly distributed.
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()
Trying this leads to the error.
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.
What should be the correct generation of the X,Y,Z-grid to interpolate on?
EDIT1: 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]
Does someone know if this could be simplified and/or how to write in a good python-style?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With