如何使用 Python 对向量场进行插值?

How to interpolate a vector field with Python?

我有一个 2D 向量场(实际上它是 3D,但如果我们知道如何用 2D 做它,我想它会很容易推广到 3D)像这样:

import matplotlib.pyplot as plt, numpy as np
x = [0, 0, 1, 1, 2, 2, 0, 1, 2]
y = [1, 2, 1, 2, 1, 2, 1.5, 1.5, 1.5]
u = [0.5, -1, 0, 0, 0.25, 1, 0, 0, 0.75]
v = [1, 1, 1, 1, 1, 1, 1, 1, 1]
plt.quiver(x, y, u, v)
plt.show()

这个向量场如何平滑插值?

我知道如何使用 np.polyfit 但我不知道如何对矢量场进行插值。

示例:我想用数百个箭头插入 [0,2]x[1,2]

使用 NumPy 的 meshgrid and SciPy's interpolate.griddata 方法,这可能是一个快速可行的解决方案:

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate

x = [0, 0, 1, 1, 2, 2, 0, 1, 2]
y = [1, 2, 1, 2, 1, 2, 1.5, 1.5, 1.5]
u = [0.5, -1, 0, 0, 0.25, 1, 0, 0, 0.75]
v = [1, 1, 1, 1, 1, 1, 1, 1, 1]

plt.figure(1)
plt.quiver(x, y, u, v)

xx = np.linspace(0, 2, 10)
yy = np.linspace(1, 2, 10)
xx, yy = np.meshgrid(xx, yy)

points = np.transpose(np.vstack((x, y)))
u_interp = interpolate.griddata(points, u, (xx, yy), method='cubic')
v_interp = interpolate.griddata(points, v, (xx, yy), method='cubic')

plt.figure(2)
plt.quiver(xx, yy, u_interp, v_interp)
plt.show()

插值图的输出:

玩转 np.linspace 调用中要创建的点数,或多或少会产生箭头。

希望对您有所帮助!