rbf.py 10 KB

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