_helper.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. from functools import update_wrapper, lru_cache
  2. import inspect
  3. from ._pocketfft import helper as _helper
  4. import numpy as np
  5. from scipy._lib._array_api import array_namespace
  6. from scipy._lib._array_api import xp_capabilities
  7. _init_nd_shape_and_axes = _helper._init_nd_shape_and_axes
  8. def next_fast_len(target, real=False):
  9. """Find the next fast size of input data to ``fft``, for zero-padding, etc.
  10. SciPy's FFT algorithms gain their speed by a recursive divide and conquer
  11. strategy. This relies on efficient functions for small prime factors of the
  12. input length. Thus, the transforms are fastest when using composites of the
  13. prime factors handled by the fft implementation. If there are efficient
  14. functions for all radices <= `n`, then the result will be a number `x`
  15. >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
  16. numbers)
  17. Parameters
  18. ----------
  19. target : int
  20. Length to start searching from. Must be a positive integer.
  21. real : bool, optional
  22. True if the FFT involves real input or output (e.g., `rfft` or `hfft`
  23. but not `fft`). Defaults to False.
  24. Returns
  25. -------
  26. out : int
  27. The smallest fast length greater than or equal to ``target``.
  28. Notes
  29. -----
  30. The result of this function may change in future as performance
  31. considerations change, for example, if new prime factors are added.
  32. Calling `fft` or `ifft` with real input data performs an ``'R2C'``
  33. transform internally.
  34. Examples
  35. --------
  36. On a particular machine, an FFT of prime length takes 11.4 ms:
  37. >>> from scipy import fft
  38. >>> import numpy as np
  39. >>> rng = np.random.default_rng()
  40. >>> min_len = 93059 # prime length is worst case for speed
  41. >>> a = rng.standard_normal(min_len)
  42. >>> b = fft.fft(a)
  43. Zero-padding to the next regular length reduces computation time to
  44. 1.6 ms, a speedup of 7.3 times:
  45. >>> fft.next_fast_len(min_len, real=True)
  46. 93312
  47. >>> b = fft.fft(a, 93312)
  48. Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
  49. compute; 1.9 times longer than the size given by ``next_fast_len``:
  50. >>> b = fft.fft(a, 131072)
  51. """
  52. pass
  53. # Directly wrap the c-function good_size but take the docstring etc., from the
  54. # next_fast_len function above
  55. _sig = inspect.signature(next_fast_len)
  56. next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
  57. next_fast_len = xp_capabilities(out_of_scope=True)(next_fast_len)
  58. next_fast_len.__wrapped__ = _helper.good_size
  59. next_fast_len.__signature__ = _sig
  60. def prev_fast_len(target, real=False):
  61. """Find the previous fast size of input data to ``fft``.
  62. Useful for discarding a minimal number of samples before FFT.
  63. SciPy's FFT algorithms gain their speed by a recursive divide and conquer
  64. strategy. This relies on efficient functions for small prime factors of the
  65. input length. Thus, the transforms are fastest when using composites of the
  66. prime factors handled by the fft implementation. If there are efficient
  67. functions for all radices <= `n`, then the result will be a number `x`
  68. <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth
  69. numbers)
  70. Parameters
  71. ----------
  72. target : int
  73. Maximum length to search until. Must be a positive integer.
  74. real : bool, optional
  75. True if the FFT involves real input or output (e.g., `rfft` or `hfft`
  76. but not `fft`). Defaults to False.
  77. Returns
  78. -------
  79. out : int
  80. The largest fast length less than or equal to ``target``.
  81. Notes
  82. -----
  83. The result of this function may change in future as performance
  84. considerations change, for example, if new prime factors are added.
  85. Calling `fft` or `ifft` with real input data performs an ``'R2C'``
  86. transform internally.
  87. In the current implementation, prev_fast_len assumes radices of
  88. 2,3,5,7,11 for complex FFT and 2,3,5 for real FFT.
  89. Examples
  90. --------
  91. On a particular machine, an FFT of prime length takes 16.2 ms:
  92. >>> from scipy import fft
  93. >>> import numpy as np
  94. >>> rng = np.random.default_rng()
  95. >>> max_len = 93059 # prime length is worst case for speed
  96. >>> a = rng.standard_normal(max_len)
  97. >>> b = fft.fft(a)
  98. Performing FFT on the maximum fast length less than max_len
  99. reduces the computation time to 1.5 ms, a speedup of 10.5 times:
  100. >>> fft.prev_fast_len(max_len, real=True)
  101. 92160
  102. >>> c = fft.fft(a[:92160]) # discard last 899 samples
  103. """
  104. pass
  105. # Directly wrap the c-function prev_good_size but take the docstring etc.,
  106. # from the prev_fast_len function above
  107. _sig_prev_fast_len = inspect.signature(prev_fast_len)
  108. prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len)
  109. prev_fast_len = xp_capabilities(out_of_scope=True)(prev_fast_len)
  110. prev_fast_len.__wrapped__ = _helper.prev_good_size
  111. prev_fast_len.__signature__ = _sig_prev_fast_len
  112. @xp_capabilities()
  113. def fftfreq(n, d=1.0, *, xp=None, device=None):
  114. """Return the Discrete Fourier Transform sample frequencies.
  115. The returned float array `f` contains the frequency bin centers in cycles
  116. per unit of the sample spacing (with zero at the start). For instance, if
  117. the sample spacing is in seconds, then the frequency unit is cycles/second.
  118. Given a window length `n` and a sample spacing `d`::
  119. f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even
  120. f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd
  121. Parameters
  122. ----------
  123. n : int
  124. Window length.
  125. d : scalar, optional
  126. Sample spacing (inverse of the sampling rate). Defaults to 1.
  127. xp : array_namespace, optional
  128. The namespace for the return array. Default is None, where NumPy is used.
  129. device : device, optional
  130. The device for the return array.
  131. Only valid when `xp.fft.fftfreq` implements the device parameter.
  132. Returns
  133. -------
  134. f : ndarray
  135. Array of length `n` containing the sample frequencies.
  136. Examples
  137. --------
  138. >>> import numpy as np
  139. >>> import scipy.fft
  140. >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
  141. >>> fourier = scipy.fft.fft(signal)
  142. >>> n = signal.size
  143. >>> timestep = 0.1
  144. >>> freq = scipy.fft.fftfreq(n, d=timestep)
  145. >>> freq
  146. array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25])
  147. """
  148. xp = np if xp is None else xp
  149. # numpy does not yet support the `device` keyword
  150. # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
  151. if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
  152. return xp.fft.fftfreq(n, d=d, device=device)
  153. if device is not None:
  154. raise ValueError('device parameter is not supported for input array type')
  155. return np.fft.fftfreq(n, d=d)
  156. @xp_capabilities()
  157. def rfftfreq(n, d=1.0, *, xp=None, device=None):
  158. """Return the Discrete Fourier Transform sample frequencies
  159. (for usage with rfft, irfft).
  160. The returned float array `f` contains the frequency bin centers in cycles
  161. per unit of the sample spacing (with zero at the start). For instance, if
  162. the sample spacing is in seconds, then the frequency unit is cycles/second.
  163. Given a window length `n` and a sample spacing `d`::
  164. f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even
  165. f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd
  166. Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
  167. the Nyquist frequency component is considered to be positive.
  168. Parameters
  169. ----------
  170. n : int
  171. Window length.
  172. d : scalar, optional
  173. Sample spacing (inverse of the sampling rate). Defaults to 1.
  174. xp : array_namespace, optional
  175. The namespace for the return array. Default is None, where NumPy is used.
  176. device : device, optional
  177. The device for the return array.
  178. Only valid when `xp.fft.rfftfreq` implements the device parameter.
  179. Returns
  180. -------
  181. f : ndarray
  182. Array of length ``n//2 + 1`` containing the sample frequencies.
  183. Examples
  184. --------
  185. >>> import numpy as np
  186. >>> import scipy.fft
  187. >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
  188. >>> fourier = scipy.fft.rfft(signal)
  189. >>> n = signal.size
  190. >>> sample_rate = 100
  191. >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
  192. >>> freq
  193. array([ 0., 10., 20., ..., -30., -20., -10.])
  194. >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
  195. >>> freq
  196. array([ 0., 10., 20., 30., 40., 50.])
  197. """
  198. xp = np if xp is None else xp
  199. # numpy does not yet support the `device` keyword
  200. # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
  201. if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
  202. return xp.fft.rfftfreq(n, d=d, device=device)
  203. if device is not None:
  204. raise ValueError('device parameter is not supported for input array type')
  205. return np.fft.rfftfreq(n, d=d)
  206. @xp_capabilities()
  207. def fftshift(x, axes=None):
  208. """Shift the zero-frequency component to the center of the spectrum.
  209. This function swaps half-spaces for all axes listed (defaults to all).
  210. Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
  211. Parameters
  212. ----------
  213. x : array_like
  214. Input array.
  215. axes : int or shape tuple, optional
  216. Axes over which to shift. Default is None, which shifts all axes.
  217. Returns
  218. -------
  219. y : ndarray
  220. The shifted array.
  221. See Also
  222. --------
  223. ifftshift : The inverse of `fftshift`.
  224. Examples
  225. --------
  226. >>> import numpy as np
  227. >>> freqs = np.fft.fftfreq(10, 0.1)
  228. >>> freqs
  229. array([ 0., 1., 2., ..., -3., -2., -1.])
  230. >>> np.fft.fftshift(freqs)
  231. array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
  232. Shift the zero-frequency component only along the second axis:
  233. >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
  234. >>> freqs
  235. array([[ 0., 1., 2.],
  236. [ 3., 4., -4.],
  237. [-3., -2., -1.]])
  238. >>> np.fft.fftshift(freqs, axes=(1,))
  239. array([[ 2., 0., 1.],
  240. [-4., 3., 4.],
  241. [-1., -3., -2.]])
  242. """
  243. xp = array_namespace(x)
  244. if hasattr(xp, 'fft'):
  245. return xp.fft.fftshift(x, axes=axes)
  246. x = np.asarray(x)
  247. y = np.fft.fftshift(x, axes=axes)
  248. return xp.asarray(y)
  249. @xp_capabilities()
  250. def ifftshift(x, axes=None):
  251. """The inverse of `fftshift`. Although identical for even-length `x`, the
  252. functions differ by one sample for odd-length `x`.
  253. Parameters
  254. ----------
  255. x : array_like
  256. Input array.
  257. axes : int or shape tuple, optional
  258. Axes over which to calculate. Defaults to None, which shifts all axes.
  259. Returns
  260. -------
  261. y : ndarray
  262. The shifted array.
  263. See Also
  264. --------
  265. fftshift : Shift zero-frequency component to the center of the spectrum.
  266. Examples
  267. --------
  268. >>> import numpy as np
  269. >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
  270. >>> freqs
  271. array([[ 0., 1., 2.],
  272. [ 3., 4., -4.],
  273. [-3., -2., -1.]])
  274. >>> np.fft.ifftshift(np.fft.fftshift(freqs))
  275. array([[ 0., 1., 2.],
  276. [ 3., 4., -4.],
  277. [-3., -2., -1.]])
  278. """
  279. xp = array_namespace(x)
  280. if hasattr(xp, 'fft'):
  281. return xp.fft.ifftshift(x, axes=axes)
  282. x = np.asarray(x)
  283. y = np.fft.ifftshift(x, axes=axes)
  284. return xp.asarray(y)