_geometric_slerp.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. from __future__ import annotations
  2. __all__ = ['geometric_slerp']
  3. import warnings
  4. from typing import TYPE_CHECKING
  5. import numpy as np
  6. from scipy.spatial.distance import euclidean
  7. if TYPE_CHECKING:
  8. import numpy.typing as npt
  9. def _geometric_slerp(start, end, t):
  10. # create an orthogonal basis using QR decomposition
  11. basis = np.vstack([start, end])
  12. Q, R = np.linalg.qr(basis.T)
  13. signs = 2 * (np.diag(R) >= 0) - 1
  14. Q = Q.T * signs.T[:, np.newaxis]
  15. R = R.T * signs.T[:, np.newaxis]
  16. # calculate the angle between `start` and `end`
  17. c = np.dot(start, end)
  18. s = np.linalg.det(R)
  19. omega = np.arctan2(s, c)
  20. # interpolate
  21. start, end = Q
  22. s = np.sin(t * omega)
  23. c = np.cos(t * omega)
  24. return start * c[:, np.newaxis] + end * s[:, np.newaxis]
  25. def geometric_slerp(
  26. start: npt.ArrayLike,
  27. end: npt.ArrayLike,
  28. t: npt.ArrayLike,
  29. tol: float = 1e-7,
  30. ) -> np.ndarray:
  31. """
  32. Geometric spherical linear interpolation.
  33. The interpolation occurs along a unit-radius
  34. great circle arc in arbitrary dimensional space.
  35. Parameters
  36. ----------
  37. start : (n_dimensions, ) array-like
  38. Single n-dimensional input coordinate in a 1-D array-like
  39. object. `n` must be greater than 1.
  40. end : (n_dimensions, ) array-like
  41. Single n-dimensional input coordinate in a 1-D array-like
  42. object. `n` must be greater than 1.
  43. t : float or (n_points,) 1D array-like
  44. A float or 1D array-like of doubles representing interpolation
  45. parameters, with values required in the inclusive interval
  46. between 0 and 1. A common approach is to generate the array
  47. with ``np.linspace(0, 1, n_pts)`` for linearly spaced points.
  48. Ascending, descending, and scrambled orders are permitted.
  49. tol : float
  50. The absolute tolerance for determining if the start and end
  51. coordinates are antipodes.
  52. Returns
  53. -------
  54. result : (t.size, D)
  55. An array of doubles containing the interpolated
  56. spherical path and including start and
  57. end when 0 and 1 t are used. The
  58. interpolated values should correspond to the
  59. same sort order provided in the t array. The result
  60. may be 1-dimensional if ``t`` is a float.
  61. Raises
  62. ------
  63. ValueError
  64. If ``start`` and ``end`` are antipodes, not on the
  65. unit n-sphere, or for a variety of degenerate conditions.
  66. See Also
  67. --------
  68. scipy.spatial.transform.Slerp : 3-D Slerp that works with quaternions
  69. Notes
  70. -----
  71. The implementation is based on the mathematical formula provided in [1]_,
  72. and the first known presentation of this algorithm, derived from study of
  73. 4-D geometry, is credited to Glenn Davis in a footnote of the original
  74. quaternion Slerp publication by Ken Shoemake [2]_.
  75. .. versionadded:: 1.5.0
  76. References
  77. ----------
  78. .. [1] https://en.wikipedia.org/wiki/Slerp#Geometric_Slerp
  79. .. [2] Ken Shoemake (1985) Animating rotation with quaternion curves.
  80. ACM SIGGRAPH Computer Graphics, 19(3): 245-254.
  81. Examples
  82. --------
  83. Interpolate four linearly-spaced values on the circumference of
  84. a circle spanning 90 degrees:
  85. >>> import numpy as np
  86. >>> from scipy.spatial import geometric_slerp
  87. >>> import matplotlib.pyplot as plt
  88. >>> fig = plt.figure()
  89. >>> ax = fig.add_subplot(111)
  90. >>> start = np.array([1, 0])
  91. >>> end = np.array([0, 1])
  92. >>> t_vals = np.linspace(0, 1, 4)
  93. >>> result = geometric_slerp(start,
  94. ... end,
  95. ... t_vals)
  96. The interpolated results should be at 30 degree intervals
  97. recognizable on the unit circle:
  98. >>> ax.scatter(result[...,0], result[...,1], c='k')
  99. >>> circle = plt.Circle((0, 0), 1, color='grey')
  100. >>> ax.add_artist(circle)
  101. >>> ax.set_aspect('equal')
  102. >>> plt.show()
  103. Attempting to interpolate between antipodes on a circle is
  104. ambiguous because there are two possible paths, and on a
  105. sphere there are infinite possible paths on the geodesic surface.
  106. Nonetheless, one of the ambiguous paths is returned along
  107. with a warning:
  108. >>> opposite_pole = np.array([-1, 0])
  109. >>> with np.testing.suppress_warnings() as sup:
  110. ... sup.filter(UserWarning)
  111. ... geometric_slerp(start,
  112. ... opposite_pole,
  113. ... t_vals)
  114. array([[ 1.00000000e+00, 0.00000000e+00],
  115. [ 5.00000000e-01, 8.66025404e-01],
  116. [-5.00000000e-01, 8.66025404e-01],
  117. [-1.00000000e+00, 1.22464680e-16]])
  118. Extend the original example to a sphere and plot interpolation
  119. points in 3D:
  120. >>> from mpl_toolkits.mplot3d import proj3d
  121. >>> fig = plt.figure()
  122. >>> ax = fig.add_subplot(111, projection='3d')
  123. Plot the unit sphere for reference (optional):
  124. >>> u = np.linspace(0, 2 * np.pi, 100)
  125. >>> v = np.linspace(0, np.pi, 100)
  126. >>> x = np.outer(np.cos(u), np.sin(v))
  127. >>> y = np.outer(np.sin(u), np.sin(v))
  128. >>> z = np.outer(np.ones(np.size(u)), np.cos(v))
  129. >>> ax.plot_surface(x, y, z, color='y', alpha=0.1)
  130. Interpolating over a larger number of points
  131. may provide the appearance of a smooth curve on
  132. the surface of the sphere, which is also useful
  133. for discretized integration calculations on a
  134. sphere surface:
  135. >>> start = np.array([1, 0, 0])
  136. >>> end = np.array([0, 0, 1])
  137. >>> t_vals = np.linspace(0, 1, 200)
  138. >>> result = geometric_slerp(start,
  139. ... end,
  140. ... t_vals)
  141. >>> ax.plot(result[...,0],
  142. ... result[...,1],
  143. ... result[...,2],
  144. ... c='k')
  145. >>> plt.show()
  146. """
  147. start = np.asarray(start, dtype=np.float64)
  148. end = np.asarray(end, dtype=np.float64)
  149. t = np.asarray(t)
  150. if t.ndim > 1:
  151. raise ValueError("The interpolation parameter "
  152. "value must be one dimensional.")
  153. if start.ndim != 1 or end.ndim != 1:
  154. raise ValueError("Start and end coordinates "
  155. "must be one-dimensional")
  156. if start.size != end.size:
  157. raise ValueError("The dimensions of start and "
  158. "end must match (have same size)")
  159. if start.size < 2 or end.size < 2:
  160. raise ValueError("The start and end coordinates must "
  161. "both be in at least two-dimensional "
  162. "space")
  163. if np.array_equal(start, end):
  164. return np.linspace(start, start, t.size)
  165. # for points that violate equation for n-sphere
  166. for coord in [start, end]:
  167. if not np.allclose(np.linalg.norm(coord), 1.0,
  168. rtol=1e-9,
  169. atol=0):
  170. raise ValueError("start and end are not"
  171. " on a unit n-sphere")
  172. if not isinstance(tol, float):
  173. raise ValueError("tol must be a float")
  174. else:
  175. tol = np.fabs(tol)
  176. coord_dist = euclidean(start, end)
  177. # diameter of 2 within tolerance means antipodes, which is a problem
  178. # for all unit n-spheres (even the 0-sphere would have an ambiguous path)
  179. if np.allclose(coord_dist, 2.0, rtol=0, atol=tol):
  180. warnings.warn("start and end are antipodes"
  181. " using the specified tolerance;"
  182. " this may cause ambiguous slerp paths")
  183. t = np.asarray(t, dtype=np.float64)
  184. if t.size == 0:
  185. return np.empty((0, start.size))
  186. if t.min() < 0 or t.max() > 1:
  187. raise ValueError("interpolation parameter must be in [0, 1]")
  188. if t.ndim == 0:
  189. return _geometric_slerp(start,
  190. end,
  191. np.atleast_1d(t)).ravel()
  192. else:
  193. return _geometric_slerp(start,
  194. end,
  195. t)