# -*- coding: utf-8 -*-
#First try at drawing spectrograms with Python, to check the sounds labelled as 'good', 'maybe' and 'other'
#Nicolas Enfon - 02/04/14 - LSIS DYNI
from 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 math import floor
import numpy
import readfile

#Various parameters
nfft = 64
overlap = 32
sampling_rate = 192000 #this sampling rate can be given by 'rate, data = read(file)' 
audio_file = 'zc06_204a22410-24210_petit_192kHz.wav'
log_file = 'zc06_204a22410-24210.Good.log'
other_file = 'zc06_204a22410-24210.Other.log'
#Reading of the input audio data
rate, data = read(audio_file)
Pxx, freqs, bins, im = specgram( data, NFFT = nfft, Fs = sampling_rate,  noverlap = overlap)
(numSpectra, numBins) = Pxx.shape

#Reading of the labels
labels = readfile.readlog(log_file) 

#Converting the time into bins (and scaling so that everything matches)
for i in xrange(len(labels)):
    #expanding the window
    labels[i][0] -= 0.01
    labels[i][1] += 0.01
for i in xrange(len(labels)):
    #scaling
    labels[i][0] = int( round( labels[i][0] *  len(Pxx[0]) * sampling_rate ) / len(data) )
    labels[i][1] = int( round( labels[i][1] *  len(Pxx[0]) * sampling_rate ) / len(data) )#+1? floor?

#Overwriting
for i in xrange(len(labels)):
    for j in xrange(labels[i][0],labels[i][1]):
	for k in xrange(2):
	    if j < len(Pxx[0]):#in case audio file is truncated, and logs are not
  	        #colours the first k lines
		Pxx[k][j] = float(0.000000001)

#Converting the data to mimic matplotlib's specgram
for i in xrange(len(Pxx)):
    for j in xrange(len(Pxx[0])):
	Pxx[i][j] = 10 * numpy.log10(Pxx[i][j])

         
#Plotting
fig = figure(figsize=(50,10))
axe1 = subplot(2,1,1)
plot(range(len(data)),data)#overview of the input signal
xlabel('Time')
ylabel('Frequency')
title('Acoustic signal')

axe2=fig.add_subplot(2,1,2)
img2 = axe2.imshow(Pxx, interpolation=None, aspect='auto', extent=(0,len(data)/sampling_rate,0,max(data)))
#xticks(range(0,10)) ne modifie pas l'échelle
xlabel('Time')
ylabel('Frequency')
title('Spectrogram: NFFT =' + str(nfft) + ', overlapping =' + str(overlap) )
#ylim(0,33)

savefig('a_supprimer.png')
#show()

print 'max(data): ', max(data) 
print 'nbbins: ', numBins
print 'nbspectra: ', numSpectra
print 'Pxx: '
print Pxx
print'len(Pxx)', len(Pxx)
print 'len(Pxx[0])', len(Pxx[0])
print 'len(data)', len(data)
print 'len(labels)', len(labels)
