# -*- coding: utf-8 -*-
#Nicolas Enfon - 02/04/14 - LSIS DYNI
#Plotting clicks labelled as 'good' and 'other' by MobySoundfrom scipy.io.wavfile import read,write
from pylab import plot, show, subplot, specgram, savefig
from matplotlib.image import NonUniformImage
from matplotlib.pyplot import *
from matplotlib.mlab import psd
from scipy.io.wavfile import read,write
from scipy.fftpack import rfft, irfft, fftfreq
from math import floor
from numpy import *
import os
os.chdir('/net/nas-lsis-3/SABIOD/public_data/ITALY_ZIPHIUS_MOBYSOUND/zc06_204a22410-24210.wav_J60_Q20_T8')

#Various parameters
audio_file = 'zc06_204a22410-24210_petit_192kHz.wav'
good_url = 'zc06_204a22410-24210.Good.log'
maybe_url = 'zc06_204a22410-24210.Maybe.log'
other_url = 'zc06_204a22410-24210.Other.log'

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

#Import and scale given labels
def scalelog(log, data, sampling_rate, size=10):
    log = log * sampling_rate
    for i in xrange(len(log)):
        log[i][0] = int( round( log[i][0] ) )
        log[i][1] = int( round( log[i][1] ) )
    log_gate = zeros( len( data ) )
    for i in xrange( len( log ) ):
        deb = int( log[i][0] - size )
        if deb < 0:
            deb = 0
        fin = int( log[i][1] + size )
        if fin >= len(data):#TODO changer le >= en > sur visual4
            fin = len (data) - 1
        if deb > fin:
            print
            print 'Error: deb=',deb,' > fin=',fin,'! at ', i
            print
#this error can simply be due to the fact that the .log covers a longer period than the .wav
        log_gate[ deb : fin ] = 1
    return log_gate

#Making the gates
good = loadtxt(good_url, skiprows=1)
good_insamples = good[:,0:2] * sampling_rate
good_gate = scalelog(good, signal, sampling_rate, size=850)
maybe = loadtxt(maybe_url, skiprows=1)
maybe_insamples = maybe[:,0:2] * sampling_rate
maybe_gate = scalelog(maybe, signal, sampling_rate, size=850)
other = loadtxt(other_url, skiprows=1)
other_insamples = other[:,0:2] * sampling_rate
other_gate = scalelog(other, signal, sampling_rate, size=850)

def plot_spectrum(signal, sampling_rate):
	signal = signal / (2.**15) #the sound pressure values are mapped to integer values that can range from -2^15 to (2^15)-1 (int16)
	length = len(signal)
	FFT = fft.fft(signal)
	nUniquePts = ceil((length+1)/2.)
	FFT = FFT[0:nUniquePts]
	FFT = abs(FFT)
	FFT = FFT / float(length)
	FFT = FFT ** 2
	if length % 2 > 0:
		FFT[1:len(FFT)] = FFT[1:len(FFT)] * 2
	else:
		FFT[1:len(FFT) - 1] = FFT[1:len(FFT) - 1] * 2
	freqArray = arange(0, nUniquePts, 1.0) * (sampling_rate / length)
	plot(freqArray/1000, 10*log10(FFT), color='b')
	xlabel('Frequency (kHz)')
	ylabel('Power (dB)')
	#xlim(0,len(FFT))
	

#Plotting
fig = figure(figsize=(50,50))
ngood, nother = 3, 9
for i in xrange(ngood):
    ax = subplot(ngood, 1, i+1)
	signal_toplot = signal[good_insamples[i][0]:good_insamples[i][1]]
	plot_spectrum(signal_toplot, sampling_rate)
	
    #ax = subplot(ngood, 2, i*2+1)	
	#toplot = signal[good_insamples[i][0]:good_insamples[i][1]]
	#plot(range(len(toplot)), toplot)	
	#xlim(0,len(toplot))
	#ylim(-200,200)
	#xlabel('Time (ms)')
	#ylabel('Signal')
	#ticks = ax.get_xticks() / sampling_rate * 1000 + good[i][0]*1000
	#ticks = ['%.3f' % a for a in ticks  ]
	#ax.set_xticklabels(ticks)
	#title("Good click #"+str(i+1))
	
    #ax = subplot(ngood, 2, i*2+1+1)
    #toplot = signal[other_insamples[i][0]:other_insamples[i][1]]
    #plot(range(len(toplot)), toplot)
    #xlim(0,len(toplot))
    #ylim(-700,700)
    #xlabel('Time (ms)')
    #ylabel('Signal')
    #ticks = ax.get_xticks() / sampling_rate * 1000 + other[i][0]*1000
    #ax.set_xticklabels(ticks)
	#title('Other click #'+str(i+1))
	
savefig('good_ziphius_spectrum.png')
