Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate a vector field with Python?

I have a 2D vector field (in fact it's a 3D, but if we know how to do it with 2D, I think it will be easy to generalize to 3D) like this:

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()

enter image description here

How to interpolate smoothly this vector field?

I know how to use np.polyfit but I don't see how to do an interpolation for a vector field.

Example: I would like to interpolate [0,2]x[1,2] with hundreds of arrows.

like image 558
Basj Avatar asked Oct 28 '25 23:10

Basj


1 Answers

Using NumPy's meshgrid and SciPy's interpolate.griddata methods, this might be a fast and feasible solution:

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()

Output of the interpolated plot:

Output

Playing around with the number of points to be created within the np.linspace calls, gives you more or less arrows.

Hope that helps!

like image 182
HansHirse Avatar answered Oct 30 '25 15:10

HansHirse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!