_pocketfft.py 52 KB

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