IMFs
IMFs
return instantaneous_frequency
def instantaneous_amplitude(imfs):
amplitude = []
for imf in imfs:
# Apply Hilbert transform to obtain analytic signal
analytic_signal = hilbert(imf)
# Calculate magnitude of the analytic signal (instantaneous amplitude)
amp = np.abs(analytic_signal)
amplitude.append(amp)
return amplitude
pi=np.pi
max_iter =6
# imf=np.zero(100)
g=2560
t = np.linspace(0, 1, g)
# print(t)
signal=np.zeros(len(t))
# tol = 1
gr=1
# for k in range(len(t)):
# signal[k]=5*np.sin(2*pi**50*t[k])+6*np.sin(2*pi*80*t[k])
# while abs(gr) >0.01:
# for l in range(len(t)):
# dt=random.randint(1,2)
# if dt//2==0:
# signal[l] = np.cos(10*pi*t[l])**1+(-1) ** dt * random.random()**1
# # signal[l]=0
# else:
# signal[l] =np.sin(1*pi*t[l])**1*(-1) ** dt * random.random()**1
#
# gr=np.mean(signal)
# print(gr)
peak_freq = 15
sample_rate = 256
seconds = 10
noise_std = .4
x = emd.simulate.ar_oscillator(peak_freq, sample_rate, seconds,noise_std=noise_std,
random_seed=42, r=0.96)[:, 0]
signal = x*1e-8
d=np.zeros(len(t))
sum=0
for i in range(max_iter):
av = 1
peaks, _ = find_peaks(x)
troughs, _ = find_peaks(-x)
P=x[peaks]
T=x[troughs]
x_p = t[peaks]
x_t= t[troughs]
fp = CubicSpline(x_p, P)
xp_new = np.linspace(0, 1, g)
yp_new = fp(xp_new)
ft = CubicSpline(x_t, T)
xt_new = np.linspace(0, 1, g)
yt_new = ft(xt_new)
m=0.5*(yp_new+yt_new)
d = x-m
av=np.mean(d)
print(av)
if abs(av) > 0.0001:
x=d
else:
imf = d
# plt.subplot(i+1,i+1,1)
col = (np.random.random(), np.random.random(), np.random.random())
# Compute Instantaneous Frequency (IF)
if_signal = instantaneous_frequency(imf, sample_rate)
# plt.figure(figsize=(10, 6))
# plt.plot(t[:-1], if_signal) # Plot instantaneous frequency over time
# plt.xlabel('Time')
# imf_amplitude = instantaneous_amplitude(imf)
analytic_signal = hilbert(imf)
instantaneous_amplitude = np.abs(analytic_signal)
# Compute the frequency spectrum
n = len(x)
frequencies = np.fft.fftfreq(n, d=t[1] - t[0])
amplitude_spectrum = np.abs(np.fft.fft(instantaneous_amplitude))
# Plot the Hilbert amplitude spectrum
plt.plot(frequencies[:n // 2], amplitude_spectrum[:n // 2], c=col,
label=f'imf {i + 1}')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude')
plt.title('Hilbert Amplitude Spectrum')
plt.legend()
axs1[i + 0].set_title(f'IMF{i + 1}', x=1.05, y=0.5)
axs1[i + 0].plot(t[:-1], if_signal, c=col, label=f'imf {i + 1}')
axs2[i + 0].set_title(f'IMF{i + 1}', x=1.05, y=0.5)
axs2[i + 0].hist(imf,bins=100, color=col, label=f'imf {i + 1}')
axs3[i + 0].set_title(f'IMF{i + 1}', x=1.05, y=0.5)
axs3[i + 0].plot(t, instantaneous_amplitude,c=col)
x=m
sum=sum+d
# plt.tight_layout()
# plt.plot(t,signal,label='signal')
# plt.plot(xt_new, sum, label='summed up imfs')
# plt.legend()
col = (np.random.random(), np.random.random(), np.random.random())
axs[max_iter+1].set_title('summed up',x=1.05,y=0.5)
axs[max_iter+1].plot(xt_new, sum,c=col, label='summed up imfs')
plt.show()