4

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?

denfromufa
  • 5,610
  • 13
  • 81
  • 138
Arcturus B
  • 5,181
  • 4
  • 31
  • 51

1 Answers1

6

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.

MB-F
  • 22,770
  • 4
  • 61
  • 116
  • Thanks for your answer, that's indeed an easy solution! Although in practice, it'd use over twice the time required with a single `method='nearest'`. I’ll have a look at [`scipy.spatial.ConvexHull`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html), it might do the trick. – Arcturus B Jan 09 '17 at 14:56
  • 1
    @Arcturus B, did you come up with a better solution for your problem by using ConvexHull? You could post it and accept it. – tiagoams Mar 17 '23 at 09:38