-
Notifications
You must be signed in to change notification settings - Fork 73
/
scipygridder.py
245 lines (203 loc) · 7.62 KB
/
scipygridder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# Copyright (c) 2017 The Verde Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Gridders that use scipy.interpolate as the backend.
"""
from abc import abstractmethod
from warnings import warn
import numpy as np
from scipy.interpolate import (
CloughTocher2DInterpolator,
LinearNDInterpolator,
NearestNDInterpolator,
)
from sklearn.utils.validation import check_is_fitted
from .base import BaseGridder, check_fit_input
from .coordinates import get_region
class _BaseScipyGridder(BaseGridder):
"""
A scipy.interpolate base gridder for scalar Cartesian data.
Used as a base class for each of the SciPy ND based interpolators.
Attributes
----------
interpolator_ : scipy interpolator class
An instance of the corresponding scipy interpolator class.
region_ : tuple
The boundaries (``[W, E, S, N]``) of the data used to fit the
interpolator. Used as the default region for the
:meth:`~verde.ScipyGridder.grid` and
:meth:`~verde.ScipyGridder.scatter` methods.
"""
@abstractmethod
def _get_interpolator(self):
"""
Return the SciPy interpolator class and any extra keyword arguments as
a dictionary.
"""
def fit(self, coordinates, data, weights=None):
"""
Fit the interpolator to the given data.
The data region is captured and used as default for the
:meth:`~verde._BaseScipyGridder.grid` method.
Parameters
----------
coordinates : tuple of arrays
Arrays with the coordinates of each data point. Should be in the
following order: (easting, northing, vertical, ...). Only easting
and northing will be used, all subsequent coordinates will be
ignored.
data : array
The data values that will be interpolated.
weights : None or array
Data weights are **not supported** by this interpolator and will be
ignored. Only present for compatibility with other gridder.
Returns
-------
self
Returns this gridder instance for chaining operations.
"""
if weights is not None:
warn(
"{} does not support weights and they will be ignored.".format(
self.__class__.__name__
)
)
coordinates, data, weights = check_fit_input(coordinates, data, weights)
easting, northing = coordinates[:2]
self.region_ = get_region((easting, northing))
points = np.column_stack((np.ravel(easting), np.ravel(northing)))
interpolator_class, kwargs = self._get_interpolator()
self.interpolator_ = interpolator_class(points, np.ravel(data), **kwargs)
return self
def predict(self, coordinates):
"""
Interpolate data on the given set of points.
Requires a fitted gridder (see :meth:`~verde._BaseScipyGridder.fit`).
Parameters
----------
coordinates : tuple of arrays
Arrays with the coordinates of each data point. Should be in the
following order: (easting, northing, vertical, ...). Only easting
and northing will be used, all subsequent coordinates will be
ignored.
Returns
-------
data : array
The data values interpolated on the given points.
"""
check_is_fitted(self, ["interpolator_"])
easting, northing = coordinates[:2]
return self.interpolator_((easting, northing))
class Linear(_BaseScipyGridder):
"""
Piecewise linear interpolation.
Provides a Verde interface to
:class:`scipy.interpolate.LinearNDInterpolator`.
Parameters
----------
rescale : bool
If ``True``, rescale the data coordinates to [0, 1] range before
interpolation. Useful when coordinates vary greatly in scale. Default
is ``False``.
Attributes
----------
interpolator_ : scipy interpolator class
An instance of the corresponding scipy interpolator class.
region_ : tuple
The boundaries (``[W, E, S, N]``) of the data used to fit the
interpolator. Used as the default region for the
:meth:`~verde.Linear.grid` method.
"""
def __init__(self, rescale=False):
super().__init__()
self.rescale = rescale
def _get_interpolator(self):
"""
Return the SciPy interpolator class and any extra keyword arguments as
a dictionary.
"""
return LinearNDInterpolator, {"rescale": self.rescale}
class Cubic(_BaseScipyGridder):
"""
Piecewise cubic interpolation.
Provides a Verde interface to
:class:`scipy.interpolate.CloughTocher2DInterpolator`.
Parameters
----------
rescale : bool
If ``True``, rescale the data coordinates to [0, 1] range before
interpolation. Useful when coordinates vary greatly in scale. Default
is ``False``.
Attributes
----------
interpolator_ : scipy interpolator class
An instance of the corresponding scipy interpolator class.
region_ : tuple
The boundaries (``[W, E, S, N]``) of the data used to fit the
interpolator. Used as the default region for the
:meth:`~verde.Cubic.grid` method.
"""
def __init__(self, rescale=False):
super().__init__()
self.rescale = rescale
def _get_interpolator(self):
"""
Return the SciPy interpolator class and any extra keyword arguments as
a dictionary.
"""
return CloughTocher2DInterpolator, {"rescale": self.rescale}
class ScipyGridder(_BaseScipyGridder):
"""
A scipy.interpolate based gridder for scalar Cartesian data.
Provides a verde gridder interface to the scipy interpolators
:class:`scipy.interpolate.LinearNDInterpolator`,
:class:`scipy.interpolate.NearestNDInterpolator`, and
:class:`scipy.interpolate.CloughTocher2DInterpolator` (cubic).
Parameters
----------
method : str
The interpolation method. Either ``'linear'``, ``'nearest'``, or
``'cubic'``.
extra_args : None or dict
Extra keyword arguments to pass to the scipy interpolator class. See
the documentation for each interpolator for a list of possible
arguments.
Attributes
----------
interpolator_ : scipy interpolator class
An instance of the corresponding scipy interpolator class.
region_ : tuple
The boundaries (``[W, E, S, N]``) of the data used to fit the
interpolator. Used as the default region for the
:meth:`~verde.ScipyGridder.grid` and
:meth:`~verde.ScipyGridder.scatter` methods.
"""
def __init__(self, method="cubic", extra_args=None):
super().__init__()
self.method = method
self.extra_args = extra_args
def _get_interpolator(self):
"""
Return the SciPy interpolator class and any extra keyword arguments as
a dictionary.
"""
classes = dict(
linear=LinearNDInterpolator,
nearest=NearestNDInterpolator,
cubic=CloughTocher2DInterpolator,
)
if self.method not in classes:
raise ValueError(
"Invalid interpolation method '{}'. Must be one of {}.".format(
self.method, str(classes.keys())
)
)
if self.extra_args is None:
kwargs = {}
else:
kwargs = self.extra_args
return classes[self.method], kwargs