_pocketfft.py 61 KB

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