1"""

2 Discrete Fourier Transforms

3

4 Routines in this module:

5

6 fft(a, n=None, axis=-1, norm="backward")

7 ifft(a, n=None, axis=-1, norm="backward")

8 rfft(a, n=None, axis=-1, norm="backward")

9 irfft(a, n=None, axis=-1, norm="backward")

10 hfft(a, n=None, axis=-1, norm="backward")

11 ihfft(a, n=None, axis=-1, norm="backward")

12 fftn(a, s=None, axes=None, norm="backward")

13 ifftn(a, s=None, axes=None, norm="backward")

14 rfftn(a, s=None, axes=None, norm="backward")

15 irfftn(a, s=None, axes=None, norm="backward")

16 fft2(a, s=None, axes=(-2,-1), norm="backward")

17 ifft2(a, s=None, axes=(-2, -1), norm="backward")

18 rfft2(a, s=None, axes=(-2,-1), norm="backward")

19 irfft2(a, s=None, axes=(-2, -1), norm="backward")

20

21 i = inverse transform

22 r = transform of purely real data

23 h = Hermite transform

24 n = n-dimensional transform

25 2 = 2-dimensional transform

26(Note: 2D routines are just nD routines with different default

27 behavior.)

28

29"""

30__all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn',

31 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn']

32

33 import functools

34

35 from numpy.core import asarray, zeros, swapaxes, conjugate, take, sqrt

36 from . import _pocketfft_internal as pfi

37 from numpy.core.multiarray import normalize_axis_index

38 from numpy.core import overrides

39

40

41 array_function_dispatch = functools.partial(

42 overrides.array_function_dispatch, module='numpy.fft')

43

44

45# `inv_norm` is a float by which the result of the transform needs to be

46# divided. This replaces the original, more intuitive 'fct` parameter to avoid

47# divisions by zero (or alternatively additional checks) in the case of

48# zero-length axes during its computation.

49 def _raw_fft(a, n, axis, is_real, is_forward, inv_norm):

50 axis = normalize_axis_index(axis, a.ndim)

51 if n is None:

52 n = a.shape[axis]

53

54 fct = 1/inv_norm

55

56 if a.shape[axis] != n:

57 s = list(a.shape)

58 index = [slice(None)]*len(s)

59 if s[axis] > n:

60 index[axis] = slice(0, n)

61 a = a[tuple(index)]

62 else:

63 index[axis] = slice(0, s[axis])

64 s[axis] = n

65 z = zeros(s, a.dtype.char)

66 z[tuple(index)] = a

67 a = z

68

69 if axis == a.ndim-1:

70 r = pfi.execute(a, is_real, is_forward, fct)

71 else:

72 a = swapaxes(a, axis, -1)

73 r = pfi.execute(a, is_real, is_forward, fct)

74 r = swapaxes(r, axis, -1)

75 return r

76

77

78 def _get_forward_norm(n, norm):

79 if n < 1:

80 raise ValueError(f"Invalid number of FFT data points ({n}) specified.")

81

82 if norm is None or norm == "backward":

83 return 1

84 elif norm == "ortho":

85 return sqrt(n)

86 elif norm == "forward":

87 return n

88 raise ValueError(f'Invalid norm value {norm}; should be "backward",'

89 '"ortho" or "forward".')

90

91

92 def _get_backward_norm(n, norm):

93 if n < 1:

94 raise ValueError(f"Invalid number of FFT data points ({n}) specified.")

95

96 if norm is None or norm == "backward":

97 return n

98 elif norm == "ortho":

99 return sqrt(n)

100 elif norm == "forward":

101 return 1

102 raise ValueError(f'Invalid norm value {norm}; should be "backward", '

103 '"ortho" or "forward".')

104

105

106_SWAP_DIRECTION_MAP = {"backward": "forward", None: "forward",

107 "ortho": "ortho", "forward": "backward"}

108

109

110 def _swap_direction(norm):

111 try:

112 return _SWAP_DIRECTION_MAP[norm]

113 except KeyError:

114 raise ValueError(f'Invalid norm value {norm}; should be "backward", '

115 '"ortho" or "forward".') from None

116

117

118 def _fft_dispatcher(a, n=None, axis=None, norm=None):

119 return (a,)

120

121

122@array_function_dispatch(_fft_dispatcher)

123 def fft(a, n=None, axis=-1, norm=None):

124 """

125 Compute the one-dimensional discrete Fourier Transform.

126

127 This function computes the one-dimensional *n*-point discrete Fourier

128 Transform (DFT) with the efficient Fast Fourier Transform (FFT)

129 algorithm [CT].

130

131 Parameters

132 ----------

133 a : array_like

134 Input array, can be complex.

135 n : int, optional

136 Length of the transformed axis of the output.

137 If `n` is smaller than the length of the input, the input is cropped.

138 If it is larger, the input is padded with zeros. If `n` is not given,

139 the length of the input along the axis specified by `axis` is used.

140 axis : int, optional

141 Axis over which to compute the FFT. If not given, the last axis is

142 used.

143 norm : {"backward", "ortho", "forward"}, optional

144 .. versionadded:: 1.10.0

145

146 Normalization mode (see `numpy.fft`). Default is "backward".

147 Indicates which direction of the forward/backward pair of transforms

148 is scaled and with what normalization factor.

149

150 .. versionadded:: 1.20.0

151

152 The "backward", "forward" values were added.

153

154 Returns

155 -------

156 out : complex ndarray

157 The truncated or zero-padded input, transformed along the axis

158 indicated by `axis`, or the last one if `axis` is not specified.

159

160 Raises

161 ------

162 IndexError

163 If `axis` is not a valid axis of `a`.

164

165 See Also

166 --------

167 numpy.fft : for definition of the DFT and conventions used.

168 ifft : The inverse of `fft`.

169 fft2 : The two-dimensional FFT.

170 fftn : The *n*-dimensional FFT.

171 rfftn : The *n*-dimensional FFT of real input.

172 fftfreq : Frequency bins for given FFT parameters.

173

174 Notes

175 -----

176 FFT (Fast Fourier Transform) refers to a way the discrete Fourier

177 Transform (DFT) can be calculated efficiently, by using symmetries in the

178 calculated terms. The symmetry is highest when `n` is a power of 2, and

179 the transform is therefore most efficient for these sizes.

180

181 The DFT is defined, with the conventions used in this implementation, in

182 the documentation for the `numpy.fft` module.

183

184 References

185 ----------

186 .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the

187 machine calculation of complex Fourier series," *Math. Comput.*

188 19: 297-301.

189

190 Examples

191 --------

192 >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))

193 array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,

194 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,

195 -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,

196 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])

197

198 In this example, real input has an FFT which is Hermitian, i.e., symmetric

199 in the real part and anti-symmetric in the imaginary part, as described in

200 the `numpy.fft` documentation:

201

202 >>> import matplotlib.pyplot as plt

203 >>> t = np.arange(256)

204 >>> sp = np.fft.fft(np.sin(t))

205 >>> freq = np.fft.fftfreq(t.shape[-1])

206 >>> plt.plot(freq, sp.real, freq, sp.imag)

207 [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]

208 >>> plt.show()

209

210 """

211 a = asarray(a)

212 if n is None:

213 n = a.shape[axis]

214 inv_norm = _get_forward_norm(n, norm)

215 output = _raw_fft(a, n, axis, False, True, inv_norm)

216 return output

217

218

219@array_function_dispatch(_fft_dispatcher)

220 def ifft(a, n=None, axis=-1, norm=None):

221 """

222 Compute the one-dimensional inverse discrete Fourier Transform.

223

224 This function computes the inverse of the one-dimensional *n*-point

225 discrete Fourier transform computed by `fft`. In other words,

226 ``ifft(fft(a)) == a`` to within numerical accuracy.

227 For a general description of the algorithm and definitions,

228 see `numpy.fft`.

229

230 The input should be ordered in the same way as is returned by `fft`,

231 i.e.,

232

233 * ``a[0]`` should contain the zero frequency term,

234 * ``a[1:n//2]`` should contain the positive-frequency terms,

235 * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in

236 increasing order starting from the most negative frequency.

237

238 For an even number of input points, ``A[n//2]`` represents the sum of

239 the values at the positive and negative Nyquist frequencies, as the two

240 are aliased together. See `numpy.fft` for details.

241

242 Parameters

243 ----------

244 a : array_like

245 Input array, can be complex.

246 n : int, optional

247 Length of the transformed axis of the output.

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 See notes about padding issues.

252 axis : int, optional

253 Axis over which to compute the inverse DFT. If not given, the last

254 axis is used.

255 norm : {"backward", "ortho", "forward"}, optional

256 .. versionadded:: 1.10.0

257

258 Normalization mode (see `numpy.fft`). Default is "backward".

259 Indicates which direction of the forward/backward pair of transforms

260 is scaled and with what normalization factor.

261

262 .. versionadded:: 1.20.0

263

264 The "backward", "forward" values were added.

265

266 Returns

267 -------

268 out : complex ndarray

269 The truncated or zero-padded input, transformed along the axis

270 indicated by `axis`, or the last one if `axis` is not specified.

271

272 Raises

273 ------

274 IndexError

275 If `axis` is not a valid axis of `a`.

276

277 See Also

278 --------

279 numpy.fft : An introduction, with definitions and general explanations.

280 fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse

281 ifft2 : The two-dimensional inverse FFT.

282 ifftn : The n-dimensional inverse FFT.

283

284 Notes

285 -----

286 If the input parameter `n` is larger than the size of the input, the input

287 is padded by appending zeros at the end. Even though this is the common

288 approach, it might lead to surprising results. If a different padding is

289 desired, it must be performed before calling `ifft`.

290

291 Examples

292 --------

293 >>> np.fft.ifft([0, 4, 0, 0])

294 array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary

295

296 Create and plot a band-limited signal with random phases:

297

298 >>> import matplotlib.pyplot as plt

299 >>> t = np.arange(400)

300 >>> n = np.zeros((400,), dtype=complex)

301 >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))

302 >>> s = np.fft.ifft(n)

303 >>> plt.plot(t, s.real, label='real')

304 [<matplotlib.lines.Line2D object at ...>]

305 >>> plt.plot(t, s.imag, '--', label='imaginary')

306 [<matplotlib.lines.Line2D object at ...>]

307 >>> plt.legend()

308 <matplotlib.legend.Legend object at ...>

309 >>> plt.show()

310

311 """

312 a = asarray(a)

313 if n is None:

314 n = a.shape[axis]

315 inv_norm = _get_backward_norm(n, norm)

316 output = _raw_fft(a, n, axis, False, False, inv_norm)

317 return output

318

319

320@array_function_dispatch(_fft_dispatcher)

321 def rfft(a, n=None, axis=-1, norm=None):

322 """

323 Compute the one-dimensional discrete Fourier Transform for real input.

324

325 This function computes the one-dimensional *n*-point discrete Fourier

326 Transform (DFT) of a real-valued array by means of an efficient algorithm

327 called the Fast Fourier Transform (FFT).

328

329 Parameters

330 ----------

331 a : array_like

332 Input array

333 n : int, optional

334 Number of points along transformation axis in the input to use.

335 If `n` is smaller than the length of the input, the input is cropped.

336 If it is larger, the input is padded with zeros. If `n` is not given,

337 the length of the input along the axis specified by `axis` is used.

338 axis : int, optional

339 Axis over which to compute the FFT. If not given, the last axis is

340 used.

341 norm : {"backward", "ortho", "forward"}, optional

342 .. versionadded:: 1.10.0

343

344 Normalization mode (see `numpy.fft`). Default is "backward".

345 Indicates which direction of the forward/backward pair of transforms

346 is scaled and with what normalization factor.

347

348 .. versionadded:: 1.20.0

349

350 The "backward", "forward" values were added.

351

352 Returns

353 -------

354 out : complex ndarray

355 The truncated or zero-padded input, transformed along the axis

356 indicated by `axis`, or the last one if `axis` is not specified.

357 If `n` is even, the length of the transformed axis is ``(n/2)+1``.

358 If `n` is odd, the length is ``(n+1)/2``.

359

360 Raises

361 ------

362 IndexError

363 If `axis` is not a valid axis of `a`.

364

365 See Also

366 --------

367 numpy.fft : For definition of the DFT and conventions used.

368 irfft : The inverse of `rfft`.

369 fft : The one-dimensional FFT of general (complex) input.

370 fftn : The *n*-dimensional FFT.

371 rfftn : The *n*-dimensional FFT of real input.

372

373 Notes

374 -----

375 When the DFT is computed for purely real input, the output is

376 Hermitian-symmetric, i.e. the negative frequency terms are just the complex

377 conjugates of the corresponding positive-frequency terms, and the

378 negative-frequency terms are therefore redundant. This function does not

379 compute the negative frequency terms, and the length of the transformed

380 axis of the output is therefore ``n//2 + 1``.

381

382 When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains

383 the zero-frequency term 0*fs, which is real due to Hermitian symmetry.

384

385 If `n` is even, ``A[-1]`` contains the term representing both positive

386 and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely

387 real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains

388 the largest positive frequency (fs/2*(n-1)/n), and is complex in the

389 general case.

390

391 If the input `a` contains an imaginary part, it is silently discarded.

392

393 Examples

394 --------

395 >>> np.fft.fft([0, 1, 0, 0])

396 array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary

397 >>> np.fft.rfft([0, 1, 0, 0])

398 array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary

399

400 Notice how the final element of the `fft` output is the complex conjugate

401 of the second element, for real input. For `rfft`, this symmetry is

402 exploited to compute only the non-negative frequency terms.

403

404 """

