Use fill_value outside boundaries with scipy.interpolate.griddata and method=nearest

7.9k views Asked by At

Function scipy.interpolate.griddata allows to specify the keyword fill_value, for which the doc states:

Value used to fill in for requested points outside of the convex hull of the input points. If not provided, then the default is nan. This option has no effect for the ‘nearest’ method.

However, I need to specify a fill_value to use outside of the boundaries when using method='nearest' with 2D data. How can this be achieved?

1

There are 1 answers

2
MB-F On

This can be relatively easily achieved with the following work-around:

  1. run with method='nearest'
  2. run again with method='linear'; here the outside region is filled with np.nan.
  3. wherever there is a NaN in the result of 2. assign your desired fill_value to the result of 1.

Code:

import numpy as np
from scipy.interpolate import griddata

def func(x, y):
    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

points = np.random.rand(100, 2)
values = func(points[:,0], points[:,1])

grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')

fill_value = 123  # Whatever you like
grid_z0[np.isnan(grid_z1)] = fill_value

A less ad-hoc approach would be to compute the convex hull explicitly and use it to assign the fill value. This would require more effort but might run faster.