import numpy as np import matplotlib.pyplot as plt from scipy.signal import welch, get_window # Parameters fs = 512 # Sampling frequency [Hz] T = 100 # Total time [sec] noise_power = 1 # To be comparad to lines amplitudes num_gates = 4 # Number of random gates min_gate_duration = 1 # in seconds max_gate_duration = 3 # in seconds # Time vector t = np.arange(0, T, 1/fs) # Sinusoid frequencies near f0 frequencies = [38, 40, 42] # Freq in Hz of closely spaced lines (just for test) amplitudes = [10.0, 10, 8] # Different amplitudes (for variety...) # Signal = sum of sinusoids + white noise sinusoid = sum( amp * np.sin(2 * np.pi * freq * t) for amp, freq in zip(amplitudes, frequencies) ) signal = sinusoid + np.random.normal(scale=np.sqrt(noise_power), size=t.shape) # ----- Random Gating ----- mask = np.ones_like(t) smooth_mask = np.ones_like(t) for _ in range(num_gates): # Random start time and duration gate_start = np.random.uniform(0, T - max_gate_duration) gate_duration = np.random.uniform(min_gate_duration, max_gate_duration) i_start = int(gate_start * fs) i_end = int((gate_start + gate_duration) * fs) # Hard cut (zero out) mask[i_start:i_end] = 0 # Tapered gate using a Tukey window length = i_end - i_start if length > 10: talpha = .5 taper = get_window(('tukey', talpha), length) smooth_mask[i_start:i_end] *= (1 - taper) # Smooth dip instead of hard cut # Apply masks gated_signal = signal * mask windowed_signal = signal * smooth_mask # Compute Welch PSDs fftlength = 10 nperseg = int(fftlength*fs) noverlap = nperseg//2 f, Pxx_original = welch(signal, fs, nperseg=nperseg, noverlap=noverlap) _, Pxx_gated = welch(gated_signal, fs, nperseg=nperseg, noverlap=noverlap) _, Pxx_windowed = welch(windowed_signal, fs, nperseg=nperseg, noverlap=noverlap) # Plot fig, ax = plt.subplots(figsize=(7, 4)) ax.semilogy(f, Pxx_original**.5, alpha=.5,label='Original Signal') ax.semilogy(f, Pxx_gated**.5,alpha=.5,label='Hard-cut Gated Signal') ax.semilogy(f, Pxx_windowed**.5,alpha=.5, label=f'Tapered Signal\n(Tukey, alpha = {talpha})') for freq in frequencies: plt.axvline(freq, color='k', linestyle='--', alpha=0.3) ax.set(xlim=(25, 53),ylim=(1e-2,1e2),xlabel='Frequency [Hz]',ylabel='Amplitude Spectral Density', title='Spectral Artefacts of Gating and Windowing') ax.legend(loc=2) ax.grid(True) fig.show() fig.savefig("arefats.png")