405 a = asarray(a)

406 if n is None:

407 n = a.shape[axis]

408 inv_norm = _get_forward_norm(n, norm)

409 output = _raw_fft(a, n, axis, True, True, inv_norm)

410 return output

411

412

413@array_function_dispatch(_fft_dispatcher)

414 def irfft(a, n=None, axis=-1, norm=None):

415 """

416 Computes the inverse of `rfft`.

417

418 This function computes the inverse of the one-dimensional *n*-point

419 discrete Fourier Transform of real input computed by `rfft`.

420 In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical

421 accuracy. (See Notes below for why ``len(a)`` is necessary here.)

422

423 The input is expected to be in the form returned by `rfft`, i.e. the

424 real zero-frequency term followed by the complex positive frequency terms

425 in order of increasing frequency. Since the discrete Fourier Transform of

426 real input is Hermitian-symmetric, the negative frequency terms are taken

427 to be the complex conjugates of the corresponding positive frequency terms.

428

429 Parameters

430 ----------

431 a : array_like

432 The input array.

433 n : int, optional

434 Length of the transformed axis of the output.

435 For `n` output points, ``n//2+1`` input points are necessary. If the

436 input is longer than this, it is cropped. If it is shorter than this,

437 it is padded with zeros. If `n` is not given, it is taken to be

438 ``2*(m-1)`` where ``m`` is the length of the input along the axis

439 specified by `axis`.

440 axis : int, optional

441 Axis over which to compute the inverse FFT. If not given, the last

442 axis is used.

443 norm : {"backward", "ortho", "forward"}, optional

444 .. versionadded:: 1.10.0

445

446 Normalization mode (see `numpy.fft`). Default is "backward".

447 Indicates which direction of the forward/backward pair of transforms

448 is scaled and with what normalization factor.

449

450 .. versionadded:: 1.20.0

451

452 The "backward", "forward" values were added.

453

454 Returns

455 -------

456 out : ndarray

457 The truncated or zero-padded input, transformed along the axis

458 indicated by `axis`, or the last one if `axis` is not specified.

459 The length of the transformed axis is `n`, or, if `n` is not given,

460 ``2*(m-1)`` where ``m`` is the length of the transformed axis of the

461 input. To get an odd number of output points, `n` must be specified.

462

463 Raises

464 ------

465 IndexError

466 If `axis` is not a valid axis of `a`.

467

468 See Also

469 --------

470 numpy.fft : For definition of the DFT and conventions used.

471 rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.

472 fft : The one-dimensional FFT.

473 irfft2 : The inverse of the two-dimensional FFT of real input.

474 irfftn : The inverse of the *n*-dimensional FFT of real input.

475

476 Notes

477 -----

478 Returns the real valued `n`-point inverse discrete Fourier transform

479 of `a`, where `a` contains the non-negative frequency terms of a

480 Hermitian-symmetric sequence. `n` is the length of the result, not the

481 input.

482

483 If you specify an `n` such that `a` must be zero-padded or truncated, the

484 extra/removed values will be added/removed at high frequencies. One can

485 thus resample a series to `m` points via Fourier interpolation by:

486 ``a_resamp = irfft(rfft(a), m)``.

487

488 The correct interpretation of the hermitian input depends on the length of

489 the original data, as given by `n`. This is because each input shape could

490 correspond to either an odd or even length signal. By default, `irfft`

491 assumes an even output length which puts the last entry at the Nyquist

492 frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,

493 the value is thus treated as purely real. To avoid losing information, the

494 correct length of the real input **must** be given.

495

496 Examples

497 --------

498 >>> np.fft.ifft([1, -1j, -1, 1j])

499 array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary

500 >>> np.fft.irfft([1, -1j, -1])

501 array([0., 1., 0., 0.])

502

503 Notice how the last term in the input to the ordinary `ifft` is the

504 complex conjugate of the second term, and the output has zero imaginary

505 part everywhere. When calling `irfft`, the negative frequencies are not

506 specified, and the output array is purely real.

507

508 """

509 a = asarray(a)

510 if n is None:

511 n = (a.shape[axis] - 1) * 2

512 inv_norm = _get_backward_norm(n, norm)

513 output = _raw_fft(a, n, axis, True, False, inv_norm)

514 return output

515

516

517@array_function_dispatch(_fft_dispatcher)

518 def hfft(a, n=None, axis=-1, norm=None):

