_rbf.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. from scipy._lib._array_api import xp_capabilities
  42. __all__ = ['Rbf']
  43. @xp_capabilities(out_of_scope=True)
  44. class Rbf:
  45. """
  46. Rbf(*args, **kwargs)
  47. Class for radial basis function interpolation of functions from
  48. N-D scattered data to an M-D domain (legacy).
  49. .. legacy:: class
  50. `Rbf` is legacy code, for new usage please use `RBFInterpolator`
  51. instead.
  52. Parameters
  53. ----------
  54. *args : arrays
  55. x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes
  56. and d is the array of values at the nodes
  57. function : str or callable, optional
  58. The radial basis function, based on the radius, r, given by the norm
  59. (default is Euclidean distance); the default is 'multiquadric'::
  60. 'multiquadric': sqrt((r/self.epsilon)**2 + 1)
  61. 'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
  62. 'gaussian': exp(-(r/self.epsilon)**2)
  63. 'linear': r
  64. 'cubic': r**3
  65. 'quintic': r**5
  66. 'thin_plate': r**2 * log(r)
  67. If callable, then it must take 2 arguments (self, r). The epsilon
  68. parameter will be available as self.epsilon. Other keyword
  69. arguments passed in will be available as well.
  70. epsilon : float, optional
  71. Adjustable constant for gaussian or multiquadrics functions
  72. - defaults to approximate average distance between nodes (which is
  73. a good start).
  74. smooth : float, optional
  75. Values greater than zero increase the smoothness of the
  76. approximation. 0 is for interpolation (default), the function will
  77. always go through the nodal points in this case.
  78. norm : str, callable, optional
  79. A function that returns the 'distance' between two points, with
  80. inputs as arrays of positions (x, y, z, ...), and an output as an
  81. array of distance. E.g., the default: 'euclidean', such that the result
  82. is a matrix of the distances from each point in ``x1`` to each point in
  83. ``x2``. For more options, see documentation of
  84. `scipy.spatial.distances.cdist`.
  85. mode : str, optional
  86. Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is
  87. '1-D' the data `d` will be considered as 1-D and flattened
  88. internally. When it is 'N-D' the data `d` is assumed to be an array of
  89. shape (n_samples, m), where m is the dimension of the target domain.
  90. Attributes
  91. ----------
  92. N : int
  93. The number of data points (as determined by the input arrays).
  94. di : ndarray
  95. The 1-D array of data values at each of the data coordinates `xi`.
  96. xi : ndarray
  97. The 2-D array of data coordinates.
  98. function : str or callable
  99. The radial basis function. See description under Parameters.
  100. epsilon : float
  101. Parameter used by gaussian or multiquadrics functions. See Parameters.
  102. smooth : float
  103. Smoothing parameter. See description under Parameters.
  104. norm : str or callable
  105. The distance function. See description under Parameters.
  106. mode : str
  107. Mode of the interpolation. See description under Parameters.
  108. nodes : ndarray
  109. A 1-D array of node values for the interpolation.
  110. A : internal property, do not use
  111. See Also
  112. --------
  113. RBFInterpolator
  114. Examples
  115. --------
  116. >>> import numpy as np
  117. >>> from scipy.interpolate import Rbf
  118. >>> rng = np.random.default_rng()
  119. >>> x, y, z, d = rng.random((4, 50))
  120. >>> rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance
  121. >>> xi = yi = zi = np.linspace(0, 1, 20)
  122. >>> di = rbfi(xi, yi, zi) # interpolated values
  123. >>> di.shape
  124. (20,)
  125. """
  126. # Available radial basis functions that can be selected as strings;
  127. # they all start with _h_ (self._init_function relies on that)
  128. def _h_multiquadric(self, r):
  129. return np.sqrt((1.0/self.epsilon*r)**2 + 1)
  130. def _h_inverse_multiquadric(self, r):
  131. return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1)
  132. def _h_gaussian(self, r):
  133. return np.exp(-(1.0/self.epsilon*r)**2)
  134. def _h_linear(self, r):
  135. return r
  136. def _h_cubic(self, r):
  137. return r**3
  138. def _h_quintic(self, r):
  139. return r**5
  140. def _h_thin_plate(self, r):
  141. return xlogy(r**2, r)
  142. # Setup self._function and do smoke test on initial r
  143. def _init_function(self, r):
  144. if isinstance(self.function, str):
  145. self.function = self.function.lower()
  146. _mapped = {'inverse': 'inverse_multiquadric',
  147. 'inverse multiquadric': 'inverse_multiquadric',
  148. 'thin-plate': 'thin_plate'}
  149. if self.function in _mapped:
  150. self.function = _mapped[self.function]
  151. func_name = "_h_" + self.function
  152. if hasattr(self, func_name):
  153. self._function = getattr(self, func_name)
  154. else:
  155. functionlist = [x[3:] for x in dir(self)
  156. if x.startswith('_h_')]
  157. raise ValueError("function must be a callable or one of " +
  158. ", ".join(functionlist))
  159. self._function = getattr(self, "_h_"+self.function)
  160. elif callable(self.function):
  161. allow_one = False
  162. if hasattr(self.function, 'func_code') or \
  163. hasattr(self.function, '__code__'):
  164. val = self.function
  165. allow_one = True
  166. elif hasattr(self.function, "__call__"):
  167. val = self.function.__call__.__func__
  168. else:
  169. raise ValueError("Cannot determine number of arguments to "
  170. "function")
  171. argcount = val.__code__.co_argcount
  172. if allow_one and argcount == 1:
  173. self._function = self.function
  174. elif argcount == 2:
  175. self._function = self.function.__get__(self, Rbf)
  176. else:
  177. raise ValueError("Function argument must take 1 or 2 "
  178. "arguments.")
  179. a0 = self._function(r)
  180. if a0.shape != r.shape:
  181. raise ValueError("Callable must take array and return array of "
  182. "the same shape")
  183. return a0
  184. def __init__(self, *args, **kwargs):
  185. # `args` can be a variable number of arrays; we flatten them and store
  186. # them as a single 2-D array `xi` of shape (n_args-1, array_size),
  187. # plus a 1-D array `di` for the values.
  188. # All arrays must have the same number of elements
  189. self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten()
  190. for a in args[:-1]])
  191. self.N = self.xi.shape[-1]
  192. self.mode = kwargs.pop('mode', '1-D')
  193. if self.mode == '1-D':
  194. self.di = np.asarray(args[-1]).flatten()
  195. self._target_dim = 1
  196. elif self.mode == 'N-D':
  197. self.di = np.asarray(args[-1])
  198. self._target_dim = self.di.shape[-1]
  199. else:
  200. raise ValueError("Mode has to be 1-D or N-D.")
  201. if not all([x.size == self.di.shape[0] for x in self.xi]):
  202. raise ValueError("All arrays must be equal length.")
  203. self.norm = kwargs.pop('norm', 'euclidean')
  204. self.epsilon = kwargs.pop('epsilon', None)
  205. if self.epsilon is None:
  206. # default epsilon is the "the average distance between nodes" based
  207. # on a bounding hypercube
  208. ximax = np.amax(self.xi, axis=1)
  209. ximin = np.amin(self.xi, axis=1)
  210. edges = ximax - ximin
  211. edges = edges[np.nonzero(edges)]
  212. self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
  213. self.smooth = kwargs.pop('smooth', 0.0)
  214. self.function = kwargs.pop('function', 'multiquadric')
  215. # attach anything left in kwargs to self for use by any user-callable
  216. # function or to save on the object returned.
  217. for item, value in kwargs.items():
  218. setattr(self, item, value)
  219. # Compute weights
  220. if self._target_dim > 1: # If we have more than one target dimension,
  221. # we first factorize the matrix
  222. self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype)
  223. lu, piv = linalg.lu_factor(self.A)
  224. for i in range(self._target_dim):
  225. self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
  226. else:
  227. self.nodes = linalg.solve(self.A, self.di)
  228. @property
  229. def A(self):
  230. # this only exists for backwards compatibility: self.A was available
  231. # and, at least technically, public.
  232. r = squareform(pdist(self.xi.T, self.norm)) # Pairwise norm
  233. return self._init_function(r) - np.eye(self.N)*self.smooth
  234. def _call_norm(self, x1, x2):
  235. return cdist(x1.T, x2.T, self.norm)
  236. def __call__(self, *args):
  237. args = [np.asarray(x) for x in args]
  238. if not all([x.shape == y.shape for x in args for y in args]):
  239. raise ValueError("Array lengths must be equal")
  240. if self._target_dim > 1:
  241. shp = args[0].shape + (self._target_dim,)
  242. else:
  243. shp = args[0].shape
  244. xa = np.asarray([a.flatten() for a in args], dtype=np.float64)
  245. r = self._call_norm(xa, self.xi)
  246. return np.dot(self._function(r), self.nodes).reshape(shp)