# -*- coding: utf-8 -*- 
#Nicolas Enfon - LSIS DYNI - NortekMED
from pylab import *
from time import *
from scipy.io.wavfile import *
from dwt_1 import *
from vocal_detector_1 import *
import os, glob

soundfile = '/NAS3/SABIOD/SITE/NORTEKMED/SAMPLE_SOUNDS/HUMPBACK/humpback2_48khz_80mbytes.wav'
soundfile = '/NAS3/SABIOD/SITE/NORTEKMED/SAMPLE_SOUNDS/BOTTLENOSE/04._Bottlenose_dolphin.wav'
logfile = '/NAS3/SABIOD/METHODES/NICOLAS/NORTEK/LOGS/detector.log'

def test_detection(soundfile, iterations=3, forget=True):
    '''Detector made for testing, debugging and time benchmarking
	
	@soundfile: path to a soundfile
	@iterations: number of times we repeat the detection (for time benchmarking)
	@forget: store some information to a log file

	returns: the decision of the detection'''

    t0 = time()
    time_memory = []

    for i in xrange(iterations):
	#compute the scalogram, detection, decision...
	t = time()
        freq, signal = read(soundfile)
        length = len(signal) / float(freq)
	pattern = randint(0,100,(50,1000))
        scalo, detec = detector(soundfile, pattern, detector_type='d2_energy', smooth=100)
        booled = booleanized(scalo, detec)
        dec = decision(booled)
	time_memory.append(time() - t)

    #for time benchmarking: mean time and variance
    time_avg = array(time_memory).mean()
    time_var = array(time_memory).var()

    if forget != True:
        file = open(forget, 'a')# a for append
	lines = [asctime() + '\nRunning a test detector a redirecting some information to a log file']
        lines.append('\n\nParameters: \nsoundfile: '+soundfile)
	lines.append('\n\nDone in '+str(time() - t0)+' seconds (can be wrong if run on utln servers)')
        file.writelines(lines)
        file.close()

    print
    print 'length of the soundfile:', length, 'seconds'
    print 'global time taken:', time() - t0
    print 'global time / iteration:', (time() - t0) / float(iterations)
    print 'average time taken:', time_avg
    print 'variance of the time:', time_var
    print
    print 'ratio soundfile length / time taken for 1 iteration:', length / time_avg
    print

    return time() - t0, time_avg, time_var



if __name__ == '__main__':
    print asctime()
    tic = time()
    test_detection(soundfile)
    print 'Done in ',time() - tic, 'seconds (the count can be wrong if on utln servers)'
