Skip to content

Instantly share code, notes, and snippets.

@grinsted
Created January 29, 2021 11:39
Show Gist options
  • Save grinsted/b974cdf8671550eb4d08e00e78cdf340 to your computer and use it in GitHub Desktop.
Save grinsted/b974cdf8671550eb4d08e00e78cdf340 to your computer and use it in GitHub Desktop.
A reasonably fast interp2 for python.
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 6 15:01:40 2020
@author: aslak grinsted
"""
import numpy as np
import matplotlib.pyplot as plt
from numpy import nan
def interpgrid(x, y, a, xi, yi):
""" 2d linear interpolation
- vectorized version.
- with bounds checking.
- does not check if input sizes are compatible.
- assumes numpy inputs
"""
xi = (xi - x[0]) / (x[1] - x[0])
yi = (yi - y[0]) / (y[1] - y[0])
Ny, Nx = a.shape
Ni = xi.shape
inbounds = (xi>=0)&(xi<Nx)&(yi>=0)&(yi<Ny) #excludes points where xi=Ny
ai = np.full(xi.shape,np.nan)
xi = xi[inbounds]
yi = yi[inbounds]
x = xi.astype(int)
y = yi.astype(int)
xn = x + 1
yn = y + 1
a00 = a[y, x]
a01 = a[y, xn]
a10 = a[yn, x]
a11 = a[yn, xn]
xt = xi - x
yt = yi - y
a0 = a00 * (1 - xt) + a01 * xt
a1 = a10 * (1 - xt) + a11 * xt
ai[inbounds] = a0 * (1 - yt) + a1 * yt
return ai
#testing...................
x=np.arange(100,1000,30)
y=np.arange(-1000,100,30)
a=np.outer(np.sin(x/60),np.cos(y/80))
plt.imshow(a)
xi=np.linspace(-100,300,10)
yi=np.linspace(-500,110,10)
new =interpgrid(x,y,a,xi,yi)
print(new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment