SciPy - rfftn() Function



SciPy's rfftn() function is an n-dimensional Fast Fourier Transform that can be used on real-valued input data. It returns non-redundant positive frequency terms for the last axis. Its symmetry cuts down computing costs and memory use, which makes it a good fit for datasets with multiple dimensions.

This method is widely utilized in signal processing, image analysis, and scientific computing. It has implications with frequency-domain filtering, convolution, and spectral analysis. rfftn is more efficient on high-dimensional data so it becomes crucial to tasks like 3D image reconstruction, weather modelling, and shrinking volumetric data.

The SciPy rfftn() method combines with irfftn for round-trip transformation between the spatial and frequency domains. Other tools, fftshift and ifftshift, are used in conjunction with rfftn. These re-order frequency parts to make them easier to view or filter out. This helps with jobs like noise cleanup and feature extraction.

Syntax

The syntax for the SciPy rfftn()method is as follows −

.rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, plan=None)
 

Parameters

This method accepts the following parameters −

  • x (array_like) Input array containing the data to be transformed.

  • s(sequence of ints, optional) Shape of the output along each transformed axis. Pads or truncates the input array accordingly.

  • axes (sequence of ints, optional) Axes over which to compute the FFT. Defaults to all axes.

  • norm (str, optional) The normalization mode control over scaling: "backward" (default, no scaling), "ortho" (unitary scaling for energy preservation), and "forward" (scales the output by 1/n, where n is the transform length).

  • overwrite_x (bool, optional) If True, allows the input array x to be overwritten for better performance. Default is False.

  • workers (int, optional) Number of parallel workers to use for computation. Default is None, meaning a single thread is used.

  • plan (object, optional) A precomputed plan for optimized repeated FFT computations (not commonly used).

Return Value

out ndarray − The n-dimensional frequency-domain representation of the input array, containing only the non-redundant positive frequency terms for the final axis.

Example 1

The SciPy rfftn() method Convert a real-valued n-D array to its reduced frequency-domain representation, making use of symmetry for performance reasons.

This below code, illustrates the basic use of rfftn, which converts a 3D real-valued array to the frequency domain. The final result is compact, containing only the necessary frequency components.

import numpy as np
from scipy.fft import rfftn

# Real-valued 3D data
data = np.random.rand(2, 2, 2)

# Compute the n-dimensional FFT
freq_data = rfftn(data)

print("Frequency-Domain Data:\n", freq_data)

When we run above program, it produces following result

Frequency-Domain Data:
 [[[ 4.70203324+0.j  0.55341305+0.j]
  [ 1.31600762+0.j -0.35677488+0.j]]

 [[ 0.22947961+0.j  0.88185044+0.j]
  [ 0.92591531+0.j -0.80153898+0.j]]]

Example 2

If there are non-real input data values, then rfftn() will throw TypeError to guarantee input validity.

This example demonstrates the requirement of using real-valued input for rfftn since non-real data yields TypeError.

import numpy as np
from scipy.fft import rfftn

# Non-real input
data = np.array([1 + 1j, 2 + 2j])

try:
    freq_data = rfftn(data)
except TypeError as e:
    print(f"TypeError: {e}")

Following is an output of the above code

TypeError: x must be a real sequence

Example 3

This code uses rfftn() to convert sound data from the time and spatial domains into the frequency domain. This aids in detecting patterns of sound throughout the room, such as periodic noises or echoes.

The first transformation considers all dimensions (time, rows, and columns), using axes parameter the second only considers time and microphone rows (performs fft on specific dimensions). This allows for focused research to be conducted; for instance, it will be much easier to identify patterns related to sound direction or recurring events.

import scipy.fft
import numpy as np
import matplotlib.pyplot as plt

# 3D array (time, row, columns)
sound_data = np.random.rand(5, 3, 3)

# Full FFT
frequency_analysis = scipy.fft.rfftn(sound_data)

# Partial FFT (time and rows)
partial_frequency_analysis = scipy.fft.rfftn(sound_data, axes=(0, 1))

# Plot the magnitudes of frequency components
fig, ax = plt.subplots(1, 2, figsize=(8, 4))

#Full 3D FFT
ax[0].plot(np.abs(frequency_analysis.flatten()), label='Full FFT (All Dimensions)')
ax[0].set_title("Full 3D FFT")
ax[0].set_xlabel("Frequency Index")
ax[0].set_ylabel("Magnitude")
ax[0].legend(fontsize=8)

#partial FFT 
ax[1].plot(np.abs(partial_frequency_analysis.flatten()), label='Partial FFT (Time, Rows)')
ax[1].set_title("Partial FFT")
ax[1].set_xlabel("Frequency Index")
ax[1].set_ylabel("Magnitude")
ax[1].legend(fontsize=8)

plt.tight_layout()
plt.show()
scipy_discrete_fourier_transform.htm
Advertisements