Python 投影外二维插值
假设我在网格上有一个3d对象Python 投影外二维插值,python,numpy,scipy,Python,Numpy,Scipy,假设我在网格上有一个3d对象V=V(a,b,c)。我想插值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 = n
V=V(a,b,c)
。我想插值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]))
然而,这一切看起来非常混乱和低效。有没有一种更像蟒蛇的方式来完成这一点?我已经更改了符号,以帮助我理解这个问题(我已经习惯了物理符号)。在三维空间中有一个标量场
V(x,y,z)
。
我们在此三维空间中定义一条参数化线:
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)