0
0
SciPydata~5 mins

Power spectral density in SciPy

Choose your learning style9 modes available
Introduction

Power spectral density shows how the strength of a signal is spread across different frequencies. It helps us understand the main rhythms or patterns in data.

To find the main frequencies in a sound recording.
To analyze heart rate signals to detect irregularities.
To study vibrations in machines for maintenance.
To explore patterns in stock market price changes.
Syntax
SciPy
from scipy.signal import welch
frequencies, power = welch(signal, fs=sample_rate, nperseg=segment_length)

signal is your data array.

fs is the sample rate (how many data points per second).

Examples
Calculate power spectral density with a sample rate of 1000 Hz.
SciPy
frequencies, power = welch(signal, fs=1000)
Calculate PSD with sample rate 500 Hz and segment length 256 points.
SciPy
frequencies, power = welch(signal, fs=500, nperseg=256)
Sample Program

This code creates a signal with two clear frequencies (5 Hz and 20 Hz). It then calculates the power spectral density using the Welch method and prints the first few frequency-power pairs. Finally, it shows a plot of power vs frequency.

SciPy
import numpy as np
from scipy.signal import welch
import matplotlib.pyplot as plt

# Create a signal with two frequencies: 5 Hz and 20 Hz
fs = 100  # sample rate, 100 samples per second
T = 2     # seconds
x = np.linspace(0, T, T*fs, endpoint=False)
signal = 0.5 * np.sin(2 * np.pi * 5 * x) + 0.3 * np.sin(2 * np.pi * 20 * x)

# Calculate power spectral density
frequencies, power = welch(signal, fs=fs, nperseg=128)

# Print first 5 frequency and power values
for f, p in zip(frequencies[:5], power[:5]):
    print(f"Frequency: {f:.2f} Hz, Power: {p:.4f}")

# Plot the power spectral density
plt.semilogy(frequencies, power)
plt.title('Power Spectral Density')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

The power spectral density helps find hidden frequencies in noisy data.

Choosing nperseg affects frequency resolution and smoothness.

Summary

Power spectral density shows how signal power is spread across frequencies.

Use scipy.signal.welch to calculate it easily.

It helps find important rhythms or cycles in data.