519 """

520 Compute the FFT of a signal that has Hermitian symmetry, i.e., a real

521 spectrum.

522

523 Parameters

524 ----------

525 a : array_like

526 The input array.

527 n : int, optional

528 Length of the transformed axis of the output. For `n` output

529 points, ``n//2 + 1`` input points are necessary. If the input is

530 longer than this, it is cropped. If it is shorter than this, it is

531 padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``

532 where ``m`` is the length of the input along the axis specified by

533 `axis`.

534 axis : int, optional

535 Axis over which to compute the FFT. If not given, the last

536 axis is used.

537 norm : {"backward", "ortho", "forward"}, optional

538 .. versionadded:: 1.10.0

539

540 Normalization mode (see `numpy.fft`). Default is "backward".

541 Indicates which direction of the forward/backward pair of transforms

542 is scaled and with what normalization factor.

543

544 .. versionadded:: 1.20.0

545

546 The "backward", "forward" values were added.

547

548 Returns

549 -------

550 out : ndarray

551 The truncated or zero-padded input, transformed along the axis

552 indicated by `axis`, or the last one if `axis` is not specified.

553 The length of the transformed axis is `n`, or, if `n` is not given,

554 ``2*m - 2`` where ``m`` is the length of the transformed axis of

555 the input. To get an odd number of output points, `n` must be

556 specified, for instance as ``2*m - 1`` in the typical case,

557

558 Raises

559 ------

560 IndexError

561 If `axis` is not a valid axis of `a`.

562

563 See also

564 --------

565 rfft : Compute the one-dimensional FFT for real input.

566 ihfft : The inverse of `hfft`.

567

568 Notes

569 -----

570 `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the

571 opposite case: here the signal has Hermitian symmetry in the time

572 domain and is real in the frequency domain. So here it's `hfft` for

573 which you must supply the length of the result if it is to be odd.

574

575 * even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,

576 * odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.

577

578 The correct interpretation of the hermitian input depends on the length of

579 the original data, as given by `n`. This is because each input shape could

580 correspond to either an odd or even length signal. By default, `hfft`

581 assumes an even output length which puts the last entry at the Nyquist

582 frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,

583 the value is thus treated as purely real. To avoid losing information, the

584 shape of the full signal **must** be given.

585

586 Examples

587 --------

588 >>> signal = np.array([1, 2, 3, 4, 3, 2])

589 >>> np.fft.fft(signal)

590 array([15.+0.j, -4.+0.j, 0.+0.j, -1.-0.j, 0.+0.j, -4.+0.j]) # may vary

591 >>> np.fft.hfft(signal[:4]) # Input first half of signal

592 array([15., -4., 0., -1., 0., -4.])

593 >>> np.fft.hfft(signal, 6) # Input entire signal and truncate

594 array([15., -4., 0., -1., 0., -4.])

595

596

597 >>> signal = np.array([[1, 1.j], [-1.j, 2]])

598 >>> np.conj(signal.T) - signal # check Hermitian symmetry

599 array([[ 0.-0.j, -0.+0.j], # may vary

600 [ 0.+0.j, 0.-0.j]])

601 >>> freq_spectrum = np.fft.hfft(signal)

602 >>> freq_spectrum

603 array([[ 1., 1.],

604 [ 2., -2.]])

605

606 """

607 a = asarray(a)

608 if n is None:

609 n = (a.shape[axis] - 1) * 2

610 new_norm = _swap_direction(norm)

611 output = irfft(conjugate(a), n, axis, norm=new_norm)

612 return output

613

614

615@array_function_dispatch(_fft_dispatcher)

616 def ihfft(a, n=None, axis=-1, norm=None):

617 """

618 Compute the inverse FFT of a signal that has Hermitian symmetry.

619

620 Parameters

621 ----------

622 a : array_like

623 Input array.

624 n : int, optional

625 Length of the inverse FFT, the number of points along

626 transformation axis in the input to use. If `n` is smaller than

627 the length of the input, the input is cropped. If it is larger,

628 the input is padded with zeros. If `n` is not given, the length of

629 the input along the axis specified by `axis` is used.

630 axis : int, optional

631 Axis over which to compute the inverse FFT. If not given, the last

632 axis is used.

633 norm : {"backward", "ortho", "forward"}, optional

634 .. versionadded:: 1.10.0

635

636 Normalization mode (see `numpy.fft`). Default is "backward".

637 Indicates which direction of the forward/backward pair of transforms

638 is scaled and with what normalization factor.

639

640 .. versionadded:: 1.20.0

641

642 The "backward", "forward" values were added.

643

644 Returns

645 -------

646 out : complex ndarray

647 The truncated or zero-padded input, transformed along the axis

648 indicated by `axis`, or the last one if `axis` is not specified.

649 The length of the transformed axis is ``n//2 + 1``.

650

651 See also

652 --------

653 hfft, irfft

654

655 Notes

656 -----

657 `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the

658 opposite case: here the signal has Hermitian symmetry in the time

659 domain and is real in the frequency domain. So here it's `hfft` for

660 which you must supply the length of the result if it is to be odd:

661

662 * even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,

663 * odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.

664

665 Examples

666 --------

667 >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])

668 >>> np.fft.ifft(spectrum)

669 array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary

670 >>> np.fft.ihfft(spectrum)

671 array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary

672

673 """

674 a = asarray(a)

675 if n is None:

676 n = a.shape[axis]

677 new_norm = _swap_direction(norm)

678 output = conjugate(rfft(a, n, axis, norm=new_norm))

679 return output

680

681

682 def _cook_nd_args(a, s=None, axes=None, invreal=0):

683 if s is None:

684 shapeless = 1

685 if axes is None:

686 s = list(a.shape)

687 else:

688 s = take(a.shape, axes)

689 else:

690 shapeless = 0

691 s = list(s)

692 if axes is None:

693 axes = list(range(-len(s), 0))

694 if len(s) != len(axes):

695 raise ValueError("Shape and axes have different lengths.")

696 if invreal and shapeless:

697 s[-1] = (a.shape[axes[-1]] - 1) * 2

698 return s, axes

699

700

701 def _raw_fftnd(a, s=None, axes=None, function=fft, norm=None):

702 a = asarray(a)

703 s, axes = _cook_nd_args(a, s, axes)

704 itl = list(range(len(axes)))

705 itl.reverse()

706 for ii in itl:

707 a = function(a, n=s[ii], axis=axes[ii], norm=norm)

708 return a

709

710

711 def _fftn_dispatcher(a, s=None, axes=None, norm=None):

712 return (a,)

713

714

715@array_function_dispatch(_fftn_dispatcher)

716 def fftn(a, s=None, axes=None, norm=None):

