在曲面上插值点

问题描述 投票:0回答:1

我有一个函数 f(x,y),我知道 X 和 Y 的某些值。 然后,我有一个新函数 x,y= g(t),它生成一系列新的点 X 和 Y。对于这些点,使用我需要插值的预先计算的数据。

import numpy as np
import timeit
import matplotlib.pyplot as plt

def f(X,Y):
    return np.sin(X)+np.cos(Y)

def g(t):
    return 3*np.cos(t)-0.5, np.sin(5*t)-1

x=      np.linspace(-4,4,100)
y=      np.linspace(-4,4,100)
X, Y=   np.meshgrid(x,y)
Z=      f(X,Y)
   
t=      np.linspace(0,1,50)
x_t, y_t=   g(t)
    
plt.figure()
plt.imshow(Z, extent=(-4, 4, -4, 4), origin='lower')
plt.scatter(x_t,y_t)
plt.show()

换句话说,我需要使用之前计算的 Z 值获取显示的曲线,进行插值,因为在现实生活中我无法访问实际函数

非常感谢!

编辑:

我找到了一个完全符合我想要的功能的函数,但它产生了相同的错误。

import numpy as np
import timeit
import matplotlib.pyplot as plt
from scipy.interpolate import interpn
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

def f(X,Y):
    return np.sin(X)+np.cos(Y)

def g(t):
    return -np.cos(t), np.sin(2*t)

x=      np.linspace(-4,4,1001)
y=      np.linspace(-4,4,1001)
X, Y=   np.meshgrid(x,y)
Z=      f(X,Y)
grid= (x,y) 

t=      np.linspace(0,2*np.pi, 50)
x_t, y_t=   g(t)
xy_t=   np.stack([x_t, y_t], axis=-1)
Z_real= f(x_t, y_t)
Z_inter= interpn(grid, Z, xy_t)

fig= plt.figure()
gs=     fig.add_gridspec(1,2, hspace=0.1, wspace=0.1)
ax1=        fig.add_subplot(gs[0,0],projection="3d")
surf=   ax1.plot_surface(X,Y,Z, cmap=cm.jet, alpha=0.3)
ax1.scatter(x_t, y_t, Z_real)
fig.colorbar(surf, shrink=0.5,  aspect=5)

ax2=    fig.add_subplot(gs[0,1])
ax2.plot(t, Z_real)
ax2.plot(t, Z_inter, '+')

plt.show()

谁能告诉我我做错了什么?

python numpy interpolation
1个回答
0
投票

我最近分享了类似问题的解决方案,它也适用于您的案例。简而言之,

scipy.interpolate
提供了一系列 2D 插值选项。在本例中,我使用了
CloughTocher2DInterpolator
,但您也可以选择使用线性插值或其他方法。

import scipy.interpolate

z_interpolator = scipy.interpolate.CloughTocher2DInterpolator(
    np.dstack((X,Y)).reshape(-1,2),
    Z.reshape(-1,1))
z_interpolator(np.array(g(t)).T)
© www.soinside.com 2019 - 2024. All rights reserved.