Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 215 lines (170 sloc) 7.154 kB
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
1 """
2 Convenience interface to N-D interpolation
3
4 .. versionadded:: 0.9
5
6 """
5f4c579 @pv MAINT: add relevant from __future__ import to all files
pv authored
7 from __future__ import division, print_function, absolute_import
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
8
9 import numpy as np
3add620 @pv MAINT: Automated 2to3 conversion of the code base
pv authored
10 from .interpnd import LinearNDInterpolator, NDInterpolatorBase, \
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
11 CloughTocher2DInterpolator, _ndim_coords_from_arrays
12 from scipy.spatial import cKDTree
13
14 __all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator',
15 'CloughTocher2DInterpolator']
16
17 #------------------------------------------------------------------------------
18 # Nearest-neighbour interpolation
19 #------------------------------------------------------------------------------
20
5d565c0 @timleslie PEP8: Fix E302 expected 2 blank lines, found 1
timleslie authored
21
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
22 class NearestNDInterpolator(NDInterpolatorBase):
23 """
24 NearestNDInterpolator(points, values)
25
26 Nearest-neighbour interpolation in N dimensions.
27
28 .. versionadded:: 0.9
29
9434dec @andreas-h DOC: add 'Methods' section to Cython-based interpolation classes
andreas-h authored
30 Methods
31 -------
32 __call__
33
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
34 Parameters
35 ----------
e16b762 @rgommers DOC: merge wiki edits, interpolate module.
rgommers authored
36 points : (Npoints, Ndims) ndarray of floats
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
37 Data point coordinates.
e16b762 @rgommers DOC: merge wiki edits, interpolate module.
rgommers authored
38 values : (Npoints,) ndarray of float or complex
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
39 Data values.
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
40 rescale : boolean, optional
41 Rescale points to unit cube before performing interpolation.
42 This is useful if some of the input dimensions have
43 incommensurable units and differ by many orders of magnitude.
44
45 .. versionadded:: 0.14.0
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
46
47 Notes
48 -----
49 Uses ``scipy.spatial.cKDTree``
50
51 """
52
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
53 def __init__(self, x, y, rescale=False):
54 NDInterpolatorBase.__init__(self, x, y, rescale=rescale,
55 need_contiguous=False,
56 need_values=False)
57 self.tree = cKDTree(self.points)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
58 self.values = y
59
9580134 @pv ENH: interpolate: allow more natural __call__ usage in N-D interpolants
pv authored
60 def __call__(self, *args):
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
61 """
62 Evaluate interpolator at given points.
63
64 Parameters
65 ----------
66 xi : ndarray of float, shape (..., ndim)
67 Points where to interpolate data at.
68
69 """
bdef3dd @pv ENH: interpolate: uniform xi input arg handling for griddata and interpn
pv authored
70 xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1])
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
71 xi = self._check_call_shape(xi)
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
72 xi = self._scale_x(xi)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
73 dist, i = self.tree.query(xi)
74 return self.values[i]
75
76
77 #------------------------------------------------------------------------------
78 # Convenience interface function
79 #------------------------------------------------------------------------------
80
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
81 def griddata(points, values, xi, method='linear', fill_value=np.nan,
82 rescale=False):
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
83 """
2cfede4 Made sure griddata docs are clear that it is D-dimensional and there …
Ben FrantzDale authored
84 Interpolate unstructured D-dimensional data.
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
85
86 .. versionadded:: 0.9
87
88 Parameters
89 ----------
2cfede4 Made sure griddata docs are clear that it is D-dimensional and there …
Ben FrantzDale authored
90 points : ndarray of floats, shape (n, D)
e16b762 @rgommers DOC: merge wiki edits, interpolate module.
rgommers authored
91 Data point coordinates. Can either be an array of
2cfede4 Made sure griddata docs are clear that it is D-dimensional and there …
Ben FrantzDale authored
92 shape (n, D), or a tuple of `ndim` arrays.
93 values : ndarray of float or complex, shape (n,)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
94 Data values.
2cfede4 Made sure griddata docs are clear that it is D-dimensional and there …
Ben FrantzDale authored
95 xi : ndarray of float, shape (M, D)
e16b762 @rgommers DOC: merge wiki edits, interpolate module.
rgommers authored
96 Points at which to interpolate data.
8947471 @rgommers ENH: make interpolate.griddata work for unsorted 1-D data. Closes #1…
rgommers authored
97 method : {'linear', 'nearest', 'cubic'}, optional
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
98 Method of interpolation. One of
99
34292fc @endolith DOC: Fix definition list formatting
endolith authored
100 ``nearest``
101 return the value at the data point closest to
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
102 the point of interpolation. See `NearestNDInterpolator` for
103 more details.
104
34292fc @endolith DOC: Fix definition list formatting
endolith authored
105 ``linear``
106 tesselate the input point set to n-dimensional
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
107 simplices, and interpolate linearly on each simplex. See
108 `LinearNDInterpolator` for more details.
109
34292fc @endolith DOC: Fix definition list formatting
endolith authored
110 ``cubic`` (1-D)
111 return the value determined from a cubic
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
112 spline.
113
34292fc @endolith DOC: Fix definition list formatting
endolith authored
114 ``cubic`` (2-D)
115 return the value determined from a
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
116 piecewise cubic, continuously differentiable (C1), and
117 approximately curvature-minimizing polynomial surface. See
118 `CloughTocher2DInterpolator` for more details.
8d6168b @pv ENH: interpolate: add a 'fill_value' keyword to griddata
pv authored
119 fill_value : float, optional
120 Value used to fill in for requested points outside of the
121 convex hull of the input points. If not provided, then the
122 default is ``nan``. This option has no effect for the
123 'nearest' method.
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
124 rescale : boolean, optional
125 Rescale points to unit cube before performing interpolation.
126 This is useful if some of the input dimensions have
127 incommensurable units and differ by many orders of magnitude.
128
129 .. versionadded:: 0.14.0
8d6168b @pv ENH: interpolate: add a 'fill_value' keyword to griddata
pv authored
130
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
131
132 Examples
133 --------
134
135 Suppose we want to interpolate the 2-D function
136
137 >>> def func(x, y):
138 >>> return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
139
140 on a grid in [0, 1]x[0, 1]
141
142 >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
143
144 but we only know its values at 1000 data points:
145
146 >>> points = np.random.rand(1000, 2)
147 >>> values = func(points[:,0], points[:,1])
148
149 This can be done with `griddata` -- below we try out all of the
150 interpolation methods:
151
152 >>> from scipy.interpolate import griddata
153 >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
154 >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
155 >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')
156
157 One can see that the exact result is reproduced by all of the
158 methods to some degree, but for this smooth function the piecewise
159 cubic interpolant gives the best results:
160
161 >>> import matplotlib.pyplot as plt
162 >>> plt.subplot(221)
163 >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
164 >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
165 >>> plt.title('Original')
166 >>> plt.subplot(222)
167 >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
168 >>> plt.title('Nearest')
169 >>> plt.subplot(223)
170 >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
171 >>> plt.title('Linear')
172 >>> plt.subplot(224)
173 >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
174 >>> plt.title('Cubic')
175 >>> plt.gcf().set_size_inches(6, 6)
176 >>> plt.show()
177
178 """
179
180 points = _ndim_coords_from_arrays(points)
181
bca4ae2 @pv BUG: interpolate: make griddata work for 1-D data, and add tests for …
pv authored
182 if points.ndim < 2:
183 ndim = points.ndim
184 else:
185 ndim = points.shape[-1]
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
186
187 if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
3add620 @pv MAINT: Automated 2to3 conversion of the code base
pv authored
188 from .interpolate import interp1d
bca4ae2 @pv BUG: interpolate: make griddata work for 1-D data, and add tests for …
pv authored
189 points = points.ravel()
9580134 @pv ENH: interpolate: allow more natural __call__ usage in N-D interpolants
pv authored
190 if isinstance(xi, tuple):
191 if len(xi) != 1:
192 raise ValueError("invalid number of dimensions in xi")
bca4ae2 @pv BUG: interpolate: make griddata work for 1-D data, and add tests for …
pv authored
193 xi, = xi
8947471 @rgommers ENH: make interpolate.griddata work for unsorted 1-D data. Closes #1…
rgommers authored
194 # Sort points/values together, necessary as input for interp1d
195 idx = np.argsort(points)
196 points = points[idx]
197 values = values[idx]
8d6168b @pv ENH: interpolate: add a 'fill_value' keyword to griddata
pv authored
198 ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
199 fill_value=fill_value)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
200 return ip(xi)
201 elif method == 'nearest':
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
202 ip = NearestNDInterpolator(points, values, rescale=rescale)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
203 return ip(xi)
204 elif method == 'linear':
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
205 ip = LinearNDInterpolator(points, values, fill_value=fill_value,
206 rescale=rescale)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
207 return ip(xi)
208 elif method == 'cubic' and ndim == 2:
b48c11a @pv ENH: interpolate: add the rescale argument to griddata and NearestNDI…
pv authored
209 ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
210 rescale=rescale)
1e8cc8e @pv interpolate: add griddata, convenience function for N-d interpolation
pv authored
211 return ip(xi)
212 else:
213 raise ValueError("Unknown interpolation method %r for "
214 "%d dimensional data" % (method, ndim))
Something went wrong with that request. Please try again.