717 """

718 Compute the N-dimensional discrete Fourier Transform.

719

720 This function computes the *N*-dimensional discrete Fourier Transform over

721 any number of axes in an *M*-dimensional array by means of the Fast Fourier

722 Transform (FFT).

723

724 Parameters

725 ----------

726 a : array_like

727 Input array, can be complex.

728 s : sequence of ints, optional

729 Shape (length of each transformed axis) of the output

730 (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).

731 This corresponds to ``n`` for ``fft(x, n)``.

732 Along any axis, if the given shape is smaller than that of the input,

733 the input is cropped. If it is larger, the input is padded with zeros.

734 if `s` is not given, the shape of the input along the axes specified

735 by `axes` is used.

736 axes : sequence of ints, optional

737 Axes over which to compute the FFT. If not given, the last ``len(s)``

738 axes are used, or all axes if `s` is also not specified.

739 Repeated indices in `axes` means that the transform over that axis is

740 performed multiple times.

741 norm : {"backward", "ortho", "forward"}, optional

742 .. versionadded:: 1.10.0

743

744 Normalization mode (see `numpy.fft`). Default is "backward".

745 Indicates which direction of the forward/backward pair of transforms

746 is scaled and with what normalization factor.

747

748 .. versionadded:: 1.20.0

749

750 The "backward", "forward" values were added.

751

752 Returns

753 -------

754 out : complex ndarray

755 The truncated or zero-padded input, transformed along the axes

756 indicated by `axes`, or by a combination of `s` and `a`,

757 as explained in the parameters section above.

758

759 Raises

760 ------

761 ValueError

762 If `s` and `axes` have different length.

763 IndexError

764 If an element of `axes` is larger than than the number of axes of `a`.

765

766 See Also

767 --------

768 numpy.fft : Overall view of discrete Fourier transforms, with definitions

769 and conventions used.

770 ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT.

771 fft : The one-dimensional FFT, with definitions and conventions used.

772 rfftn : The *n*-dimensional FFT of real input.

773 fft2 : The two-dimensional FFT.

774 fftshift : Shifts zero-frequency terms to centre of array

775

776 Notes

777 -----

778 The output, analogously to `fft`, contains the term for zero frequency in

779 the low-order corner of all axes, the positive frequency terms in the

780 first half of all axes, the term for the Nyquist frequency in the middle

781 of all axes and the negative frequency terms in the second half of all

782 axes, in order of decreasingly negative frequency.

783

784 See `numpy.fft` for details, definitions and conventions used.

785

786 Examples

787 --------

788 >>> a = np.mgrid[:3, :3, :3][0]

789 >>> np.fft.fftn(a, axes=(1, 2))

790 array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary

791 [ 0.+0.j, 0.+0.j, 0.+0.j],

792 [ 0.+0.j, 0.+0.j, 0.+0.j]],

793 [[ 9.+0.j, 0.+0.j, 0.+0.j],

794 [ 0.+0.j, 0.+0.j, 0.+0.j],

795 [ 0.+0.j, 0.+0.j, 0.+0.j]],

796 [[18.+0.j, 0.+0.j, 0.+0.j],

797 [ 0.+0.j, 0.+0.j, 0.+0.j],

798 [ 0.+0.j, 0.+0.j, 0.+0.j]]])

799 >>> np.fft.fftn(a, (2, 2), axes=(0, 1))

800 array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary

801 [ 0.+0.j, 0.+0.j, 0.+0.j]],

802 [[-2.+0.j, -2.+0.j, -2.+0.j],

803 [ 0.+0.j, 0.+0.j, 0.+0.j]]])

804

805 >>> import matplotlib.pyplot as plt

806 >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,

807 ... 2 * np.pi * np.arange(200) / 34)

808 >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)

809 >>> FS = np.fft.fftn(S)

810 >>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2))

811 <matplotlib.image.AxesImage object at 0x...>

812 >>> plt.show()

813

814 """

815 return _raw_fftnd(a, s, axes, fft, norm)

816

817

818@array_function_dispatch(_fftn_dispatcher)

819 def ifftn(a, s=None, axes=None, norm=None):

820 """

821 Compute the N-dimensional inverse discrete Fourier Transform.

822

823 This function computes the inverse of the N-dimensional discrete

824 Fourier Transform over any number of axes in an M-dimensional array by

825 means of the Fast Fourier Transform (FFT). In other words,

826 ``ifftn(fftn(a)) == a`` to within numerical accuracy.

827 For a description of the definitions and conventions used, see `numpy.fft`.

828

829 The input, analogously to `ifft`, should be ordered in the same way as is

830 returned by `fftn`, i.e. it should have the term for zero frequency

831 in all axes in the low-order corner, the positive frequency terms in the

832 first half of all axes, the term for the Nyquist frequency in the middle

833 of all axes and the negative frequency terms in the second half of all

834 axes, in order of decreasingly negative frequency.

835

836 Parameters

837 ----------

838 a : array_like

839 Input array, can be complex.

840 s : sequence of ints, optional

841 Shape (length of each transformed axis) of the output

842 (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).

843 This corresponds to ``n`` for ``ifft(x, n)``.

844 Along any axis, if the given shape is smaller than that of the input,

845 the input is cropped. If it is larger, the input is padded with zeros.

846 if `s` is not given, the shape of the input along the axes specified

847 by `axes` is used. See notes for issue on `ifft` zero padding.

848 axes : sequence of ints, optional

849 Axes over which to compute the IFFT. If not given, the last ``len(s)``

850 axes are used, or all axes if `s` is also not specified.

851 Repeated indices in `axes` means that the inverse transform over that

852 axis is performed multiple times.

853 norm : {"backward", "ortho", "forward"}, optional

854 .. versionadded:: 1.10.0

855

856 Normalization mode (see `numpy.fft`). Default is "backward".

857 Indicates which direction of the forward/backward pair of transforms

858 is scaled and with what normalization factor.

859

860 .. versionadded:: 1.20.0

861

862 The "backward", "forward" values were added.

863

864 Returns

865 -------

866 out : complex ndarray

867 The truncated or zero-padded input, transformed along the axes

868 indicated by `axes`, or by a combination of `s` or `a`,

869 as explained in the parameters section above.

870

871 Raises

872 ------

873 ValueError

874 If `s` and `axes` have different length.

875 IndexError

876 If an element of `axes` is larger than than the number of axes of `a`.

877

878 See Also

879 --------

880 numpy.fft : Overall view of discrete Fourier transforms, with definitions

881 and conventions used.

882 fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.

883 ifft : The one-dimensional inverse FFT.

884 ifft2 : The two-dimensional inverse FFT.

885 ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning

886 of array.

887

888 Notes

889 -----

890 See `numpy.fft` for definitions and conventions used.

891

892 Zero-padding, analogously with `ifft`, is performed by appending zeros to

893 the input along the specified dimension. Although this is the common

894 approach, it might lead to surprising results. If another form of zero

895 padding is desired, it must be performed before `ifftn` is called.

896

897 Examples

898 --------

899 >>> a = np.eye(4)

900 >>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))

901 array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary

902 [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],

903 [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],

904 [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])

905

906

907 Create and plot an image with band-limited frequency content:

908

909 >>> import matplotlib.pyplot as plt

910 >>> n = np.zeros((200,200), dtype=complex)

911 >>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))

912 >>> im = np.fft.ifftn(n).real

913 >>> plt.imshow(im)

914 <matplotlib.image.AxesImage object at 0x...>

915 >>> plt.show()

916

917 """

918 return _raw_fftnd(a, s, axes, ifft, norm)

919

920

