Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plotting cross-spectral density in Python using Matplotlib
Cross-spectral density analysis in Python provides an effective way to understand frequency characteristics and relationships between signals. This article explores how to plot cross-spectral density using Python and Matplotlib to visualize frequency spectra and reveal signal correlations.
We'll demonstrate generating signals, computing their cross-spectral density, and creating insightful visualizations using a systematic approach.
What is Cross-Spectral Density?
Cross-spectral density is a mathematical metric that examines frequency characteristics and relationships between two signals. It reveals how the power of one signal at different frequencies correlates with another signal's power at those same frequencies.
By computing cross-spectral density, you can identify shared or correlated frequency components between signals, assessing their mutual influence or dependence. This technique is crucial in signal processing, communication systems, and vibration analysis.
Understanding the Process
The cross-spectral density calculation involves several key steps ?
Signal Generation: Create or load two signals for analysis
FFT Computation: Apply Fast Fourier Transform to both signals
Cross-Correlation: Calculate frequency domain correlation
Visualization: Plot results using logarithmic scale for clarity
Plotting Cross-Spectral Density
Here's a complete example showing how to compute and plot cross-spectral density between a sine wave and white noise ?
import numpy as np
import matplotlib.pyplot as plt
# Set random seed for reproducibility
np.random.seed(0)
# Define signal parameters
N = 1000 # Number of samples
dt = 0.01 # Time step
t = np.arange(0, N*dt, dt) # Time vector
# Generate Signal 1: Sine wave
f1 = 5 # Frequency (Hz)
A1 = 1 # Amplitude
x1 = A1 * np.sin(2*np.pi*f1*t)
# Generate Signal 2: White noise
mean = 0
std_dev = 1
x2 = np.random.normal(mean, std_dev, N)
# Compute cross-spectral density
frequencies, Cxy = plt.csd(x1, x2, NFFT=1024, Fs=1/dt)
# Plot the cross-spectral density
plt.figure(figsize=(10, 6))
plt.semilogy(frequencies, np.abs(Cxy), 'r-', linewidth=1.5)
plt.xlabel('Frequency [Hz]')
plt.ylabel('Cross-Spectral Density [Magnitude]')
plt.title('Cross-Spectral Density: Sine Wave vs White Noise')
plt.grid(True, alpha=0.3)
plt.xlim(0, 50) # Focus on lower frequencies
plt.show()
The output displays the cross-spectral density magnitude across frequencies. Since we're comparing a pure sine wave with random noise, the cross-spectral density should be relatively low, indicating minimal correlation between the signals.
Key Parameters
| Parameter | Description | Typical Values |
|---|---|---|
NFFT |
FFT block size | 256, 512, 1024 |
Fs |
Sampling frequency | 1/dt |
overlap |
Block overlap ratio | 0.5 (50%) |
Analyzing Correlated Signals
To see meaningful cross-spectral density, let's analyze two related signals ?
import numpy as np
import matplotlib.pyplot as plt
# Signal parameters
np.random.seed(42)
N = 2000
dt = 0.01
t = np.arange(0, N*dt, dt)
# Create two related signals
f1, f2 = 10, 15 # Frequencies (Hz)
signal_base = np.sin(2*np.pi*f1*t) + 0.5*np.sin(2*np.pi*f2*t)
# Signal 1: Original signal with noise
x1 = signal_base + 0.2*np.random.normal(0, 1, N)
# Signal 2: Delayed and modified version
delay_samples = 10
x2 = np.zeros_like(signal_base)
x2[delay_samples:] = 0.8 * signal_base[:-delay_samples]
x2 += 0.3*np.random.normal(0, 1, N)
# Compute and plot cross-spectral density
frequencies, Cxy = plt.csd(x1, x2, NFFT=512, Fs=1/dt)
plt.figure(figsize=(12, 5))
# Plot both signals
plt.subplot(1, 2, 1)
plt.plot(t[:200], x1[:200], 'b-', label='Signal 1', alpha=0.7)
plt.plot(t[:200], x2[:200], 'r-', label='Signal 2', alpha=0.7)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.title('Input Signals')
plt.legend()
plt.grid(True, alpha=0.3)
# Plot cross-spectral density
plt.subplot(1, 2, 2)
plt.semilogy(frequencies, np.abs(Cxy), 'g-', linewidth=2)
plt.xlabel('Frequency [Hz]')
plt.ylabel('Cross-Spectral Density')
plt.title('Cross-Spectral Density')
plt.grid(True, alpha=0.3)
plt.xlim(0, 30)
plt.tight_layout()
plt.show()
This example shows higher cross-spectral density at the frequencies where both signals share common components (10 Hz and 15 Hz), demonstrating the correlation between the signals.
Practical Applications
Cross-spectral density analysis is valuable for ?
System Identification: Analyzing input-output relationships
Noise Analysis: Identifying correlated noise sources
Vibration Studies: Finding resonance frequencies
Communication Systems: Signal integrity assessment
Conclusion
Cross-spectral density plotting in Python using Matplotlib provides powerful insights into signal relationships and frequency characteristics. The plt.csd() function makes it straightforward to analyze correlations between signals across different frequencies, essential for signal processing and system analysis applications.
