Debian Codegraph @

geotiepoints/interpolator.py

raw
1 """Generic interpolation routines."""
2
3 from abc import ABC, abstractmethod
4 from functools import partial
5 import numpy as np
6 from scipy.interpolate import RectBivariateSpline, splev, splrep, RegularGridInterpolator
7
8
9 def generic_modis5kmto1km(*data5km):
10 """Get 1km data for modis from 5km tiepoints."""
11 cols5km = np.arange(2, 1354, 5)
12 cols1km = np.arange(1354)
13 lines = data5km[0].shape[0] * 5
14 rows5km = np.arange(2, lines, 5)
15 rows1km = np.arange(lines)
16
17 along_track_order = 1
18 cross_track_order = 3
19
20 satint = Interpolator(list(data5km),
21 (rows5km, cols5km),
22 (rows1km, cols1km),
23 along_track_order,
24 cross_track_order,
25 chunk_size=10)
26 satint.fill_borders("y", "x")
27 return satint.interpolate()
28
29 # NOTE: extrapolate on a sphere ?
30
31
32 def _linear_extrapolate(pos, data, xev):
33 """Perform linear extrapolation.
34
35 >>> import numpy as np
36 >>> pos = np.array([1, 2])
37 >>> data = np.arange(10).reshape((2, 5), order="F")
38 >>> xev = 5
39 >>> retv = _linear_extrapolate(pos, data, xev)
40 >>> print([val for val in retv])
41 [4.0, 6.0, 8.0, 10.0, 12.0]
42 >>> xev = 0
43 >>> retv = _linear_extrapolate(pos, data, xev)
44 >>> print([val for val in retv])
45 [-1.0, 1.0, 3.0, 5.0, 7.0]
46 """
47 if len(data) != 2 or len(pos) != 2:
48 raise ValueError("len(pos) and the number of lines of data"
49 " must be 2.")
50
51 return data[1] + ((xev - pos[1]) / (1.0 * (pos[0] - pos[1])) * (data[0] - data[1]))
52
53
54 class Interpolator:
55 """Handles interpolation of data from a grid of tie points.
56
57 It is preferable to have tie-points out till the edges if the tiepoint grid,
58 but a method is provided to extrapolate linearly the tiepoints to the borders of the
59 grid. The extrapolation is done automatically if it seems necessary.
60
61 Uses numpy and scipy.
62
63 The constructor takes in the tiepointed data as *data*, the *tiepoint_grid* and the desired *final_grid*. As
64 optional arguments, one can provide *kx_* and *ky_* as interpolation orders (in x and y directions respectively),
65 and the *chunksize* if the data has to be handled by pieces along the y axis (this affects how the extrapolator
66 behaves). If *chunksize* is set, don't forget to adjust the interpolation orders accordingly: the interpolation
67 is indeed done globaly (not chunkwise).
68 """
69
70 def __init__(self, data, tiepoint_grid, final_grid,
71 kx_=1, ky_=1, chunk_size=0):
72 self.row_indices = tiepoint_grid[0]
73 self.col_indices = tiepoint_grid[1]
74 self.hrow_indices = final_grid[0]
75 self.hcol_indices = final_grid[1]
76 self.chunk_size = chunk_size
77 if not isinstance(data, (tuple, list)):
78 self.tie_data = [data]
79 else:
80 self.tie_data = list(data)
81
82 self.new_data = [[] for _ in self.tie_data]
83 self.kx_, self.ky_ = kx_, ky_
84
85 def fill_borders(self, *args):
86 """Extrapolate tiepoint lons and lats to fill in the border of the chunks."""
87 to_run = []
88 cases = {"y": self._fill_row_borders,
89 "x": self._fill_col_borders}
90 for dim in args:
91 try:
92 to_run.append(cases[dim])
93 except KeyError:
94 raise NameError("Unrecognized dimension: " + str(dim))
95
96 for fun in to_run:
97 fun()
98
99 def _extrapolate_cols(self, data, first=True, last=True):
100 """Extrapolate the column of data, to get the first and last together with the data."""
101 if first:
102 pos = self.col_indices[:2]
103 first_column = _linear_extrapolate(pos,
104 (data[:, 0], data[:, 1]),
105 self.hcol_indices[0])
106 if last:
107 pos = self.col_indices[-2:]
108 last_column = _linear_extrapolate(pos,
109 (data[:, -2], data[:, -1]),
110 self.hcol_indices[-1])
111
112 if first and last:
113 return np.hstack((np.expand_dims(first_column, 1),
114 data,
115 np.expand_dims(last_column, 1)))
116 elif first:
117 return np.hstack((np.expand_dims(first_column, 1),
118 data))
119 elif last:
120 return np.hstack((data,
121 np.expand_dims(last_column, 1)))
122 else:
123 return data
124
125 def _fill_col_borders(self):
126 """Add the first and last column to the data by extrapolation."""
127 first = True
128 last = True
129 if self.col_indices[0] == self.hcol_indices[0]:
130 first = False
131 if self.col_indices[-1] == self.hcol_indices[-1]:
132 last = False
133 for num, data in enumerate(self.tie_data):
134 self.tie_data[num] = self._extrapolate_cols(data, first, last)
135
136 if first and last:
137 self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]),
138 self.col_indices,
139 np.array([self.hcol_indices[-1]])))
140 elif first:
141 self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]),
142 self.col_indices))
143 elif last:
144 self.col_indices = np.concatenate((self.col_indices,
145 np.array([self.hcol_indices[-1]])))
146
147 def _extrapolate_rows(self, data, row_indices, first_index, last_index):
148 """Extrapolate the rows of data, to get the first and last together with the data."""
149 pos = row_indices[:2]
150 first_row = _linear_extrapolate(pos,
151 (data[0, :], data[1, :]),
152 first_index)
153 pos = row_indices[-2:]
154 last_row = _linear_extrapolate(pos,
155 (data[-2, :], data[-1, :]),
156 last_index)
157 return np.vstack((np.expand_dims(first_row, 0),
158 data,
159 np.expand_dims(last_row, 0)))
160
161 def _fill_row_borders(self):
162 """Add the first and last rows to the data by extrapolation."""
163 lines = len(self.hrow_indices)
164 chunk_size = self.chunk_size or lines
165 factor = len(self.hrow_indices) / len(self.row_indices)
166
167 tmp_data = []
168 for _num in range(len(self.tie_data)):
169 tmp_data.append([])
170 row_indices = []
171
172 for index in range(0, lines, chunk_size):
173 indices = np.logical_and(self.row_indices >= index / factor,
174 self.row_indices < (index + chunk_size) / factor)
175 ties = np.argwhere(indices).squeeze()
176 tiepos = self.row_indices[indices].squeeze()
177
178 for num, data in enumerate(self.tie_data):
179 to_extrapolate = data[ties, :]
180 if len(to_extrapolate) > 0:
181 extrapolated = self._extrapolate_rows(to_extrapolate,
182 tiepos,
183 self.hrow_indices[
184 index],
185 self.hrow_indices[index + chunk_size - 1])
186 tmp_data[num].append(extrapolated)
187
188 row_indices.append(np.array([self.hrow_indices[index]]))
189 row_indices.append(tiepos)
190 row_indices.append(np.array([self.hrow_indices[index + chunk_size - 1]]))
191
192 for num in range(len(self.tie_data)):
193 self.tie_data[num] = np.vstack(tmp_data[num])
194 self.row_indices = np.concatenate(row_indices)
195
196 def _interp(self):
197 """Interpolate the cartesian coordinates."""
198 if np.array_equal(self.hrow_indices, self.row_indices):
199 return self._interp1d()
200
201 for num, data in enumerate(self.tie_data):
202 spl = RectBivariateSpline(self.row_indices,
203 self.col_indices,
204 data,
205 s=0,
206 kx=self.kx_,
207 ky=self.ky_)
208
209 self.new_data[num] = spl(self.hrow_indices, self.hcol_indices, grid=True)
210
211 def _interp1d(self):
212 """Interpolate in one dimension."""
213 lines = len(self.hrow_indices)
214
215 for num, data in enumerate(self.tie_data):
216 self.new_data[num] = np.empty((len(self.hrow_indices),
217 len(self.hcol_indices)),
218 data.dtype)
219
220 for cnt in range(lines):
221 tck = splrep(self.col_indices, data[cnt, :], k=self.ky_, s=0)
222 self.new_data[num][cnt, :] = splev(
223 self.hcol_indices, tck, der=0)
224
225 def interpolate(self):
226 """Do the interpolation, and return resulting longitudes and latitudes."""
227 self._interp()
228
229 return self.new_data
230
231
232 class AbstractSingleInterpolator(ABC):
233 """An abstract interpolator for a single 2d data array."""
234
235 def __init__(self, points, values, scipy_interpolator, **interpolator_init_kwargs):
236 """Set up the interpolator.
237
238 *kwargs* are passed to the underlying scipy interpolator instance.
239 So for example, to allow extrapolation, the kwargs can be `bounds_error=False, fill_value=None`.
240 """
241 self.interpolator = scipy_interpolator(points, values, **interpolator_init_kwargs)
242 self.points = points
243 self.values = values
244
245 def interpolate(self, fine_points, chunks=None, **interpolator_call_kwargs):
246 """Interpolate the value points to the *fine_points* grid.
247
248 Args:
249 fine_points: the points on the target grid to use, as one dimensional vectors for each dimension.
250 chunks: If not None, a lazy (dask-based) interpolation will be performed using the chunk sizes specified.
251 The result will be a dask array in this case. Defaults to None.
252 interpolator_kwargs: The keyword arguments to pass to the underlying scipy interpolator.
253 """
254 if chunks is not None:
255 res = self.interpolate_dask(fine_points, chunks=chunks, **interpolator_call_kwargs)
256 else:
257 res = self.interpolate_numpy(fine_points, **interpolator_call_kwargs)
258
259 return res
260
261 def interpolate_dask(self, fine_points, chunks, **interpolator_call_kwargs):
262 """Interpolate (lazily) to a dask array."""
263 from dask.base import tokenize
264 import dask.array as da
265 from dask.array.core import normalize_chunks
266 v_fine_points, h_fine_points = fine_points
267 shape = len(v_fine_points), len(h_fine_points)
268
269 chunks = normalize_chunks(chunks, shape, dtype=self.values.dtype)
270
271 token = tokenize(chunks, self.points, self.values, fine_points, interpolator_call_kwargs)
272 name = 'interpolate-' + token
273
274 interpolate_slices = partial(self.interpolate_slices, **interpolator_call_kwargs)
275
276 dskx = {(name, ) + position: (interpolate_slices,
277 slices)
278 for position, slices in _enumerate_chunk_slices(chunks)}
279
280 res = da.Array(dskx, name, shape=list(shape),
281 chunks=chunks,
282 dtype=self.values.dtype)
283 return res
284
285 @abstractmethod
286 def interpolate_numpy(self, fine_points, **interpolator_call_kwargs):
287 """Interpolate to a numpy array."""
288 raise NotImplementedError
289
290 def interpolate_slices(self, fine_points, **interpolator_call_kwargs):
291 """Interpolate using slices.
292
293 *fine_points* are a tuple of slices for the y and x dimensions
294 """
295 slice_y, slice_x = fine_points
296 points_y = np.arange(slice_y.start, slice_y.stop)
297 points_x = np.arange(slice_x.start, slice_x.stop)
298 fine_points = points_y, points_x
299
300 return self.interpolate_numpy(fine_points, **interpolator_call_kwargs)
301
302
303 def _enumerate_chunk_slices(chunks):
304 """Enumerate chunks with slices."""
305 for position in np.ndindex(tuple(map(len, (chunks)))):
306 slices = []
307 for pos, chunk in zip(position, chunks):
308 chunk_size = chunk[pos]
309 offset = sum(chunk[:pos])
310 slices.append(slice(offset, offset + chunk_size))
311
312 yield (position, slices)
313
314
315 class SingleGridInterpolator(AbstractSingleInterpolator):
316 """A regular grid interpolator for a single 2d data array."""
317
318 def __init__(self, *args, **interpolator_init_kwargs):
319 """Set up the grid interpolator."""
320 super().__init__(*args, scipy_interpolator=RegularGridInterpolator, **interpolator_init_kwargs)
321
322 def interpolate_numpy(self, fine_points, **interpolator_call_kwargs):
323 """Interpolate to a numpy array."""
324 fine_x, fine_y = np.meshgrid(*fine_points, indexing='ij')
325 return self.interpolator((fine_x, fine_y), **interpolator_call_kwargs).astype(self.values.dtype)
326
327
328 class SingleSplineInterpolator(AbstractSingleInterpolator):
329 """An spline interpolator for a single 2d data array."""
330
331 def __init__(self, points, values, **interpolator_init_kwargs):
332 """Set up the spline interpolator."""
333 self.interpolator = RectBivariateSpline(*points, values, **interpolator_init_kwargs)
334 self.points = points
335 self.values = values
336
337 def interpolate_numpy(self, fine_points, **interpolator_call_kwargs):
338 """Interpolate to a numpy array."""
339 return self.interpolator(*fine_points, **interpolator_call_kwargs).astype(self.values.dtype)
340
341
342 class AbstractMultipleInterpolator(ABC): # noqa: B024
343 """Abstract interpolator that works on mulitple arrays."""
344
345 def __init__(self, interpolator, tie_points, *data, **interpolator_init_kwargs):
346 """Set up the interpolator from the multiple `data` arrays."""
347 self.interpolators = []
348 for values in data:
349 self.interpolators.append(interpolator(tie_points, values, **interpolator_init_kwargs))
350
351 def interpolate(self, fine_points, **kwargs):
352 """Interpolate the data.
353
354 The keyword arguments will be passed on to SingleGridInterpolator's interpolate function.
355 """
356 return (interpolator.interpolate(fine_points, **kwargs) for interpolator in self.interpolators)
357
358 def interpolate_to_shape(self, shape, **interpolator_call_kwargs):
359 """Interpolate to a given *shape*."""
360 fine_points = [np.arange(size) for size in shape]
361 return self.interpolate(fine_points, **interpolator_call_kwargs)
362
363
364 class MultipleGridInterpolator(AbstractMultipleInterpolator):
365 """Grid interpolator that works on multiple data arrays."""
366
367 def __init__(self, tie_points, *data, **interpolator_init_kwargs):
368 """Set up the interpolator from the multiple `data` arrays."""
369 super().__init__(SingleGridInterpolator, tie_points, *data, **interpolator_init_kwargs)
370
371
372 class MultipleSplineInterpolator(AbstractMultipleInterpolator):
373 """Spline interpolator that works on multiple data arrays."""
374
375 def __init__(self, tie_points, *data, **interpolator_init_kwargs):
376 """Set up the interpolator from the multiple `data` arrays."""
377 super().__init__(SingleSplineInterpolator, tie_points, *data, **interpolator_init_kwargs)