| 1 |
from __future__ import division |
| 2 |
|
| 3 |
import numpy as np |
| 4 |
|
| 5 |
from geotiepoints.multilinear_cython import multilinear_interpolation |
| 6 |
|
| 7 |
|
| 8 |
def mlinspace(smin, smax, orders): |
| 9 |
if len(orders) == 1: |
| 10 |
res = np.atleast_2d( |
| 11 |
np.linspace(np.array(smin), np.array(smax), np.array(orders))) |
| 12 |
return res.copy() # workaround for strange bug |
| 13 |
else: |
| 14 |
meshes = np.meshgrid( |
| 15 |
*[np.linspace(smin[i], smax[i], orders[i]) for i in range(len(orders))], indexing='ij') |
| 16 |
return np.vstack([l.flatten() for l in meshes]) |
| 17 |
|
| 18 |
|
| 19 |
class MultilinearInterpolator: |
| 20 |
"""Multilinear interpolation. |
| 21 |
|
| 22 |
Methods |
| 23 |
------- |
| 24 |
smin, smax, orders : iterable objects |
| 25 |
Specifies the boundaries of a cartesian grid, with the number of points along each dimension. |
| 26 |
values : array_like (2D), optional |
| 27 |
Each line enumerates values taken by a function on the cartesian grid, with last index varying faster. |
| 28 |
|
| 29 |
|
| 30 |
Attributes |
| 31 |
---------- |
| 32 |
smin, smax, orders : |
| 33 |
Boundaries and number of points along each dimension. |
| 34 |
d : number of dimensions |
| 35 |
grid : array_like (2D) |
| 36 |
Enumerate the approximation grid. Each column contains coordinates of a point in R^d. |
| 37 |
values : |
| 38 |
Values on the grid to be interpolated. |
| 39 |
|
| 40 |
Example |
| 41 |
------- |
| 42 |
|
| 43 |
smin = [-1,-1] |
| 44 |
smax = [1,1] |
| 45 |
orders = [5,5] |
| 46 |
|
| 47 |
f = lambda x: np.vstack([np.sqrt( x[0,:]**2 + x[1,:]**2 ), |
| 48 |
np.power( x[0,:]**3 + x[1,:]**3, 1.0/3.0 )]) |
| 49 |
|
| 50 |
interp = MultilinearInterpolator(smin,smax,orders) |
| 51 |
interp.set_values( f(interp.grid) ) |
| 52 |
|
| 53 |
random_points = np.random.random( (2, 1000) ) |
| 54 |
|
| 55 |
interpolated_values = interp(random_points) |
| 56 |
exact_values = f(random_points) |
| 57 |
""" |
| 58 |
|
| 59 |
__grid__ = None |
| 60 |
|
| 61 |
def __init__(self, smin, smax, orders, values=None, dtype=np.float64): |
| 62 |
self.smin = np.asarray(smin, dtype=dtype) |
| 63 |
self.smax = np.asarray(smax, dtype=dtype) |
| 64 |
self.orders = np.asarray(orders, dtype="long") |
| 65 |
self.d = len(orders) |
| 66 |
self.dtype = dtype |
| 67 |
if values is not None: |
| 68 |
self.set_values(values) |
| 69 |
|
| 70 |
@property |
| 71 |
def grid(self): |
| 72 |
if self.__grid__ is None: |
| 73 |
self.__grid__ = mlinspace(self.smin, self.smax, self.orders) |
| 74 |
return self.__grid__ |
| 75 |
|
| 76 |
def set_values(self, values): |
| 77 |
self.values = np.ascontiguousarray(values, dtype=self.dtype) |
| 78 |
|
| 79 |
def interpolate(self, s): |
| 80 |
s = np.ascontiguousarray(s, dtype=self.dtype) |
| 81 |
a = multilinear_interpolation( |
| 82 |
self.smin, self.smax, self.orders, self.values, s) |
| 83 |
return a |
| 84 |
|
| 85 |
def __call__(self, s): |
| 86 |
return self.interpolate(s) |