_pocketfft.py 47 KB

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