_rbf.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. """rbf - Radial basis functions for interpolation/smoothing scattered N-D data.
  2. Written by John Travers <jtravs@gmail.com>, February 2007
  3. Based closely on Matlab code by Alex Chirokov
  4. Additional, large, improvements by Robert Hetland
  5. Some additional alterations by Travis Oliphant
  6. Interpolation with multi-dimensional target domain by Josua Sassen
  7. Permission to use, modify, and distribute this software is given under the
  8. terms of the SciPy (BSD style) license. See LICENSE.txt that came with
  9. this distribution for specifics.
  10. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  11. Copyright (c) 2006-2007, Robert Hetland <hetland@tamu.edu>
  12. Copyright (c) 2007, John Travers <jtravs@gmail.com>
  13. Redistribution and use in source and binary forms, with or without
  14. modification, are permitted provided that the following conditions are
  15. met:
  16. * Redistributions of source code must retain the above copyright
  17. notice, this list of conditions and the following disclaimer.
  18. * Redistributions in binary form must reproduce the above
  19. copyright notice, this list of conditions and the following
  20. disclaimer in the documentation and/or other materials provided
  21. with the distribution.
  22. * Neither the name of Robert Hetland nor the names of any
  23. contributors may be used to endorse or promote products derived
  24. from this software without specific prior written permission.
  25. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  28. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  29. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  30. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  31. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  32. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  33. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  35. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. """
  37. import numpy as np
  38. from scipy import linalg
  39. from scipy.special import xlogy
  40. from scipy.spatial.distance import cdist, pdist, squareform
  41. __all__ = ['Rbf']
  42. class Rbf:
  43. """
  44. Rbf(*args, **kwargs)
  45. A class for radial basis function interpolation of functions from
  46. N-D scattered data to an M-D domain.
  47. .. note::
  48. `Rbf` is legacy code, for new usage please use `RBFInterpolator`
  49. instead.
  50. Parameters
  51. ----------
  52. *args : arrays
  53. x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes
  54. and d is the array of values at the nodes
  55. function : str or callable, optional
  56. The radial basis function, based on the radius, r, given by the norm
  57. (default is Euclidean distance); the default is 'multiquadric'::
  58. 'multiquadric': sqrt((r/self.epsilon)**2 + 1)
  59. 'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
  60. 'gaussian': exp(-(r/self.epsilon)**2)
  61. 'linear': r
  62. 'cubic': r**3
  63. 'quintic': r**5
  64. 'thin_plate': r**2 * log(r)
  65. If callable, then it must take 2 arguments (self, r). The epsilon
  66. parameter will be available as self.epsilon. Other keyword
  67. arguments passed in will be available as well.
  68. epsilon : float, optional
  69. Adjustable constant for gaussian or multiquadrics functions
  70. - defaults to approximate average distance between nodes (which is
  71. a good start).
  72. smooth : float, optional
  73. Values greater than zero increase the smoothness of the
  74. approximation. 0 is for interpolation (default), the function will
  75. always go through the nodal points in this case.
  76. norm : str, callable, optional
  77. A function that returns the 'distance' between two points, with
  78. inputs as arrays of positions (x, y, z, ...), and an output as an
  79. array of distance. E.g., the default: 'euclidean', such that the result
  80. is a matrix of the distances from each point in ``x1`` to each point in
  81. ``x2``. For more options, see documentation of
  82. `scipy.spatial.distances.cdist`.
  83. mode : str, optional
  84. Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is
  85. '1-D' the data `d` will be considered as 1-D and flattened
  86. internally. When it is 'N-D' the data `d` is assumed to be an array of
  87. shape (n_samples, m), where m is the dimension of the target domain.
  88. Attributes
  89. ----------
  90. N : int
  91. The number of data points (as determined by the input arrays).
  92. di : ndarray
  93. The 1-D array of data values at each of the data coordinates `xi`.
  94. xi : ndarray
  95. The 2-D array of data coordinates.
  96. function : str or callable
  97. The radial basis function. See description under Parameters.
  98. epsilon : float
  99. Parameter used by gaussian or multiquadrics functions. See Parameters.
  100. smooth : float
  101. Smoothing parameter. See description under Parameters.
  102. norm : str or callable
  103. The distance function. See description under Parameters.
  104. mode : str
  105. Mode of the interpolation. See description under Parameters.
  106. nodes : ndarray
  107. A 1-D array of node values for the interpolation.
  108. A : internal property, do not use
  109. See Also
  110. --------
  111. RBFInterpolator
  112. Examples
  113. --------
  114. >>> import numpy as np
  115. >>> from scipy.interpolate import Rbf
  116. >>> rng = np.random.default_rng()
  117. >>> x, y, z, d = rng.random((4, 50))
  118. >>> rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance
  119. >>> xi = yi = zi = np.linspace(0, 1, 20)
  120. >>> di = rbfi(xi, yi, zi) # interpolated values
  121. >>> di.shape
  122. (20,)
  123. """
  124. # Available radial basis functions that can be selected as strings;
  125. # they all start with _h_ (self._init_function relies on that)
  126. def _h_multiquadric(self, r):
  127. return np.sqrt((1.0/self.epsilon*r)**2 + 1)
  128. def _h_inverse_multiquadric(self, r):
  129. return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1)
  130. def _h_gaussian(self, r):
  131. return np.exp(-(1.0/self.epsilon*r)**2)
  132. def _h_linear(self, r):
  133. return r
  134. def _h_cubic(self, r):
  135. return r**3
  136. def _h_quintic(self, r):
  137. return r**5
  138. def _h_thin_plate(self, r):
  139. return xlogy(r**2, r)
  140. # Setup self._function and do smoke test on initial r
  141. def _init_function(self, r):
  142. if isinstance(self.function, str):
  143. self.function = self.function.lower()
  144. _mapped = {'inverse': 'inverse_multiquadric',
  145. 'inverse multiquadric': 'inverse_multiquadric',
  146. 'thin-plate': 'thin_plate'}
  147. if self.function in _mapped:
  148. self.function = _mapped[self.function]
  149. func_name = "_h_" + self.function
  150. if hasattr(self, func_name):
  151. self._function = getattr(self, func_name)
  152. else:
  153. functionlist = [x[3:] for x in dir(self)
  154. if x.startswith('_h_')]
  155. raise ValueError("function must be a callable or one of " +
  156. ", ".join(functionlist))
  157. self._function = getattr(self, "_h_"+self.function)
  158. elif callable(self.function):
  159. allow_one = False
  160. if hasattr(self.function, 'func_code') or \
  161. hasattr(self.function, '__code__'):
  162. val = self.function
  163. allow_one = True
  164. elif hasattr(self.function, "__call__"):
  165. val = self.function.__call__.__func__
  166. else:
  167. raise ValueError("Cannot determine number of arguments to "
  168. "function")
  169. argcount = val.__code__.co_argcount
  170. if allow_one and argcount == 1:
  171. self._function = self.function
  172. elif argcount == 2:
  173. self._function = self.function.__get__(self, Rbf)
  174. else:
  175. raise ValueError("Function argument must take 1 or 2 "
  176. "arguments.")
  177. a0 = self._function(r)
  178. if a0.shape != r.shape:
  179. raise ValueError("Callable must take array and return array of "
  180. "the same shape")
  181. return a0
  182. def __init__(self, *args, **kwargs):
  183. # `args` can be a variable number of arrays; we flatten them and store
  184. # them as a single 2-D array `xi` of shape (n_args-1, array_size),
  185. # plus a 1-D array `di` for the values.
  186. # All arrays must have the same number of elements
  187. self.xi = np.asarray([np.asarray(a, dtype=np.float_).flatten()
  188. for a in args[:-1]])
  189. self.N = self.xi.shape[-1]
  190. self.mode = kwargs.pop('mode', '1-D')
  191. if self.mode == '1-D':
  192. self.di = np.asarray(args[-1]).flatten()
  193. self._target_dim = 1
  194. elif self.mode == 'N-D':
  195. self.di = np.asarray(args[-1])
  196. self._target_dim = self.di.shape[-1]
  197. else:
  198. raise ValueError("Mode has to be 1-D or N-D.")
  199. if not all([x.size == self.di.shape[0] for x in self.xi]):
  200. raise ValueError("All arrays must be equal length.")
  201. self.norm = kwargs.pop('norm', 'euclidean')
  202. self.epsilon = kwargs.pop('epsilon', None)
  203. if self.epsilon is None:
  204. # default epsilon is the "the average distance between nodes" based
  205. # on a bounding hypercube
  206. ximax = np.amax(self.xi, axis=1)
  207. ximin = np.amin(self.xi, axis=1)
  208. edges = ximax - ximin
  209. edges = edges[np.nonzero(edges)]
  210. self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
  211. self.smooth = kwargs.pop('smooth', 0.0)
  212. self.function = kwargs.pop('function', 'multiquadric')
  213. # attach anything left in kwargs to self for use by any user-callable
  214. # function or to save on the object returned.
  215. for item, value in kwargs.items():
  216. setattr(self, item, value)
  217. # Compute weights
  218. if self._target_dim > 1: # If we have more than one target dimension,
  219. # we first factorize the matrix
  220. self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype)
  221. lu, piv = linalg.lu_factor(self.A)
  222. for i in range(self._target_dim):
  223. self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
  224. else:
  225. self.nodes = linalg.solve(self.A, self.di)
  226. @property
  227. def A(self):
  228. # this only exists for backwards compatibility: self.A was available
  229. # and, at least technically, public.
  230. r = squareform(pdist(self.xi.T, self.norm)) # Pairwise norm
  231. return self._init_function(r) - np.eye(self.N)*self.smooth
  232. def _call_norm(self, x1, x2):
  233. return cdist(x1.T, x2.T, self.norm)
  234. def __call__(self, *args):
  235. args = [np.asarray(x) for x in args]
  236. if not all([x.shape == y.shape for x in args for y in args]):
  237. raise ValueError("Array lengths must be equal")
  238. if self._target_dim > 1:
  239. shp = args[0].shape + (self._target_dim,)
  240. else:
  241. shp = args[0].shape
  242. xa = np.asarray([a.flatten() for a in args], dtype=np.float_)
  243. r = self._call_norm(xa, self.xi)
  244. return np.dot(self._function(r), self.nodes).reshape(shp)