"ComplexWarning" error message

I keep getting an error message for “casting complex numbers.” I’m trying to generate a signal and the perform a discrete Fourier transform:

first, define the signal, which consists of sine waves with different frequencies and amplitudes. Gaussian noise has been added to this signal

import numpy as np
from numpy import exp
from numpy import sin, pi, arange, real, imag
import matplotlib.pyplot as plt

sampling_freq = 500

freq = [3, 10, 5 ,15, 35]
amplitude = [5, 15, 10, 5, 7]
phases = pi*np.array([1/7, 1/8, 1, 1/2, -1/4])

time = arange(-1, 1 + 1/sampling_freq, 1/sampling_freq)

sine_waves =
for i,f in enumerate(freq):
sine_waves.append(amplitude[i] * sin(2pif*time + phases[i]))
sine_waves = np.array(sine_waves)

noise = 5 * np.random.randn(sine_waves.shape[1])
signal = np.sum(sine_waves,axis=0) + noise

plt.figure(figsize=(12,3))
plt.plot( signal, linewidth=2)
plt.title(“Sum of sine waves plus white noise”, fontsize=18)
plt.ylabel(‘Intensity’, fontsize=18)
plt.xlabel(‘Time’, fontsize=18)
plt.show()

to create the filter bank, generate n-1 sin waves and plot the first 5

these are generated from the signal

time = np.arange(0, len(signal), 1)/len(signal)

sine_waves =
for i in range(len(signal)):
sine_waves.append(exp(-1j2piitime))
sine_waves = np.array(sine_waves)

f,a = plt.subplots(nrows=5, figsize=(12,8), sharex=True)
for i in range(0,5):
a[i].plot(sine_waves[i,:], linewidth=2)
a[0].set_title(‘Bank of sine waves’, fontsize=18)
a[i].set_xlabel(‘Time’, fontsize=18)
plt.tight_layout()
plt.show()

estimate the fourier coefficients, which are the dot products of each sin wave with the signal

fourier = 2*np.dot(signal, sine_waves)/len(signal) # calculates an array where each element is the dot product (Fourier coefficients) of a sin wave and the signal
print(fourier) # this prints the fourier array

visualuze the fourier coefficients of each sine wave by graphing amplitude against frequency (characteristics of the sine waves)

the frequenceis are not in the right units yet. These are just the index of the sine wave

plt.figure(figsize=(12, 5))
plt.plot(np.abs(fourier[0:int(np.ceil(len(fourier)/2))]), linewidth=2)
plt.xlabel(‘Frequency (index)’, fontsize=18)
plt.ylabel(‘Amplitude’, fontsize=18)
plt.title(‘Power spectrum derived from discrete fourier transform’, fontsize=18)
plt.show()

now change the units on the X-axis to turn them into frequencies

the frequencies and amplitudes of spikes are the same frequencies and amplitudes used to make the sine wave

from numpy.fft import fftfreq

freq = fftfreq(len(signal),1/sampling_freq)

plt.figure(figsize=(12,5))
plt.plot(freq[:80], np.abs(fourier)[0:80], linewidth=2)
plt.xlabel(‘Frequency (Hz)’, fontsize=18)
plt.ylabel(‘Amplitude’, fontsize=18)
plt.title(‘Power spectrum derived from discrete fourier transform’, fontsize=18)
plt.show()