921@array_function_dispatch(_fftn_dispatcher)

922 def fft2(a, s=None, axes=(-2, -1), norm=None):

923 """

924 Compute the 2-dimensional discrete Fourier Transform.

925

926 This function computes the *n*-dimensional discrete Fourier Transform

927 over any axes in an *M*-dimensional array by means of the

928 Fast Fourier Transform (FFT). By default, the transform is computed over

929 the last two axes of the input array, i.e., a 2-dimensional FFT.

930

931 Parameters

932 ----------

933 a : array_like

934 Input array, can be complex

935 s : sequence of ints, optional

936 Shape (length of each transformed axis) of the output

937 (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).

938 This corresponds to ``n`` for ``fft(x, n)``.

939 Along each axis, if the given shape is smaller than that of the input,

940 the input is cropped. If it is larger, the input is padded with zeros.

941 if `s` is not given, the shape of the input along the axes specified

942 by `axes` is used.

943 axes : sequence of ints, optional

944 Axes over which to compute the FFT. If not given, the last two

945 axes are used. A repeated index in `axes` means the transform over

946 that axis is performed multiple times. A one-element sequence means

947 that a one-dimensional FFT is performed.

948 norm : {"backward", "ortho", "forward"}, optional

949 .. versionadded:: 1.10.0

950

951 Normalization mode (see `numpy.fft`). Default is "backward".

952 Indicates which direction of the forward/backward pair of transforms

953 is scaled and with what normalization factor.

954

955 .. versionadded:: 1.20.0

956

957 The "backward", "forward" values were added.

958

959 Returns

960 -------

961 out : complex ndarray

962 The truncated or zero-padded input, transformed along the axes

963 indicated by `axes`, or the last two axes if `axes` is not given.

964

965 Raises

966 ------

967 ValueError

968 If `s` and `axes` have different length, or `axes` not given and

969 ``len(s) != 2``.

970 IndexError

971 If an element of `axes` is larger than than the number of axes of `a`.

972

973 See Also

974 --------

975 numpy.fft : Overall view of discrete Fourier transforms, with definitions

976 and conventions used.

977 ifft2 : The inverse two-dimensional FFT.

978 fft : The one-dimensional FFT.

979 fftn : The *n*-dimensional FFT.

980 fftshift : Shifts zero-frequency terms to the center of the array.

981 For two-dimensional input, swaps first and third quadrants, and second

982 and fourth quadrants.

983

984 Notes

985 -----

986 `fft2` is just `fftn` with a different default for `axes`.

987

988 The output, analogously to `fft`, contains the term for zero frequency in

989 the low-order corner of the transformed axes, the positive frequency terms

990 in the first half of these axes, the term for the Nyquist frequency in the

991 middle of the axes and the negative frequency terms in the second half of

992 the axes, in order of decreasingly negative frequency.

993

994 See `fftn` for details and a plotting example, and `numpy.fft` for

995 definitions and conventions used.

996

997

998 Examples

999 --------

1000 >>> a = np.mgrid[:5, :5][0]

1001 >>> np.fft.fft2(a)

1002 array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary

1003 0. +0.j , 0. +0.j ],

1004 [-12.5+17.20477401j, 0. +0.j , 0. +0.j ,

1005 0. +0.j , 0. +0.j ],

1006 [-12.5 +4.0614962j , 0. +0.j , 0. +0.j ,

1007 0. +0.j , 0. +0.j ],

1008 [-12.5 -4.0614962j , 0. +0.j , 0. +0.j ,

1009 0. +0.j , 0. +0.j ],

1010 [-12.5-17.20477401j, 0. +0.j , 0. +0.j ,

1011 0. +0.j , 0. +0.j ]])

1012

1013 """

1014 return _raw_fftnd(a, s, axes, fft, norm)

1015

1016

1017@array_function_dispatch(_fftn_dispatcher)

1018 def ifft2(a, s=None, axes=(-2, -1), norm=None):

1019 """

1020 Compute the 2-dimensional inverse discrete Fourier Transform.

1021

1022 This function computes the inverse of the 2-dimensional discrete Fourier

1023 Transform over any number of axes in an M-dimensional array by means of

1024 the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a``

1025 to within numerical accuracy. By default, the inverse transform is

1026 computed over the last two axes of the input array.

1027

1028 The input, analogously to `ifft`, should be ordered in the same way as is

1029 returned by `fft2`, i.e. it should have the term for zero frequency

1030 in the low-order corner of the two axes, the positive frequency terms in

1031 the first half of these axes, the term for the Nyquist frequency in the

1032 middle of the axes and the negative frequency terms in the second half of

1033 both axes, in order of decreasingly negative frequency.

1034

1035 Parameters

1036 ----------

1037 a : array_like

1038 Input array, can be complex.

1039 s : sequence of ints, optional

1040 Shape (length of each axis) of the output (``s[0]`` refers to axis 0,

1041 ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.

1042 Along each axis, if the given shape is smaller than that of the input,

1043 the input is cropped. If it is larger, the input is padded with zeros.

1044 if `s` is not given, the shape of the input along the axes specified

1045 by `axes` is used. See notes for issue on `ifft` zero padding.

1046 axes : sequence of ints, optional

1047 Axes over which to compute the FFT. If not given, the last two

1048 axes are used. A repeated index in `axes` means the transform over

1049 that axis is performed multiple times. A one-element sequence means

1050 that a one-dimensional FFT is performed.

1051 norm : {"backward", "ortho", "forward"}, optional

1052 .. versionadded:: 1.10.0

1053

1054 Normalization mode (see `numpy.fft`). Default is "backward".

1055 Indicates which direction of the forward/backward pair of transforms

1056 is scaled and with what normalization factor.

1057

1058 .. versionadded:: 1.20.0

1059

1060 The "backward", "forward" values were added.

1061

1062 Returns

1063 -------

1064 out : complex ndarray

1065 The truncated or zero-padded input, transformed along the axes

1066 indicated by `axes`, or the last two axes if `axes` is not given.

1067

1068 Raises

1069 ------

1070 ValueError

1071 If `s` and `axes` have different length, or `axes` not given and

1072 ``len(s) != 2``.

1073 IndexError

1074 If an element of `axes` is larger than than the number of axes of `a`.

1075

1076 See Also

1077 --------

1078 numpy.fft : Overall view of discrete Fourier transforms, with definitions

1079 and conventions used.

1080 fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse.

1081 ifftn : The inverse of the *n*-dimensional FFT.

1082 fft : The one-dimensional FFT.

1083 ifft : The one-dimensional inverse FFT.

1084

1085 Notes

1086 -----

1087 `ifft2` is just `ifftn` with a different default for `axes`.

1088

1089 See `ifftn` for details and a plotting example, and `numpy.fft` for

1090 definition and conventions used.

1091

1092 Zero-padding, analogously with `ifft`, is performed by appending zeros to

1093 the input along the specified dimension. Although this is the common

1094 approach, it might lead to surprising results. If another form of zero

1095 padding is desired, it must be performed before `ifft2` is called.

1096

1097 Examples

1098 --------

1099 >>> a = 4 * np.eye(4)

1100 >>> np.fft.ifft2(a)

1101 array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary

1102 [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],

1103 [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],

1104 [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])

1105

1106 """

