投影以外的二维插值

时间:2019-06-02 12:08:04

标签: python numpy scipy

假设我在网格V = V(a, b, c)上有一个3d对象。我想插值V(a, b + alpha*d, c+d)

换句话说,定义f(d) = V(a, b + alpha*d, c+d)。我想近似f。重要的是,我想将optimize.root应用于近似值,因此,我感谢f的高效计算。

例如,

gamma = 0.5
aGrid = np.linspace(5, 10, 30)
bGrid = np.linspace(4, 7, 40)
cGrid = np.linspace(0.1, 0.5, 20)
A, B, C = np.meshgrid(aGrid, bGrid, cGrid, indexing='ij')
V = A**2 + B*C
# define initial a, b, c
idx = (7, 8, 9)
a, b, c = A[idx], B[idx], C[idx]
# so V(a, b, c) = V[idx]

天真的方法是

g = scipy.interpolate.interp2d(bGrid, cGrid, V[7, ...])
f = lambda x: g(b + gamma*x, c + x)

和我的最终目标:

constant = 10
err = lambda x: f(x) - constant
scipy.optimize.root(err, np.array([5]))

但是,这一切看起来都很混乱且效率低下。有没有更Python化的方式来做到这一点?

1 个答案:

答案 0 :(得分:1)

我已经更改了表示法以帮助我理解问题(我已经习惯了物理表示法)。 3D空间中有一个标量字段V(x, y, z)。 我们在此3D空间中定义一条参数线:

f_{x0, y0, z0, v_x, v_y, v_z}(t) = (x0 + v_x*t, y0 + v_y*t, z0 + v_z*t)

它可以看作是从点(x0, y0, z0)开始并沿着具有速度向量(v_x, v_y, v_z)的直线运动的微粒的轨迹。

我们正在寻找时间t1,以使V( f(t1) )等于特定的给定值V0。这是问的问题吗?

import numpy as np
from scipy.interpolate import RegularGridInterpolator
from scipy.optimize import root_scalar
import matplotlib.pylab as plt

# build the field
aGrid = np.linspace(5, 10, 30)
bGrid = np.linspace(4, 7, 40)
cGrid = np.linspace(0.1, 0.5, 20)
A, B, C = np.meshgrid(aGrid, bGrid, cGrid, indexing='ij')
V = A**2 + B*C

# Build a continuous field by linear interpolation of the gridded data:
V_interpolated = RegularGridInterpolator((aGrid, bGrid, cGrid), V,
                                         bounds_error=False, fill_value=None)

# define the parametric line
idx = (7, 8, 9)
x0, y0, z0 = A[idx], B[idx], C[idx]
alpha = 0.5
v_x, v_y, v_z = 0, alpha, 1 

def line(t):
    xyz = (x0 + v_x*t, y0 + v_y*t, z0 + v_z*t) 
    return xyz

# Plot V(x,y,z) along this line (to check, is there a unique solution?)
t_span = np.linspace(0, 10, 23)
V_along_the_line = V_interpolated( line(t_span) )

plt.plot(t_span, V_along_the_line);
plt.xlabel('t'); plt.ylabel('V');

# Find t such that V( f(t) ) == V1
V1 = 80 
sol = root_scalar(lambda s: V_interpolated( line(s) ) - V1,
                  x0=.0, x1=10)

print(sol)

#      converged: True
#           flag: 'converged'
# function_calls: 8
#     iterations: 7
#           root: 5.385594973846983

# Get the coordinates of the solution point:
print("(x,y,z)_sol = ", line(sol.root))

# (6.206896551724138, 7.308182102308106, 5.675068658057509)