
from numpy.fft import fft
import numpy as np
import math
from matplotlib.pyplot import *
                

T = 1.0
w0 = 2*math.pi/T
def signal(t):
    return 1.0+2.0*np.cos(w0*t)+0.5*np.cos(2*w0*t)\
    +1.0*np.sin(3*w0*t)+0.2*np.cos(10*w0*t)
                

fe = 50.0
te = 1/fe
temps = np.arange(start=0.0,stop=T,step=te)
echantillons = signal(temps)
                

figure(figsize=(8,4))
plot(temps,echantillons,'r.')
xlabel('t')
ylabel('s')
                

N = temps.size
tfd = fft(echantillons)/N
freq = np.zeros(N)
for k in range(N): 
    freq[k] = k*1.0/T
                

spectre = np.absolute(tfd)
figure(figsize=(10,4))
vlines(freq,[0],spectre,'r')
xlabel('f')
ylabel('S')
axis([-1,fe,0,spectre.max()])
grid()
                

def tracerSpectre(fonction,fe):
    t = np.arange(start=0.0,stop=1.0,step=1.0/fe)
    echantillons = t.copy()
    for k in range(t.size):
        echantillons[k] = fonction(t[k])
    N = echantillons.size
    tfd = fft(echantillons)/N
    spectre = np.absolute(tfd)
    freq = np.arange(N)
    figure(figsize=(10,4))
    vlines(freq,[0],spectre,'r')
    xlabel('f')
    ylabel('S')
    axis([-1,fe,0,spectre.max()])
    grid()
    return tfd
                

tracerSpectre(signal,22)
                

tracerSpectre(signal,15)
                

def signal(t):
    if t < 0.5:
        return 1.0
    else:
        return -1.0
tfd = tracerSpectre(signal,100)
                

pmax = 20            
rapport = np.zeros(pmax)
for p in range(pmax):
    rapport[p] = abs(tfd[1])/abs(tfd[2*p+1])/(2*p+1)
            

tfd = tracerSpectre(signal,500)
pmax = 20            
rapport = np.zeros(pmax)
for p in range(pmax):
    rapport[p] = abs(tfd[1])/abs(tfd[2*p+1])/(2*p+1)
            