1107 return _raw_fftnd(a, s, axes, ifft, norm)

1108

1109

1110@array_function_dispatch(_fftn_dispatcher)

1111 def rfftn(a, s=None, axes=None, norm=None):

1112 """

1113 Compute the N-dimensional discrete Fourier Transform for real input.

1114

1115 This function computes the N-dimensional discrete Fourier Transform over

1116 any number of axes in an M-dimensional real array by means of the Fast

1117 Fourier Transform (FFT). By default, all axes are transformed, with the

1118 real transform performed over the last axis, while the remaining

1119 transforms are complex.

1120

1121 Parameters

1122 ----------

1123 a : array_like

1124 Input array, taken to be real.

1125 s : sequence of ints, optional

1126 Shape (length along each transformed axis) to use from the input.

1127 (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).

1128 The final element of `s` corresponds to `n` for ``rfft(x, n)``, while

1129 for the remaining axes, it corresponds to `n` for ``fft(x, n)``.

1130 Along any axis, if the given shape is smaller than that of the input,

1131 the input is cropped. If it is larger, the input is padded with zeros.

1132 if `s` is not given, the shape of the input along the axes specified

1133 by `axes` is used.

1134 axes : sequence of ints, optional

1135 Axes over which to compute the FFT. If not given, the last ``len(s)``

1136 axes are used, or all axes if `s` is also not specified.

1137 norm : {"backward", "ortho", "forward"}, optional

1138 .. versionadded:: 1.10.0

1139

1140 Normalization mode (see `numpy.fft`). Default is "backward".

1141 Indicates which direction of the forward/backward pair of transforms

1142 is scaled and with what normalization factor.

1143

1144 .. versionadded:: 1.20.0

1145

1146 The "backward", "forward" values were added.

1147

1148 Returns

1149 -------

1150 out : complex ndarray

1151 The truncated or zero-padded input, transformed along the axes

1152 indicated by `axes`, or by a combination of `s` and `a`,

1153 as explained in the parameters section above.

1154 The length of the last axis transformed will be ``s[-1]//2+1``,

1155 while the remaining transformed axes will have lengths according to

1156 `s`, or unchanged from the input.

1157

1158 Raises

1159 ------

1160 ValueError

1161 If `s` and `axes` have different length.

1162 IndexError

1163 If an element of `axes` is larger than than the number of axes of `a`.

1164

1165 See Also

1166 --------

1167 irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT

1168 of real input.

1169 fft : The one-dimensional FFT, with definitions and conventions used.

1170 rfft : The one-dimensional FFT of real input.

1171 fftn : The n-dimensional FFT.

1172 rfft2 : The two-dimensional FFT of real input.

1173

1174 Notes

1175 -----

1176 The transform for real input is performed over the last transformation

1177 axis, as by `rfft`, then the transform over the remaining axes is

1178 performed as by `fftn`. The order of the output is as for `rfft` for the

1179 final transformation axis, and as for `fftn` for the remaining

1180 transformation axes.

1181

1182 See `fft` for details, definitions and conventions used.

1183

1184 Examples

1185 --------

1186 >>> a = np.ones((2, 2, 2))

1187 >>> np.fft.rfftn(a)

1188 array([[[8.+0.j, 0.+0.j], # may vary

1189 [0.+0.j, 0.+0.j]],

1190 [[0.+0.j, 0.+0.j],

1191 [0.+0.j, 0.+0.j]]])

1192

1193 >>> np.fft.rfftn(a, axes=(2, 0))

1194 array([[[4.+0.j, 0.+0.j], # may vary

1195 [4.+0.j, 0.+0.j]],

1196 [[0.+0.j, 0.+0.j],

1197 [0.+0.j, 0.+0.j]]])

1198

1199 """

1200 a = asarray(a)

1201 s, axes = _cook_nd_args(a, s, axes)

1202 a = rfft(a, s[-1], axes[-1], norm)

1203 for ii in range(len(axes)-1):

1204 a = fft(a, s[ii], axes[ii], norm)

1205 return a

1206

1207

1208@array_function_dispatch(_fftn_dispatcher)

1209 def rfft2(a, s=None, axes=(-2, -1), norm=None):

1210 """

1211 Compute the 2-dimensional FFT of a real array.

1212

1213 Parameters

1214 ----------

1215 a : array

1216 Input array, taken to be real.

1217 s : sequence of ints, optional

1218 Shape of the FFT.

1219 axes : sequence of ints, optional

1220 Axes over which to compute the FFT.

1221 norm : {"backward", "ortho", "forward"}, optional

1222 .. versionadded:: 1.10.0

1223

1224 Normalization mode (see `numpy.fft`). Default is "backward".

1225 Indicates which direction of the forward/backward pair of transforms

1226 is scaled and with what normalization factor.

1227

1228 .. versionadded:: 1.20.0

1229

1230 The "backward", "forward" values were added.

1231

1232 Returns

1233 -------

1234 out : ndarray

1235 The result of the real 2-D FFT.

1236

1237 See Also

1238 --------

1239 rfftn : Compute the N-dimensional discrete Fourier Transform for real

1240 input.

1241

1242 Notes

1243 -----

1244 This is really just `rfftn` with different default behavior.

1245 For more details see `rfftn`.

1246

1247 Examples

1248 --------

1249 >>> a = np.mgrid[:5, :5][0]

1250 >>> np.fft.rfft2(a)

1251 array([[ 50. +0.j , 0. +0.j , 0. +0.j ],

1252 [-12.5+17.20477401j, 0. +0.j , 0. +0.j ],

1253 [-12.5 +4.0614962j , 0. +0.j , 0. +0.j ],

1254 [-12.5 -4.0614962j , 0. +0.j , 0. +0.j ],

1255 [-12.5-17.20477401j, 0. +0.j , 0. +0.j ]])

1256 """

