# -*- coding: utf-8 -*-
"""
Created on Mon Oct 27 21:38:45 2014

@author: yvestalbourdel
"""


import numpy
import math
from matplotlib.pyplot import *
import numpy.fft
import scipy.signal

P=500
fe=50000
fc=3100
h = numpy.zeros(2*P+1)
def sinc(u):
    if u==0:
        return 1.0
    else:
        return math.sin(u)/(u)
a=fc/fe
for k in range(2*P+1):
    h[k] = 2*a*sinc(2*math.pi*(k-P)*a)
indices = numpy.arange(2*P+1)
figure(figsize=(8,4))
vlines(indices,[0],h)
grid()
                

def reponseFreq(h):
    N = h.size
    def Hf(f):
        s = 0.0
        for k in range(N):
            s += h[k]*numpy.exp(-1j*2*math.pi*k*f)
        return s
    f = numpy.arange(start=0.0,stop=0.5,step=0.0001)
    hf = Hf(f)
    g = numpy.absolute(hf)
    phi = numpy.unwrap(numpy.angle(hf))
    return [f,g,phi]
                  

(f,g,phi)=reponseFreq(h)
figure(figsize=(6,4))
plot(f*fe,g)
xlabel('f (Hz)')
ylabel('|H|')
axis([0,fc*2,0,2])
grid()
figure(figsize=(6,4))
plot(f*fe,phi*180/math.pi)
xlabel('f (Hz)')
ylabel('phase')
axis([0,fc*2,-20000,0])
grid()

h = h*scipy.signal.get_window("hamming",2*P+1)
(f,g,phi)=reponseFreq(h)
figure(figsize=(6,4))
plot(f*fe,g)
xlabel('f (Hz)')
ylabel('|H|')
axis([0,fc*2,0,2])
grid()
                    

figure(figsize=(6,5))
plot(f*fe,20*numpy.log10(g))
xlabel('f (Hz)')
ylabel('GdB')
xscale('log')
grid()
                    
with open('votre chemin de fichier exporté de LatisPro','r') as fichier:

    fichier.readline()         

    t0 = np.array([])                               
    u0 = np.array([])

    for ligne in fichier:
        chaines = ligne.split()              
        t = float(chaines[0])               
        u = float(chaines[1])               
        t0 = np.append(t, t0)             
        u0 = np.append(u, u0)                

t0 = t0[::-1]                             
u0 = u0[::-1] 

def filtrageNum(P,h):

    u2 = scipy.signal.convolve(u0,h,mode='valid')
    te = t0[1]-t0[0]
    print (1/te)
    t2 = numpy.arange(2*P+1,2*P+1+u2.size)*te
    figure(figsize=(8,4))
    plot(t0,u0,'b+',label='entree')
    plot(t2,u2,'r+',label='sortie')
    xlabel('t (s)')
    ylabel('u (V)')
    axis([0.01,0.08,-3,3])
    legend(loc='upper right')
    grid()
    show()
                     
filtrageNum(P,h)