# -*- coding: utf-8 -*- 
#Nicolas Enfon - 01/05/14 - LSIS DYNI
import numpy as np
from matplotlib.pyplot import *
from scipy.io.wavfile import read, write
from pylab import norm

#Various parameters
audio_file = 'ANTARES_67528.21_25_10_2012_20.15.17_23.08.23_part1.wav'
dat_url = 'ANTARES_67528.21_25_10_2012_20.15.17_23.08.23_T8_Q20_J60_scalo1_L1.dat'

#Reading of the input audio data
sampling_rate, signal = read(audio_file)

#Reading the .dat
dat_file = np.loadtxt(dat_url, delimiter=',')

#Makes the trend used by the detector
def make_trend(dat_file, startline=0, endline=None, conv_size=35):
    if endline == None:
        endline=len(dat_file)
    trend = dat_file[startline:endline,:].sum(0)
    smoothed_trend = np.convolve(trend, np.ones(conv_size), mode='same')
    return smoothed_trend, smoothed_trend.min(), smoothed_trend.max()
                        
#Simple detector
def detector(smoothed_trend, threshold=1):
    ''' Detects the energy peaks above a threshold, and saves their position '''
    peaks = []
    for i in xrange( len( smoothed_trend ) ):
        if smoothed_trend[i] > threshold:
            peaks.append(i)
    return peaks
                                    
#Scaled to the data size
def scaled_detector(len_signal, len_dat_file, peaks, size=150):
    ''' Scales the peaks and make 0/1 gates that match the audio data size.
        size is in bins, ie in seconds * sampling_rate(data) '''
    peaks = np.array(peaks)
    peaks = peaks * len_signal / float(len_dat_file)#CAUTION: len_dat_file = len(dat_file[0])
    for i in xrange(len(peaks)):
        peaks[i] = int( round( peaks[i] ) )#caution, numpy array keeps float type
    peaks_gate = np.zeros( len_signal )
    for i in xrange( len( peaks ) ):
        deb = int( peaks[i] - size )
        if deb < 0:
            deb = 0
        fin = int( peaks[i] + size )
        if fin > len_signal:
            fin = len_signal
        peaks_gate[ deb : fin ] = 1
    return peaks_gate

#Computing the trend to detect the clicks
startline, endline = 18, 68
startavoid, endavoid = -6, 88
smoothed_trend, min, max = make_trend(dat_file, startline, endline, conv_size=51)
smoothed_avoid, min2, max2 = make_trend(dat_file, startavoid, endavoid, conv_size=51)
#Getting the peaks from the trend
threshold = smoothed_trend.mean() + 2
threshold_avoid = smoothed_avoid.mean()
peaks = detector(smoothed_trend, threshold)
peaks_gate = scaled_detector( len(signal), len(dat_file[0]), peaks, size=68 )
peaks_avoid = detector(smoothed_avoid, threshold_avoid)
peaks_gate_avoid = scaled_detector( len(signal), len(dat_file[0]), peaks_avoid, size=68 )
peaks_gate = peaks_gate.astype(int) & ( peaks_gate_avoid.astype(int) ^ np.ones(len(peaks_gate)).astype(int)   )

#Extracting and normalizing the clicks in the signal
index1 = (np.array((0.07975, 0.07995)) * sampling_rate).astype(int)
index2 = (np.array((1.3092,1.3094)) * sampling_rate).astype(int)
index3 = (np.array((1.55345, 1.55375)) * sampling_rate).astype(int)
clicks = [   signal[index1[0]:index1[1]], signal[index2[0]:index2[1]], signal[index3[0]:index3[1]]   ]
for i in xrange(len(clicks)):
	clicks[i] = clicks[i] / float( (clicks[i]**2).sum() )


#convolution signal * click
conv = []
for i in xrange(len(clicks)):
	conv.append( np.convolve(signal,clicks[i],mode='same') )

#PLotting
figure(figsize=(80,30))
subplot(411)
plot(signal)
xlim(0,len(signal))
title('signal')
subplot(412)
plot(conv[0])
xlim(0,len(signal))
title('click 1 - small - '+str(index1))
subplot(413)
plot(conv[1])
xlim(0,len(signal))
title('click 2 - medium - '+str(index2))
subplot(414)
plot(conv[2])
xlim(0,len(signal))
title('click 3 - big - '+str(index3))
#savefig('3_convolved_signals_XXS.png')