1257 return rfftn(a, s, axes, norm)

1258

1259

1260@array_function_dispatch(_fftn_dispatcher)

1261 def irfftn(a, s=None, axes=None, norm=None):

1262 """

1263 Computes the inverse of `rfftn`.

1264

1265 This function computes the inverse of the N-dimensional discrete

1266 Fourier Transform for real input over any number of axes in an

1267 M-dimensional array by means of the Fast Fourier Transform (FFT). In

1268 other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical

1269 accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,

1270 and for the same reason.)

1271

1272 The input should be ordered in the same way as is returned by `rfftn`,

1273 i.e. as for `irfft` for the final transformation axis, and as for `ifftn`

1274 along all the other axes.

1275

1276 Parameters

1277 ----------

1278 a : array_like

1279 Input array.

1280 s : sequence of ints, optional

1281 Shape (length of each transformed axis) of the output

1282 (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the

1283 number of input points used along this axis, except for the last axis,

1284 where ``s[-1]//2+1`` points of the input are used.

1285 Along any axis, if the shape indicated by `s` is smaller than that of

1286 the input, the input is cropped. If it is larger, the input is padded

1287 with zeros. If `s` is not given, the shape of the input along the axes

1288 specified by axes is used. Except for the last axis which is taken to

1289 be ``2*(m-1)`` where ``m`` is the length of the input along that axis.

1290 axes : sequence of ints, optional

1291 Axes over which to compute the inverse FFT. If not given, the last

1292 `len(s)` axes are used, or all axes if `s` is also not specified.

1293 Repeated indices in `axes` means that the inverse transform over that

1294 axis is performed multiple times.

1295 norm : {"backward", "ortho", "forward"}, optional

1296 .. versionadded:: 1.10.0

1297

1298 Normalization mode (see `numpy.fft`). Default is "backward".

1299 Indicates which direction of the forward/backward pair of transforms

1300 is scaled and with what normalization factor.

1301

1302 .. versionadded:: 1.20.0

1303

1304 The "backward", "forward" values were added.

1305

1306 Returns

1307 -------

1308 out : ndarray

1309 The truncated or zero-padded input, transformed along the axes

1310 indicated by `axes`, or by a combination of `s` or `a`,

1311 as explained in the parameters section above.

1312 The length of each transformed axis is as given by the corresponding

1313 element of `s`, or the length of the input in every axis except for the

1314 last one if `s` is not given. In the final transformed axis the length

1315 of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the

1316 length of the final transformed axis of the input. To get an odd

1317 number of output points in the final axis, `s` must be specified.

1318

1319 Raises

1320 ------

1321 ValueError

1322 If `s` and `axes` have different length.

1323 IndexError

1324 If an element of `axes` is larger than than the number of axes of `a`.

1325

1326 See Also

1327 --------

1328 rfftn : The forward n-dimensional FFT of real input,

1329 of which `ifftn` is the inverse.

1330 fft : The one-dimensional FFT, with definitions and conventions used.

1331 irfft : The inverse of the one-dimensional FFT of real input.

1332 irfft2 : The inverse of the two-dimensional FFT of real input.

1333

1334 Notes

1335 -----

1336 See `fft` for definitions and conventions used.

1337

1338 See `rfft` for definitions and conventions used for real input.

1339

1340 The correct interpretation of the hermitian input depends on the shape of

1341 the original data, as given by `s`. This is because each input shape could

1342 correspond to either an odd or even length signal. By default, `irfftn`

1343 assumes an even output length which puts the last entry at the Nyquist

1344 frequency; aliasing with its symmetric counterpart. When performing the

1345 final complex to real transform, the last value is thus treated as purely

1346 real. To avoid losing information, the correct shape of the real input

1347 **must** be given.

1348

1349 Examples

1350 --------

1351 >>> a = np.zeros((3, 2, 2))

1352 >>> a[0, 0, 0] = 3 * 2 * 2

1353 >>> np.fft.irfftn(a)

1354 array([[[1., 1.],

1355 [1., 1.]],

1356 [[1., 1.],

1357 [1., 1.]],

1358 [[1., 1.],

1359 [1., 1.]]])

1360

1361 """

1362 a = asarray(a)

1363 s, axes = _cook_nd_args(a, s, axes, invreal=1)

1364 for ii in range(len(axes)-1):

1365 a = ifft(a, s[ii], axes[ii], norm)

1366 a = irfft(a, s[-1], axes[-1], norm)

1367 return a

1368

1369

1370@array_function_dispatch(_fftn_dispatcher)

1371 def irfft2(a, s=None, axes=(-2, -1), norm=None):

1372 """

1373 Computes the inverse of `rfft2`.

1374

1375 Parameters

1376 ----------

1377 a : array_like

1378 The input array

1379 s : sequence of ints, optional

1380 Shape of the real output to the inverse FFT.

1381 axes : sequence of ints, optional

1382 The axes over which to compute the inverse fft.

1383 Default is the last two axes.

1384 norm : {"backward", "ortho", "forward"}, optional

1385 .. versionadded:: 1.10.0

1386

1387 Normalization mode (see `numpy.fft`). Default is "backward".

1388 Indicates which direction of the forward/backward pair of transforms

1389 is scaled and with what normalization factor.

1390

1391 .. versionadded:: 1.20.0

1392

1393 The "backward", "forward" values were added.

1394

1395 Returns

1396 -------

1397 out : ndarray

1398 The result of the inverse real 2-D FFT.

1399

1400 See Also

1401 --------

1402 rfft2 : The forward two-dimensional FFT of real input,

1403 of which `irfft2` is the inverse.

1404 rfft : The one-dimensional FFT for real input.

1405 irfft : The inverse of the one-dimensional FFT of real input.

1406 irfftn : Compute the inverse of the N-dimensional FFT of real input.

1407

1408 Notes

1409 -----

1410 This is really `irfftn` with different defaults.

1411 For more details see `irfftn`.

1412

1413 Examples

1414 --------

1415 >>> a = np.mgrid[:5, :5][0]

1416 >>> A = np.fft.rfft2(a)

1417 >>> np.fft.irfft2(A, s=a.shape)

1418 array([[0., 0., 0., 0., 0.],

1419 [1., 1., 1., 1., 1.],

1420 [2., 2., 2., 2., 2.],

1421 [3., 3., 3., 3., 3.],

1422 [4., 4., 4., 4., 4.]])

1423 """

1424 return irfftn(a, s, axes, norm)