_pocketfft.py 61 KB

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