I am using the griddata interpolation package in scipy, and an extrapolation function pulled from fatiando:
import numpy as np
import scipy
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
def extrapolate_nans(x, y, v):
'''
Extrapolate the NaNs or masked values in a grid INPLACE using nearest
value.
.. warning:: Replaces the NaN or masked values of the original array!
Parameters:
* x, y : 1D arrays
Arrays with the x and y coordinates of the data points.
* v : 1D array
Array with the scalar value assigned to the data points.
Returns:
* v : 1D array
The array with NaNs or masked values extrapolated.
'''
if np.ma.is_masked(v):
nans = v.mask
else:
nans = np.isnan(v)
notnans = np.logical_not(nans)
v[nans] = scipy.interpolate.griddata((x[notnans], y[notnans]), v[notnans],
(x[nans], y[nans]), method='nearest').ravel()
return v
grid_x, grid_y = np.mgrid[0:1.5:50j, 0:1.2:50j]
points = np.random.rand(50, 2)
values = np.random.random_integers(1,10,50)
x = []
y = []
for i in points:
x.append(i[0])
y.append(i[1])
n = plt.Normalize(values.min(), values.max())
grid_z = griddata(points, values, (grid_x, grid_y), method='cubic')
extrapolate_nans(grid_x,grid_y,grid_z)
plt.contourf(grid_x,grid_y,grid_z)
plt.scatter(x,y,c=values)
plt.colorbar()
plt.show()
I think the results are decent, but the problem is that the extrapolated values have a distinct zigzag pattern: 
How do I smooth these lines? Or is there an alternative interpolation method in python that will generate smoother results?
No comments:
Post a Comment