_pocketfft.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. """
  2. Discrete Fourier Transforms
  3. Routines in this module:
  4. fft(a, n=None, axis=-1, norm="backward")
  5. ifft(a, n=None, axis=-1, norm="backward")
  6. rfft(a, n=None, axis=-1, norm="backward")
  7. irfft(a, n=None, axis=-1, norm="backward")
  8. hfft(a, n=None, axis=-1, norm="backward")
  9. ihfft(a, n=None, axis=-1, norm="backward")
  10. fftn(a, s=None, axes=None, norm="backward")
  11. ifftn(a, s=None, axes=None, norm="backward")
  12. rfftn(a, s=None, axes=None, norm="backward")
  13. irfftn(a, s=None, axes=None, norm="backward")
  14. fft2(a, s=None, axes=(-2,-1), norm="backward")
  15. ifft2(a, s=None, axes=(-2, -1), norm="backward")
  16. rfft2(a, s=None, axes=(-2,-1), norm="backward")
  17. irfft2(a, s=None, axes=(-2, -1), norm="backward")
  18. i = inverse transform
  19. r = transform of purely real data
  20. h = Hermite transform
  21. n = n-dimensional transform
  22. 2 = 2-dimensional transform
  23. (Note: 2D routines are just nD routines with different default
  24. behavior.)
  25. """
  26. __all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn',
  27. 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn']
  28. import functools
  29. from numpy.core import asarray, zeros, swapaxes, conjugate, take, sqrt
  30. from . import _pocketfft_internal as pfi
  31. from numpy.core.multiarray import normalize_axis_index
  32. from numpy.core import overrides
  33. array_function_dispatch = functools.partial(
  34. overrides.array_function_dispatch, module='numpy.fft')
  35. # `inv_norm` is a float by which the result of the transform needs to be
  36. # divided. This replaces the original, more intuitive 'fct` parameter to avoid
  37. # divisions by zero (or alternatively additional checks) in the case of
  38. # zero-length axes during its computation.
  39. def _raw_fft(a, n, axis, is_real, is_forward, inv_norm):
  40. axis = normalize_axis_index(axis, a.ndim)
  41. if n is None:
  42. n = a.shape[axis]
  43. fct = 1/inv_norm
  44. if a.shape[axis] != n:
  45. s = list(a.shape)
  46. index = [slice(None)]*len(s)
  47. if s[axis] > n:
  48. index[axis] = slice(0, n)
  49. a = a[tuple(index)]
  50. else:
  51. index[axis] = slice(0, s[axis])
  52. s[axis] = n
  53. z = zeros(s, a.dtype.char)
  54. z[tuple(index)] = a
  55. a = z
  56. if axis == a.ndim-1:
  57. r = pfi.execute(a, is_real, is_forward, fct)
  58. else:
  59. a = swapaxes(a, axis, -1)
  60. r = pfi.execute(a, is_real, is_forward, fct)
  61. r = swapaxes(r, axis, -1)
  62. return r
  63. def _get_forward_norm(n, norm):
  64. if n < 1:
  65. raise ValueError(f"Invalid number of FFT data points ({n}) specified.")
  66. if norm is None or norm == "backward":
  67. return 1
  68. elif norm == "ortho":
  69. return sqrt(n)
  70. elif norm == "forward":
  71. return n
  72. raise ValueError(f'Invalid norm value {norm}; should be "backward",'
  73. '"ortho" or "forward".')
  74. def _get_backward_norm(n, norm):
  75. if n < 1:
  76. raise ValueError(f"Invalid number of FFT data points ({n}) specified.")
  77. if norm is None or norm == "backward":
  78. return n
  79. elif norm == "ortho":
  80. return sqrt(n)
  81. elif norm == "forward":
  82. return 1
  83. raise ValueError(f'Invalid norm value {norm}; should be "backward", '
  84. '"ortho" or "forward".')
  85. _SWAP_DIRECTION_MAP = {"backward": "forward", None: "forward",
  86. "ortho": "ortho", "forward": "backward"}
  87. def _swap_direction(norm):
  88. try:
  89. return _SWAP_DIRECTION_MAP[norm]
  90. except KeyError:
  91. raise ValueError(f'Invalid norm value {norm}; should be "backward", '
  92. '"ortho" or "forward".')
  93. def _fft_dispatcher(a, n=None, axis=None, norm=None):
  94. return (a,)
  95. @array_function_dispatch(_fft_dispatcher)
  96. def fft(a, n=None, axis=-1, norm=None):
  97. """
  98. Compute the one-dimensional discrete Fourier Transform.
  99. This function computes the one-dimensional *n*-point discrete Fourier
  100. Transform (DFT) with the efficient Fast Fourier Transform (FFT)
  101. algorithm [CT].
  102. Parameters
  103. ----------
  104. a : array_like
  105. Input array, can be complex.
  106. n : int, optional
  107. Length of the transformed axis of the output.
  108. If `n` is smaller than the length of the input, the input is cropped.
  109. If it is larger, the input is padded with zeros. If `n` is not given,
  110. the length of the input along the axis specified by `axis` is used.
  111. axis : int, optional
  112. Axis over which to compute the FFT. If not given, the last axis is
  113. used.
  114. norm : {"backward", "ortho", "forward"}, optional
  115. .. versionadded:: 1.10.0
  116. Normalization mode (see `numpy.fft`). Default is "backward".
  117. Indicates which direction of the forward/backward pair of transforms
  118. is scaled and with what normalization factor.
  119. .. versionadded:: 1.20.0
  120. The "backward", "forward" values were added.
  121. Returns
  122. -------
  123. out : complex ndarray
  124. The truncated or zero-padded input, transformed along the axis
  125. indicated by `axis`, or the last one if `axis` is not specified.
  126. Raises
  127. ------
  128. IndexError
  129. if `axes` is larger than the last axis of `a`.
  130. See Also
  131. --------
  132. numpy.fft : for definition of the DFT and conventions used.
  133. ifft : The inverse of `fft`.
  134. fft2 : The two-dimensional FFT.
  135. fftn : The *n*-dimensional FFT.
  136. rfftn : The *n*-dimensional FFT of real input.
  137. fftfreq : Frequency bins for given FFT parameters.
  138. Notes
  139. -----
  140. FFT (Fast Fourier Transform) refers to a way the discrete Fourier
  141. Transform (DFT) can be calculated efficiently, by using symmetries in the
  142. calculated terms. The symmetry is highest when `n` is a power of 2, and
  143. the transform is therefore most efficient for these sizes.
  144. The DFT is defined, with the conventions used in this implementation, in
  145. the documentation for the `numpy.fft` module.
  146. References
  147. ----------
  148. .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
  149. machine calculation of complex Fourier series," *Math. Comput.*
  150. 19: 297-301.
  151. Examples
  152. --------
  153. >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
  154. array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,
  155. 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,
  156. -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,
  157. 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])
  158. In this example, real input has an FFT which is Hermitian, i.e., symmetric
  159. in the real part and anti-symmetric in the imaginary part, as described in
  160. the `numpy.fft` documentation:
  161. >>> import matplotlib.pyplot as plt
  162. >>> t = np.arange(256)
  163. >>> sp = np.fft.fft(np.sin(t))
  164. >>> freq = np.fft.fftfreq(t.shape[-1])
  165. >>> plt.plot(freq, sp.real, freq, sp.imag)
  166. [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
  167. >>> plt.show()
  168. """
  169. a = asarray(a)
  170. if n is None:
  171. n = a.shape[axis]
  172. inv_norm = _get_forward_norm(n, norm)
  173. output = _raw_fft(a, n, axis, False, True, inv_norm)
  174. return output
  175. @array_function_dispatch(_fft_dispatcher)
  176. def ifft(a, n=None, axis=-1, norm=None):
  177. """
  178. Compute the one-dimensional inverse discrete Fourier Transform.
  179. This function computes the inverse of the one-dimensional *n*-point
  180. discrete Fourier transform computed by `fft`. In other words,
  181. ``ifft(fft(a)) == a`` to within numerical accuracy.
  182. For a general description of the algorithm and definitions,
  183. see `numpy.fft`.
  184. The input should be ordered in the same way as is returned by `fft`,
  185. i.e.,
  186. * ``a[0]`` should contain the zero frequency term,
  187. * ``a[1:n//2]`` should contain the positive-frequency terms,
  188. * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in
  189. increasing order starting from the most negative frequency.
  190. For an even number of input points, ``A[n//2]`` represents the sum of
  191. the values at the positive and negative Nyquist frequencies, as the two
  192. are aliased together. See `numpy.fft` for details.
  193. Parameters
  194. ----------
  195. a : array_like
  196. Input array, can be complex.
  197. n : int, optional
  198. Length of the transformed axis of the output.
  199. If `n` is smaller than the length of the input, the input is cropped.
  200. If it is larger, the input is padded with zeros. If `n` is not given,
  201. the length of the input along the axis specified by `axis` is used.
  202. See notes about padding issues.
  203. axis : int, optional
  204. Axis over which to compute the inverse DFT. If not given, the last
  205. axis is used.
  206. norm : {"backward", "ortho", "forward"}, optional
  207. .. versionadded:: 1.10.0
  208. Normalization mode (see `numpy.fft`). Default is "backward".
  209. Indicates which direction of the forward/backward pair of transforms
  210. is scaled and with what normalization factor.
  211. .. versionadded:: 1.20.0
  212. The "backward", "forward" values were added.
  213. Returns
  214. -------
  215. out : complex ndarray
  216. The truncated or zero-padded input, transformed along the axis
  217. indicated by `axis`, or the last one if `axis` is not specified.
  218. Raises
  219. ------
  220. IndexError
  221. If `axes` is larger than the last axis of `a`.
  222. See Also
  223. --------
  224. numpy.fft : An introduction, with definitions and general explanations.
  225. fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse
  226. ifft2 : The two-dimensional inverse FFT.
  227. ifftn : The n-dimensional inverse FFT.
  228. Notes
  229. -----
  230. If the input parameter `n` is larger than the size of the input, the input
  231. is padded by appending zeros at the end. Even though this is the common
  232. approach, it might lead to surprising results. If a different padding is
  233. desired, it must be performed before calling `ifft`.
  234. Examples
  235. --------
  236. >>> np.fft.ifft([0, 4, 0, 0])
  237. array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary
  238. Create and plot a band-limited signal with random phases:
  239. >>> import matplotlib.pyplot as plt
  240. >>> t = np.arange(400)
  241. >>> n = np.zeros((400,), dtype=complex)
  242. >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))
  243. >>> s = np.fft.ifft(n)
  244. >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
  245. [<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
  246. >>> plt.legend(('real', 'imaginary'))
  247. <matplotlib.legend.Legend object at ...>
  248. >>> plt.show()
  249. """
  250. a = asarray(a)
  251. if n is None:
  252. n = a.shape[axis]
  253. inv_norm = _get_backward_norm(n, norm)
  254. output = _raw_fft(a, n, axis, False, False, inv_norm)
  255. return output
  256. @array_function_dispatch(_fft_dispatcher)
  257. def rfft(a, n=None, axis=-1, norm=None):
  258. """
  259. Compute the one-dimensional discrete Fourier Transform for real input.
  260. This function computes the one-dimensional *n*-point discrete Fourier
  261. Transform (DFT) of a real-valued array by means of an efficient algorithm
  262. called the Fast Fourier Transform (FFT).
  263. Parameters
  264. ----------
  265. a : array_like
  266. Input array
  267. n : int, optional
  268. Number of points along transformation axis in the input to use.
  269. If `n` is smaller than the length of the input, the input is cropped.
  270. If it is larger, the input is padded with zeros. If `n` is not given,
  271. the length of the input along the axis specified by `axis` is used.
  272. axis : int, optional
  273. Axis over which to compute the FFT. If not given, the last axis is
  274. used.
  275. norm : {"backward", "ortho", "forward"}, optional
  276. .. versionadded:: 1.10.0
  277. Normalization mode (see `numpy.fft`). Default is "backward".
  278. Indicates which direction of the forward/backward pair of transforms
  279. is scaled and with what normalization factor.
  280. .. versionadded:: 1.20.0
  281. The "backward", "forward" values were added.
  282. Returns
  283. -------
  284. out : complex ndarray
  285. The truncated or zero-padded input, transformed along the axis
  286. indicated by `axis`, or the last one if `axis` is not specified.
  287. If `n` is even, the length of the transformed axis is ``(n/2)+1``.
  288. If `n` is odd, the length is ``(n+1)/2``.
  289. Raises
  290. ------
  291. IndexError
  292. If `axis` is larger than the last axis of `a`.
  293. See Also
  294. --------
  295. numpy.fft : For definition of the DFT and conventions used.
  296. irfft : The inverse of `rfft`.
  297. fft : The one-dimensional FFT of general (complex) input.
  298. fftn : The *n*-dimensional FFT.
  299. rfftn : The *n*-dimensional FFT of real input.
  300. Notes
  301. -----
  302. When the DFT is computed for purely real input, the output is
  303. Hermitian-symmetric, i.e. the negative frequency terms are just the complex
  304. conjugates of the corresponding positive-frequency terms, and the
  305. negative-frequency terms are therefore redundant. This function does not
  306. compute the negative frequency terms, and the length of the transformed
  307. axis of the output is therefore ``n//2 + 1``.
  308. When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains
  309. the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
  310. If `n` is even, ``A[-1]`` contains the term representing both positive
  311. and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
  312. real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
  313. the largest positive frequency (fs/2*(n-1)/n), and is complex in the
  314. general case.
  315. If the input `a` contains an imaginary part, it is silently discarded.
  316. Examples
  317. --------
  318. >>> np.fft.fft([0, 1, 0, 0])
  319. array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
  320. >>> np.fft.rfft([0, 1, 0, 0])
  321. array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
  322. Notice how the final element of the `fft` output is the complex conjugate
  323. of the second element, for real input. For `rfft`, this symmetry is
  324. exploited to compute only the non-negative frequency terms.
  325. """
  326. a = asarray(a)
  327. if n is None:
  328. n = a.shape[axis]
  329. inv_norm = _get_forward_norm(n, norm)
  330. output = _raw_fft(a, n, axis, True, True, inv_norm)
  331. return output
  332. @array_function_dispatch(_fft_dispatcher)
  333. def irfft(a, n=None, axis=-1, norm=None):
  334. """
  335. Computes the inverse of `rfft`.
  336. This function computes the inverse of the one-dimensional *n*-point
  337. discrete Fourier Transform of real input computed by `rfft`.
  338. In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
  339. accuracy. (See Notes below for why ``len(a)`` is necessary here.)
  340. The input is expected to be in the form returned by `rfft`, i.e. the
  341. real zero-frequency term followed by the complex positive frequency terms
  342. in order of increasing frequency. Since the discrete Fourier Transform of
  343. real input is Hermitian-symmetric, the negative frequency terms are taken
  344. to be the complex conjugates of the corresponding positive frequency terms.
  345. Parameters
  346. ----------
  347. a : array_like
  348. The input array.
  349. n : int, optional
  350. Length of the transformed axis of the output.
  351. For `n` output points, ``n//2+1`` input points are necessary. If the
  352. input is longer than this, it is cropped. If it is shorter than this,
  353. it is padded with zeros. If `n` is not given, it is taken to be
  354. ``2*(m-1)`` where ``m`` is the length of the input along the axis
  355. specified by `axis`.
  356. axis : int, optional
  357. Axis over which to compute the inverse FFT. If not given, the last
  358. axis is used.
  359. norm : {"backward", "ortho", "forward"}, optional
  360. .. versionadded:: 1.10.0
  361. Normalization mode (see `numpy.fft`). Default is "backward".
  362. Indicates which direction of the forward/backward pair of transforms
  363. is scaled and with what normalization factor.
  364. .. versionadded:: 1.20.0
  365. The "backward", "forward" values were added.
  366. Returns
  367. -------
  368. out : ndarray
  369. The truncated or zero-padded input, transformed along the axis
  370. indicated by `axis`, or the last one if `axis` is not specified.
  371. The length of the transformed axis is `n`, or, if `n` is not given,
  372. ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
  373. input. To get an odd number of output points, `n` must be specified.
  374. Raises
  375. ------
  376. IndexError
  377. If `axis` is larger than the last axis of `a`.
  378. See Also
  379. --------
  380. numpy.fft : For definition of the DFT and conventions used.
  381. rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
  382. fft : The one-dimensional FFT.
  383. irfft2 : The inverse of the two-dimensional FFT of real input.
  384. irfftn : The inverse of the *n*-dimensional FFT of real input.
  385. Notes
  386. -----
  387. Returns the real valued `n`-point inverse discrete Fourier transform
  388. of `a`, where `a` contains the non-negative frequency terms of a
  389. Hermitian-symmetric sequence. `n` is the length of the result, not the
  390. input.
  391. If you specify an `n` such that `a` must be zero-padded or truncated, the
  392. extra/removed values will be added/removed at high frequencies. One can
  393. thus resample a series to `m` points via Fourier interpolation by:
  394. ``a_resamp = irfft(rfft(a), m)``.
  395. The correct interpretation of the hermitian input depends on the length of
  396. the original data, as given by `n`. This is because each input shape could
  397. correspond to either an odd or even length signal. By default, `irfft`
  398. assumes an even output length which puts the last entry at the Nyquist
  399. frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
  400. the value is thus treated as purely real. To avoid losing information, the
  401. correct length of the real input **must** be given.
  402. Examples
  403. --------
  404. >>> np.fft.ifft([1, -1j, -1, 1j])
  405. array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
  406. >>> np.fft.irfft([1, -1j, -1])
  407. array([0., 1., 0., 0.])
  408. Notice how the last term in the input to the ordinary `ifft` is the
  409. complex conjugate of the second term, and the output has zero imaginary
  410. part everywhere. When calling `irfft`, the negative frequencies are not
  411. specified, and the output array is purely real.
  412. """
  413. a = asarray(a)
  414. if n is None:
  415. n = (a.shape[axis] - 1) * 2
  416. inv_norm = _get_backward_norm(n, norm)
  417. output = _raw_fft(a, n, axis, True, False, inv_norm)
  418. return output
  419. @array_function_dispatch(_fft_dispatcher)
  420. def hfft(a, n=None, axis=-1, norm=None):
  421. """
  422. Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
  423. spectrum.
  424. Parameters
  425. ----------
  426. a : array_like
  427. The input array.
  428. n : int, optional
  429. Length of the transformed axis of the output. For `n` output
  430. points, ``n//2 + 1`` input points are necessary. If the input is
  431. longer than this, it is cropped. If it is shorter than this, it is
  432. padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``
  433. where ``m`` is the length of the input along the axis specified by
  434. `axis`.
  435. axis : int, optional
  436. Axis over which to compute the FFT. If not given, the last
  437. axis is used.
  438. norm : {"backward", "ortho", "forward"}, optional
  439. .. versionadded:: 1.10.0
  440. Normalization mode (see `numpy.fft`). Default is "backward".
  441. Indicates which direction of the forward/backward pair of transforms
  442. is scaled and with what normalization factor.
  443. .. versionadded:: 1.20.0
  444. The "backward", "forward" values were added.
  445. Returns
  446. -------
  447. out : ndarray
  448. The truncated or zero-padded input, transformed along the axis
  449. indicated by `axis`, or the last one if `axis` is not specified.
  450. The length of the transformed axis is `n`, or, if `n` is not given,
  451. ``2*m - 2`` where ``m`` is the length of the transformed axis of
  452. the input. To get an odd number of output points, `n` must be
  453. specified, for instance as ``2*m - 1`` in the typical case,
  454. Raises
  455. ------
  456. IndexError
  457. If `axis` is larger than the last axis of `a`.
  458. See also
  459. --------
  460. rfft : Compute the one-dimensional FFT for real input.
  461. ihfft : The inverse of `hfft`.
  462. Notes
  463. -----
  464. `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
  465. opposite case: here the signal has Hermitian symmetry in the time
  466. domain and is real in the frequency domain. So here it's `hfft` for
  467. which you must supply the length of the result if it is to be odd.
  468. * even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,
  469. * odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.
  470. The correct interpretation of the hermitian input depends on the length of
  471. the original data, as given by `n`. This is because each input shape could
  472. correspond to either an odd or even length signal. By default, `hfft`
  473. assumes an even output length which puts the last entry at the Nyquist
  474. frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
  475. the value is thus treated as purely real. To avoid losing information, the
  476. shape of the full signal **must** be given.
  477. Examples
  478. --------
  479. >>> signal = np.array([1, 2, 3, 4, 3, 2])
  480. >>> np.fft.fft(signal)
  481. array([15.+0.j, -4.+0.j, 0.+0.j, -1.-0.j, 0.+0.j, -4.+0.j]) # may vary
  482. >>> np.fft.hfft(signal[:4]) # Input first half of signal
  483. array([15., -4., 0., -1., 0., -4.])
  484. >>> np.fft.hfft(signal, 6) # Input entire signal and truncate
  485. array([15., -4., 0., -1., 0., -4.])
  486. >>> signal = np.array([[1, 1.j], [-1.j, 2]])
  487. >>> np.conj(signal.T) - signal # check Hermitian symmetry
  488. array([[ 0.-0.j, -0.+0.j], # may vary
  489. [ 0.+0.j, 0.-0.j]])
  490. >>> freq_spectrum = np.fft.hfft(signal)
  491. >>> freq_spectrum
  492. array([[ 1., 1.],
  493. [ 2., -2.]])
  494. """
  495. a = asarray(a)
  496. if n is None:
  497. n = (a.shape[axis] - 1) * 2
  498. new_norm = _swap_direction(norm)
  499. output = irfft(conjugate(a), n, axis, norm=new_norm)
  500. return output
  501. @array_function_dispatch(_fft_dispatcher)
  502. def ihfft(a, n=None, axis=-1, norm=None):
  503. """
  504. Compute the inverse FFT of a signal that has Hermitian symmetry.
  505. Parameters
  506. ----------
  507. a : array_like
  508. Input array.
  509. n : int, optional
  510. Length of the inverse FFT, the number of points along
  511. transformation axis in the input to use. If `n` is smaller than
  512. the length of the input, the input is cropped. If it is larger,
  513. the input is padded with zeros. If `n` is not given, the length of
  514. the input along the axis specified by `axis` is used.
  515. axis : int, optional
  516. Axis over which to compute the inverse FFT. If not given, the last
  517. axis is used.
  518. norm : {"backward", "ortho", "forward"}, optional
  519. .. versionadded:: 1.10.0
  520. Normalization mode (see `numpy.fft`). Default is "backward".
  521. Indicates which direction of the forward/backward pair of transforms
  522. is scaled and with what normalization factor.
  523. .. versionadded:: 1.20.0
  524. The "backward", "forward" values were added.
  525. Returns
  526. -------
  527. out : complex ndarray
  528. The truncated or zero-padded input, transformed along the axis
  529. indicated by `axis`, or the last one if `axis` is not specified.
  530. The length of the transformed axis is ``n//2 + 1``.
  531. See also
  532. --------
  533. hfft, irfft
  534. Notes
  535. -----
  536. `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
  537. opposite case: here the signal has Hermitian symmetry in the time
  538. domain and is real in the frequency domain. So here it's `hfft` for
  539. which you must supply the length of the result if it is to be odd:
  540. * even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,
  541. * odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.
  542. Examples
  543. --------
  544. >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
  545. >>> np.fft.ifft(spectrum)
  546. array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary
  547. >>> np.fft.ihfft(spectrum)
  548. array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary
  549. """
  550. a = asarray(a)
  551. if n is None:
  552. n = a.shape[axis]
  553. new_norm = _swap_direction(norm)
  554. output = conjugate(rfft(a, n, axis, norm=new_norm))
  555. return output
  556. def _cook_nd_args(a, s=None, axes=None, invreal=0):
  557. if s is None:
  558. shapeless = 1
  559. if axes is None:
  560. s = list(a.shape)
  561. else:
  562. s = take(a.shape, axes)
  563. else:
  564. shapeless = 0
  565. s = list(s)
  566. if axes is None:
  567. axes = list(range(-len(s), 0))
  568. if len(s) != len(axes):
  569. raise ValueError("Shape and axes have different lengths.")
  570. if invreal and shapeless:
  571. s[-1] = (a.shape[axes[-1]] - 1) * 2
  572. return s, axes
  573. def _raw_fftnd(a, s=None, axes=None, function=fft, norm=None):
  574. a = asarray(a)
  575. s, axes = _cook_nd_args(a, s, axes)
  576. itl = list(range(len(axes)))
  577. itl.reverse()
  578. for ii in itl:
  579. a = function(a, n=s[ii], axis=axes[ii], norm=norm)
  580. return a
  581. def _fftn_dispatcher(a, s=None, axes=None, norm=None):
  582. return (a,)
  583. @array_function_dispatch(_fftn_dispatcher)
  584. def fftn(a, s=None, axes=None, norm=None):
  585. """
  586. Compute the N-dimensional discrete Fourier Transform.
  587. This function computes the *N*-dimensional discrete Fourier Transform over
  588. any number of axes in an *M*-dimensional array by means of the Fast Fourier
  589. Transform (FFT).
  590. Parameters
  591. ----------
  592. a : array_like
  593. Input array, can be complex.
  594. s : sequence of ints, optional
  595. Shape (length of each transformed axis) of the output
  596. (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
  597. This corresponds to ``n`` for ``fft(x, n)``.
  598. Along any axis, if the given shape is smaller than that of the input,
  599. the input is cropped. If it is larger, the input is padded with zeros.
  600. if `s` is not given, the shape of the input along the axes specified
  601. by `axes` is used.
  602. axes : sequence of ints, optional
  603. Axes over which to compute the FFT. If not given, the last ``len(s)``
  604. axes are used, or all axes if `s` is also not specified.
  605. Repeated indices in `axes` means that the transform over that axis is
  606. performed multiple times.
  607. norm : {"backward", "ortho", "forward"}, optional
  608. .. versionadded:: 1.10.0
  609. Normalization mode (see `numpy.fft`). Default is "backward".
  610. Indicates which direction of the forward/backward pair of transforms
  611. is scaled and with what normalization factor.
  612. .. versionadded:: 1.20.0
  613. The "backward", "forward" values were added.
  614. Returns
  615. -------
  616. out : complex ndarray
  617. The truncated or zero-padded input, transformed along the axes
  618. indicated by `axes`, or by a combination of `s` and `a`,
  619. as explained in the parameters section above.
  620. Raises
  621. ------
  622. ValueError
  623. If `s` and `axes` have different length.
  624. IndexError
  625. If an element of `axes` is larger than than the number of axes of `a`.
  626. See Also
  627. --------
  628. numpy.fft : Overall view of discrete Fourier transforms, with definitions
  629. and conventions used.
  630. ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT.
  631. fft : The one-dimensional FFT, with definitions and conventions used.
  632. rfftn : The *n*-dimensional FFT of real input.
  633. fft2 : The two-dimensional FFT.
  634. fftshift : Shifts zero-frequency terms to centre of array
  635. Notes
  636. -----
  637. The output, analogously to `fft`, contains the term for zero frequency in
  638. the low-order corner of all axes, the positive frequency terms in the
  639. first half of all axes, the term for the Nyquist frequency in the middle
  640. of all axes and the negative frequency terms in the second half of all
  641. axes, in order of decreasingly negative frequency.
  642. See `numpy.fft` for details, definitions and conventions used.
  643. Examples
  644. --------
  645. >>> a = np.mgrid[:3, :3, :3][0]
  646. >>> np.fft.fftn(a, axes=(1, 2))
  647. array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary
  648. [ 0.+0.j, 0.+0.j, 0.+0.j],
  649. [ 0.+0.j, 0.+0.j, 0.+0.j]],
  650. [[ 9.+0.j, 0.+0.j, 0.+0.j],
  651. [ 0.+0.j, 0.+0.j, 0.+0.j],
  652. [ 0.+0.j, 0.+0.j, 0.+0.j]],
  653. [[18.+0.j, 0.+0.j, 0.+0.j],
  654. [ 0.+0.j, 0.+0.j, 0.+0.j],
  655. [ 0.+0.j, 0.+0.j, 0.+0.j]]])
  656. >>> np.fft.fftn(a, (2, 2), axes=(0, 1))
  657. array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary
  658. [ 0.+0.j, 0.+0.j, 0.+0.j]],
  659. [[-2.+0.j, -2.+0.j, -2.+0.j],
  660. [ 0.+0.j, 0.+0.j, 0.+0.j]]])
  661. >>> import matplotlib.pyplot as plt
  662. >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
  663. ... 2 * np.pi * np.arange(200) / 34)
  664. >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)
  665. >>> FS = np.fft.fftn(S)
  666. >>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2))
  667. <matplotlib.image.AxesImage object at 0x...>
  668. >>> plt.show()
  669. """
  670. return _raw_fftnd(a, s, axes, fft, norm)
  671. @array_function_dispatch(_fftn_dispatcher)
  672. def ifftn(a, s=None, axes=None, norm=None):
  673. """
  674. Compute the N-dimensional inverse discrete Fourier Transform.
  675. This function computes the inverse of the N-dimensional discrete
  676. Fourier Transform over any number of axes in an M-dimensional array by
  677. means of the Fast Fourier Transform (FFT). In other words,
  678. ``ifftn(fftn(a)) == a`` to within numerical accuracy.
  679. For a description of the definitions and conventions used, see `numpy.fft`.
  680. The input, analogously to `ifft`, should be ordered in the same way as is
  681. returned by `fftn`, i.e. it should have the term for zero frequency
  682. in all axes in the low-order corner, the positive frequency terms in the
  683. first half of all axes, the term for the Nyquist frequency in the middle
  684. of all axes and the negative frequency terms in the second half of all
  685. axes, in order of decreasingly negative frequency.
  686. Parameters
  687. ----------
  688. a : array_like
  689. Input array, can be complex.
  690. s : sequence of ints, optional
  691. Shape (length of each transformed axis) of the output
  692. (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
  693. This corresponds to ``n`` for ``ifft(x, n)``.
  694. Along any axis, if the given shape is smaller than that of the input,
  695. the input is cropped. If it is larger, the input is padded with zeros.
  696. if `s` is not given, the shape of the input along the axes specified
  697. by `axes` is used. See notes for issue on `ifft` zero padding.
  698. axes : sequence of ints, optional
  699. Axes over which to compute the IFFT. If not given, the last ``len(s)``
  700. axes are used, or all axes if `s` is also not specified.
  701. Repeated indices in `axes` means that the inverse transform over that
  702. axis is performed multiple times.
  703. norm : {"backward", "ortho", "forward"}, optional
  704. .. versionadded:: 1.10.0
  705. Normalization mode (see `numpy.fft`). Default is "backward".
  706. Indicates which direction of the forward/backward pair of transforms
  707. is scaled and with what normalization factor.
  708. .. versionadded:: 1.20.0
  709. The "backward", "forward" values were added.
  710. Returns
  711. -------
  712. out : complex ndarray
  713. The truncated or zero-padded input, transformed along the axes
  714. indicated by `axes`, or by a combination of `s` or `a`,
  715. as explained in the parameters section above.
  716. Raises
  717. ------
  718. ValueError
  719. If `s` and `axes` have different length.
  720. IndexError
  721. If an element of `axes` is larger than than the number of axes of `a`.
  722. See Also
  723. --------
  724. numpy.fft : Overall view of discrete Fourier transforms, with definitions
  725. and conventions used.
  726. fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.
  727. ifft : The one-dimensional inverse FFT.
  728. ifft2 : The two-dimensional inverse FFT.
  729. ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
  730. of array.
  731. Notes
  732. -----
  733. See `numpy.fft` for definitions and conventions used.
  734. Zero-padding, analogously with `ifft`, is performed by appending zeros to
  735. the input along the specified dimension. Although this is the common
  736. approach, it might lead to surprising results. If another form of zero
  737. padding is desired, it must be performed before `ifftn` is called.
  738. Examples
  739. --------
  740. >>> a = np.eye(4)
  741. >>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))
  742. array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
  743. [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
  744. [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
  745. [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
  746. Create and plot an image with band-limited frequency content:
  747. >>> import matplotlib.pyplot as plt
  748. >>> n = np.zeros((200,200), dtype=complex)
  749. >>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))
  750. >>> im = np.fft.ifftn(n).real
  751. >>> plt.imshow(im)
  752. <matplotlib.image.AxesImage object at 0x...>
  753. >>> plt.show()
  754. """
  755. return _raw_fftnd(a, s, axes, ifft, norm)
  756. @array_function_dispatch(_fftn_dispatcher)
  757. def fft2(a, s=None, axes=(-2, -1), norm=None):
  758. """
  759. Compute the 2-dimensional discrete Fourier Transform.
  760. This function computes the *n*-dimensional discrete Fourier Transform
  761. over any axes in an *M*-dimensional array by means of the
  762. Fast Fourier Transform (FFT). By default, the transform is computed over
  763. the last two axes of the input array, i.e., a 2-dimensional FFT.
  764. Parameters
  765. ----------
  766. a : array_like
  767. Input array, can be complex
  768. s : sequence of ints, optional
  769. Shape (length of each transformed axis) of the output
  770. (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
  771. This corresponds to ``n`` for ``fft(x, n)``.
  772. Along each axis, if the given shape is smaller than that of the input,
  773. the input is cropped. If it is larger, the input is padded with zeros.
  774. if `s` is not given, the shape of the input along the axes specified
  775. by `axes` is used.
  776. axes : sequence of ints, optional
  777. Axes over which to compute the FFT. If not given, the last two
  778. axes are used. A repeated index in `axes` means the transform over
  779. that axis is performed multiple times. A one-element sequence means
  780. that a one-dimensional FFT is performed.
  781. norm : {"backward", "ortho", "forward"}, optional
  782. .. versionadded:: 1.10.0
  783. Normalization mode (see `numpy.fft`). Default is "backward".
  784. Indicates which direction of the forward/backward pair of transforms
  785. is scaled and with what normalization factor.
  786. .. versionadded:: 1.20.0
  787. The "backward", "forward" values were added.
  788. Returns
  789. -------
  790. out : complex ndarray
  791. The truncated or zero-padded input, transformed along the axes
  792. indicated by `axes`, or the last two axes if `axes` is not given.
  793. Raises
  794. ------
  795. ValueError
  796. If `s` and `axes` have different length, or `axes` not given and
  797. ``len(s) != 2``.
  798. IndexError
  799. If an element of `axes` is larger than than the number of axes of `a`.
  800. See Also
  801. --------
  802. numpy.fft : Overall view of discrete Fourier transforms, with definitions
  803. and conventions used.
  804. ifft2 : The inverse two-dimensional FFT.
  805. fft : The one-dimensional FFT.
  806. fftn : The *n*-dimensional FFT.
  807. fftshift : Shifts zero-frequency terms to the center of the array.
  808. For two-dimensional input, swaps first and third quadrants, and second
  809. and fourth quadrants.
  810. Notes
  811. -----
  812. `fft2` is just `fftn` with a different default for `axes`.
  813. The output, analogously to `fft`, contains the term for zero frequency in
  814. the low-order corner of the transformed axes, the positive frequency terms
  815. in the first half of these axes, the term for the Nyquist frequency in the
  816. middle of the axes and the negative frequency terms in the second half of
  817. the axes, in order of decreasingly negative frequency.
  818. See `fftn` for details and a plotting example, and `numpy.fft` for
  819. definitions and conventions used.
  820. Examples
  821. --------
  822. >>> a = np.mgrid[:5, :5][0]
  823. >>> np.fft.fft2(a)
  824. array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary
  825. 0. +0.j , 0. +0.j ],
  826. [-12.5+17.20477401j, 0. +0.j , 0. +0.j ,
  827. 0. +0.j , 0. +0.j ],
  828. [-12.5 +4.0614962j , 0. +0.j , 0. +0.j ,
  829. 0. +0.j , 0. +0.j ],
  830. [-12.5 -4.0614962j , 0. +0.j , 0. +0.j ,
  831. 0. +0.j , 0. +0.j ],
  832. [-12.5-17.20477401j, 0. +0.j , 0. +0.j ,
  833. 0. +0.j , 0. +0.j ]])
  834. """
  835. return _raw_fftnd(a, s, axes, fft, norm)
  836. @array_function_dispatch(_fftn_dispatcher)
  837. def ifft2(a, s=None, axes=(-2, -1), norm=None):
  838. """
  839. Compute the 2-dimensional inverse discrete Fourier Transform.
  840. This function computes the inverse of the 2-dimensional discrete Fourier
  841. Transform over any number of axes in an M-dimensional array by means of
  842. the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a``
  843. to within numerical accuracy. By default, the inverse transform is
  844. computed over the last two axes of the input array.
  845. The input, analogously to `ifft`, should be ordered in the same way as is
  846. returned by `fft2`, i.e. it should have the term for zero frequency
  847. in the low-order corner of the two axes, the positive frequency terms in
  848. the first half of these axes, the term for the Nyquist frequency in the
  849. middle of the axes and the negative frequency terms in the second half of
  850. both axes, in order of decreasingly negative frequency.
  851. Parameters
  852. ----------
  853. a : array_like
  854. Input array, can be complex.
  855. s : sequence of ints, optional
  856. Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
  857. ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
  858. Along each axis, if the given shape is smaller than that of the input,
  859. the input is cropped. If it is larger, the input is padded with zeros.
  860. if `s` is not given, the shape of the input along the axes specified
  861. by `axes` is used. See notes for issue on `ifft` zero padding.
  862. axes : sequence of ints, optional
  863. Axes over which to compute the FFT. If not given, the last two
  864. axes are used. A repeated index in `axes` means the transform over
  865. that axis is performed multiple times. A one-element sequence means
  866. that a one-dimensional FFT is performed.
  867. norm : {"backward", "ortho", "forward"}, optional
  868. .. versionadded:: 1.10.0
  869. Normalization mode (see `numpy.fft`). Default is "backward".
  870. Indicates which direction of the forward/backward pair of transforms
  871. is scaled and with what normalization factor.
  872. .. versionadded:: 1.20.0
  873. The "backward", "forward" values were added.
  874. Returns
  875. -------
  876. out : complex ndarray
  877. The truncated or zero-padded input, transformed along the axes
  878. indicated by `axes`, or the last two axes if `axes` is not given.
  879. Raises
  880. ------
  881. ValueError
  882. If `s` and `axes` have different length, or `axes` not given and
  883. ``len(s) != 2``.
  884. IndexError
  885. If an element of `axes` is larger than than the number of axes of `a`.
  886. See Also
  887. --------
  888. numpy.fft : Overall view of discrete Fourier transforms, with definitions
  889. and conventions used.
  890. fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse.
  891. ifftn : The inverse of the *n*-dimensional FFT.
  892. fft : The one-dimensional FFT.
  893. ifft : The one-dimensional inverse FFT.
  894. Notes
  895. -----
  896. `ifft2` is just `ifftn` with a different default for `axes`.
  897. See `ifftn` for details and a plotting example, and `numpy.fft` for
  898. definition and conventions used.
  899. Zero-padding, analogously with `ifft`, is performed by appending zeros to
  900. the input along the specified dimension. Although this is the common
  901. approach, it might lead to surprising results. If another form of zero
  902. padding is desired, it must be performed before `ifft2` is called.
  903. Examples
  904. --------
  905. >>> a = 4 * np.eye(4)
  906. >>> np.fft.ifft2(a)
  907. array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
  908. [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
  909. [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
  910. [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
  911. """
  912. return _raw_fftnd(a, s, axes, ifft, norm)
  913. @array_function_dispatch(_fftn_dispatcher)
  914. def rfftn(a, s=None, axes=None, norm=None):
  915. """
  916. Compute the N-dimensional discrete Fourier Transform for real input.
  917. This function computes the N-dimensional discrete Fourier Transform over
  918. any number of axes in an M-dimensional real array by means of the Fast
  919. Fourier Transform (FFT). By default, all axes are transformed, with the
  920. real transform performed over the last axis, while the remaining
  921. transforms are complex.
  922. Parameters
  923. ----------
  924. a : array_like
  925. Input array, taken to be real.
  926. s : sequence of ints, optional
  927. Shape (length along each transformed axis) to use from the input.
  928. (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
  929. The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
  930. for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
  931. Along any axis, if the given shape is smaller than that of the input,
  932. the input is cropped. If it is larger, the input is padded with zeros.
  933. if `s` is not given, the shape of the input along the axes specified
  934. by `axes` is used.
  935. axes : sequence of ints, optional
  936. Axes over which to compute the FFT. If not given, the last ``len(s)``
  937. axes are used, or all axes if `s` is also not specified.
  938. norm : {"backward", "ortho", "forward"}, optional
  939. .. versionadded:: 1.10.0
  940. Normalization mode (see `numpy.fft`). Default is "backward".
  941. Indicates which direction of the forward/backward pair of transforms
  942. is scaled and with what normalization factor.
  943. .. versionadded:: 1.20.0
  944. The "backward", "forward" values were added.
  945. Returns
  946. -------
  947. out : complex ndarray
  948. The truncated or zero-padded input, transformed along the axes
  949. indicated by `axes`, or by a combination of `s` and `a`,
  950. as explained in the parameters section above.
  951. The length of the last axis transformed will be ``s[-1]//2+1``,
  952. while the remaining transformed axes will have lengths according to
  953. `s`, or unchanged from the input.
  954. Raises
  955. ------
  956. ValueError
  957. If `s` and `axes` have different length.
  958. IndexError
  959. If an element of `axes` is larger than than the number of axes of `a`.
  960. See Also
  961. --------
  962. irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT
  963. of real input.
  964. fft : The one-dimensional FFT, with definitions and conventions used.
  965. rfft : The one-dimensional FFT of real input.
  966. fftn : The n-dimensional FFT.
  967. rfft2 : The two-dimensional FFT of real input.
  968. Notes
  969. -----
  970. The transform for real input is performed over the last transformation
  971. axis, as by `rfft`, then the transform over the remaining axes is
  972. performed as by `fftn`. The order of the output is as for `rfft` for the
  973. final transformation axis, and as for `fftn` for the remaining
  974. transformation axes.
  975. See `fft` for details, definitions and conventions used.
  976. Examples
  977. --------
  978. >>> a = np.ones((2, 2, 2))
  979. >>> np.fft.rfftn(a)
  980. array([[[8.+0.j, 0.+0.j], # may vary
  981. [0.+0.j, 0.+0.j]],
  982. [[0.+0.j, 0.+0.j],
  983. [0.+0.j, 0.+0.j]]])
  984. >>> np.fft.rfftn(a, axes=(2, 0))
  985. array([[[4.+0.j, 0.+0.j], # may vary
  986. [4.+0.j, 0.+0.j]],
  987. [[0.+0.j, 0.+0.j],
  988. [0.+0.j, 0.+0.j]]])
  989. """
  990. a = asarray(a)
  991. s, axes = _cook_nd_args(a, s, axes)
  992. a = rfft(a, s[-1], axes[-1], norm)
  993. for ii in range(len(axes)-1):
  994. a = fft(a, s[ii], axes[ii], norm)
  995. return a
  996. @array_function_dispatch(_fftn_dispatcher)
  997. def rfft2(a, s=None, axes=(-2, -1), norm=None):
  998. """
  999. Compute the 2-dimensional FFT of a real array.
  1000. Parameters
  1001. ----------
  1002. a : array
  1003. Input array, taken to be real.
  1004. s : sequence of ints, optional
  1005. Shape of the FFT.
  1006. axes : sequence of ints, optional
  1007. Axes over which to compute the FFT.
  1008. norm : {"backward", "ortho", "forward"}, optional
  1009. .. versionadded:: 1.10.0
  1010. Normalization mode (see `numpy.fft`). Default is "backward".
  1011. Indicates which direction of the forward/backward pair of transforms
  1012. is scaled and with what normalization factor.
  1013. .. versionadded:: 1.20.0
  1014. The "backward", "forward" values were added.
  1015. Returns
  1016. -------
  1017. out : ndarray
  1018. The result of the real 2-D FFT.
  1019. See Also
  1020. --------
  1021. rfftn : Compute the N-dimensional discrete Fourier Transform for real
  1022. input.
  1023. Notes
  1024. -----
  1025. This is really just `rfftn` with different default behavior.
  1026. For more details see `rfftn`.
  1027. """
  1028. return rfftn(a, s, axes, norm)
  1029. @array_function_dispatch(_fftn_dispatcher)
  1030. def irfftn(a, s=None, axes=None, norm=None):
  1031. """
  1032. Computes the inverse of `rfftn`.
  1033. This function computes the inverse of the N-dimensional discrete
  1034. Fourier Transform for real input over any number of axes in an
  1035. M-dimensional array by means of the Fast Fourier Transform (FFT). In
  1036. other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical
  1037. accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
  1038. and for the same reason.)
  1039. The input should be ordered in the same way as is returned by `rfftn`,
  1040. i.e. as for `irfft` for the final transformation axis, and as for `ifftn`
  1041. along all the other axes.
  1042. Parameters
  1043. ----------
  1044. a : array_like
  1045. Input array.
  1046. s : sequence of ints, optional
  1047. Shape (length of each transformed axis) of the output
  1048. (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
  1049. number of input points used along this axis, except for the last axis,
  1050. where ``s[-1]//2+1`` points of the input are used.
  1051. Along any axis, if the shape indicated by `s` is smaller than that of
  1052. the input, the input is cropped. If it is larger, the input is padded
  1053. with zeros. If `s` is not given, the shape of the input along the axes
  1054. specified by axes is used. Except for the last axis which is taken to
  1055. be ``2*(m-1)`` where ``m`` is the length of the input along that axis.
  1056. axes : sequence of ints, optional
  1057. Axes over which to compute the inverse FFT. If not given, the last
  1058. `len(s)` axes are used, or all axes if `s` is also not specified.
  1059. Repeated indices in `axes` means that the inverse transform over that
  1060. axis is performed multiple times.
  1061. norm : {"backward", "ortho", "forward"}, optional
  1062. .. versionadded:: 1.10.0
  1063. Normalization mode (see `numpy.fft`). Default is "backward".
  1064. Indicates which direction of the forward/backward pair of transforms
  1065. is scaled and with what normalization factor.
  1066. .. versionadded:: 1.20.0
  1067. The "backward", "forward" values were added.
  1068. Returns
  1069. -------
  1070. out : ndarray
  1071. The truncated or zero-padded input, transformed along the axes
  1072. indicated by `axes`, or by a combination of `s` or `a`,
  1073. as explained in the parameters section above.
  1074. The length of each transformed axis is as given by the corresponding
  1075. element of `s`, or the length of the input in every axis except for the
  1076. last one if `s` is not given. In the final transformed axis the length
  1077. of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
  1078. length of the final transformed axis of the input. To get an odd
  1079. number of output points in the final axis, `s` must be specified.
  1080. Raises
  1081. ------
  1082. ValueError
  1083. If `s` and `axes` have different length.
  1084. IndexError
  1085. If an element of `axes` is larger than than the number of axes of `a`.
  1086. See Also
  1087. --------
  1088. rfftn : The forward n-dimensional FFT of real input,
  1089. of which `ifftn` is the inverse.
  1090. fft : The one-dimensional FFT, with definitions and conventions used.
  1091. irfft : The inverse of the one-dimensional FFT of real input.
  1092. irfft2 : The inverse of the two-dimensional FFT of real input.
  1093. Notes
  1094. -----
  1095. See `fft` for definitions and conventions used.
  1096. See `rfft` for definitions and conventions used for real input.
  1097. The correct interpretation of the hermitian input depends on the shape of
  1098. the original data, as given by `s`. This is because each input shape could
  1099. correspond to either an odd or even length signal. By default, `irfftn`
  1100. assumes an even output length which puts the last entry at the Nyquist
  1101. frequency; aliasing with its symmetric counterpart. When performing the
  1102. final complex to real transform, the last value is thus treated as purely
  1103. real. To avoid losing information, the correct shape of the real input
  1104. **must** be given.
  1105. Examples
  1106. --------
  1107. >>> a = np.zeros((3, 2, 2))
  1108. >>> a[0, 0, 0] = 3 * 2 * 2
  1109. >>> np.fft.irfftn(a)
  1110. array([[[1., 1.],
  1111. [1., 1.]],
  1112. [[1., 1.],
  1113. [1., 1.]],
  1114. [[1., 1.],
  1115. [1., 1.]]])
  1116. """
  1117. a = asarray(a)
  1118. s, axes = _cook_nd_args(a, s, axes, invreal=1)
  1119. for ii in range(len(axes)-1):
  1120. a = ifft(a, s[ii], axes[ii], norm)
  1121. a = irfft(a, s[-1], axes[-1], norm)
  1122. return a
  1123. @array_function_dispatch(_fftn_dispatcher)
  1124. def irfft2(a, s=None, axes=(-2, -1), norm=None):
  1125. """
  1126. Computes the inverse of `rfft2`.
  1127. Parameters
  1128. ----------
  1129. a : array_like
  1130. The input array
  1131. s : sequence of ints, optional
  1132. Shape of the real output to the inverse FFT.
  1133. axes : sequence of ints, optional
  1134. The axes over which to compute the inverse fft.
  1135. Default is the last two axes.
  1136. norm : {"backward", "ortho", "forward"}, optional
  1137. .. versionadded:: 1.10.0
  1138. Normalization mode (see `numpy.fft`). Default is "backward".
  1139. Indicates which direction of the forward/backward pair of transforms
  1140. is scaled and with what normalization factor.
  1141. .. versionadded:: 1.20.0
  1142. The "backward", "forward" values were added.
  1143. Returns
  1144. -------
  1145. out : ndarray
  1146. The result of the inverse real 2-D FFT.
  1147. See Also
  1148. --------
  1149. rfft2 : The forward two-dimensional FFT of real input,
  1150. of which `irfft2` is the inverse.
  1151. rfft : The one-dimensional FFT for real input.
  1152. irfft : The inverse of the one-dimensional FFT of real input.
  1153. irfftn : Compute the inverse of the N-dimensional FFT of real input.
  1154. Notes
  1155. -----
  1156. This is really `irfftn` with different defaults.
  1157. For more details see `irfftn`.
  1158. """
  1159. return irfftn(a, s, axes, norm)