In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
In [2]:
from scipy.interpolate import griddata
In this example the values of a scalar field $f(x,y)$ are known at a very limited set of points in a square domain:
Create arrays x
, y
, f
:
x
should be a 1d array of the x coordinates on the boundary and the 1 interior point.y
should be a 1d array of the y coordinates on the boundary and the 1 interior point.f
should be a 1d array of the values of f at the corresponding x and y coordinates.You might find that np.hstack
is helpful.
In [3]:
xt = np.arange(-5,6,1)
yt = np.zeros_like(xt)
yt.fill(5)
ft = np.zeros_like(xt)
yl = np.arange(-5,5,1)
xl = np.zeros_like(yl)
xl.fill(-5)
fl = np.zeros_like(yl)
yr = yl
xr = np.zeros_like(xl)
xr.fill(5)
fr = fl
xb = np.arange(-4,5,1)
yb = np.zeros_like(xb)
yb.fill(-5)
fb = np.zeros_like(xb)
x = np.hstack((0,xt,xr,xb,xl))
y = np.hstack((0,yt,yr,yb,yl))
f = np.hstack((1,ft,fr,fb,fl))
The following plot should show the points on the boundary and the single point in the interior:
In [4]:
plt.scatter(x, y);
In [5]:
assert x.shape==(41,)
assert y.shape==(41,)
assert f.shape==(41,)
assert np.count_nonzero(f)==1
Use meshgrid
and griddata
to interpolate the function $f(x,y)$ on the entire square domain:
xnew
and ynew
should be 1d arrays with 100 points between $[-5,5]$.Xnew
and Ynew
should be 2d versions of xnew
and ynew
created by meshgrid
.Fnew
should be a 2d array with the interpolated values of $f(x,y)$ at the points (Xnew
,Ynew
).
In [6]:
xnew = np.linspace(-5,5,100)
ynew = xnew
Xnew,Ynew = np.meshgrid(xnew,ynew)
Fnew = griddata( (x,y), f, (Xnew,Ynew), method="cubic")
In [7]:
assert xnew.shape==(100,)
assert ynew.shape==(100,)
assert Xnew.shape==(100,100)
assert Ynew.shape==(100,100)
assert Fnew.shape==(100,100)
Plot the values of the interpolated scalar field using a contour plot. Customize your plot to make it effective and beautiful.
In [8]:
plt.contour(Xnew, Ynew, Fnew)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("f (x,y)", fontsize= 14)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
In [ ]:
assert True # leave this to grade the plot