Index: tests/demo/bench/onset/Makefile.am
===================================================================
--- tests/demo/bench/onset/Makefile.am	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/onset/Makefile.am	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,44 @@
+export BASEDIR=../../../..
+export PYTHONPATH=$(BASEDIR)/python
+export LD_LIBRARY_PATH=$(BASEDIR)/src/.libs:$(BASEDIR)/ext/.libs
+
+DETAILSOURCE = \
+	/var/tmp/Onset-Mirex2005/poly_pitched \
+	/var/tmp/Onset-Mirex2005/solo_bars_and_bells \
+	/var/tmp/Onset-Mirex2005/solo_brass \
+	/var/tmp/Onset-Mirex2005/solo_drums \
+	/var/tmp/Onset-Mirex2005/solo_plucked_strings \
+	/var/tmp/Onset-Mirex2005/solo_singing_voice \
+	/var/tmp/Onset-Mirex2005/solo_sustained_strings \
+	/var/tmp/Onset-Mirex2005/solo_winds \
+	/var/tmp/Onset-Mirex2005/complex
+
+SOURCE = /var/tmp/Onset-Mirex2005
+
+TESTSOURCE = \
+	/var/tmp/Onset-Mirex2005/solo_bars_and_bells \
+	/var/tmp/Onset-Mirex2005/solo_winds \
+	/archives/samples/DB/PercussivePhrases/CM18/Samba_Audio
+
+test-aubiocut:            $(patsubst %, %.aubiocut,    $(TESTSOURCE))
+test-aubiodelay:          $(patsubst %, %.aubiodelay,  $(TESTSOURCE))
+test-aubiowindow:         $(patsubst %, %.aubiowindow, $(TESTSOURCE))
+
+final-aubiocut:           $(patsubst %, %.aubiocut,    $(DETAILSOURCE) $(SOURCE))
+final-aubiodelay:         $(patsubst %, %.aubiodelay,  $(SOURCE))
+final-aubiowindow:        $(patsubst %, %.aubiowindow, $(SOURCE))
+
+%.aubiocut: %
+	rm -f `basename $@`
+	./bench-onset $< | tee `basename $@`
+	-diff `basename $@`.ref `basename $@`
+
+%.aubiodelay: %
+	rm -f `basename $@`
+	./bench-delay $< | tee `basename $@`
+	-diff `basename $@`.ref `basename $@`
+
+%.aubiowindow: %
+	rm -f `basename $@`
+	./bench-window $< | tee `basename $@`
+	-diff `basename $@`.ref `basename $@`
Index: tests/demo/bench/onset/bench-delay
===================================================================
--- tests/demo/bench/onset/bench-delay	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/onset/bench-delay	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,62 @@
+#! /usr/bin/python
+
+from aubio.bench.onset import benchonset
+from aubio.task.onset import taskonset
+from aubio.task.params import taskparams
+
+class mybenchonset(benchonset):
+
+	def run_bench(self,modes=['dual'],thresholds=[0.5]):
+		from os.path import dirname,basename
+		self.thresholds = thresholds
+		self.pretty_titles()
+
+		for mode in modes:
+			d = []
+			self.params.onsetmode = mode
+			self.params.localmin = True
+			self.params.delay = 1. 
+			self.params.threshold = thresholds[0]
+			#
+			self.params.localmin = False 
+			self.params.delay = 0. 
+			self.dir_eval_print()
+			self.plotdiffs(d,plottitle="Causal")
+			#
+			self.params.localmin = True
+			self.params.delay = 0. 
+			self.dir_eval_print()
+			self.plotdiffs(d,plottitle="Local min")
+
+			self.params.localmin = False 
+			self.params.delay = 6. 
+			self.dir_eval_print()
+			self.plotdiffs(d,plottitle="Fixed delay")
+
+			#self.plotplotdiffs(d)
+			outplot = "_-_".join(("delay",mode,basename(self.datadir) ))
+			for ext in ("png","svg","ps"):
+				self.plotplotdiffs(d,outplot=outplot,extension=ext)
+
+if __name__ == "__main__":
+	import sys
+	if len(sys.argv) > 1: datapath = sys.argv[1]
+	else: print "ERR: a path is required"; sys.exit(1)
+	modes = ['complex', 'energy', 'phase', 'hfc', 'specdiff', 'kl', 'mkl', 'dual']
+	#thresholds = [ 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]
+	#modes = [ 'hfc' ]
+	thresholds = [0.5]
+
+	#datapath = "%s%s" % (DATADIR,'/onset/DB/*/')
+	respath = '/var/tmp/DB-testings'
+
+	benchonset = mybenchonset(datapath,respath,checkres=True,checkanno=True)
+	benchonset.params = taskparams()
+	benchonset.task = taskonset
+	benchonset.valuesdict = {}
+
+	try:
+		#benchonset.auto_learn2(modes=modes)
+		benchonset.run_bench(modes=modes,thresholds=thresholds)
+	except KeyboardInterrupt:
+		sys.exit(1)
Index: tests/demo/bench/onset/bench-onset
===================================================================
--- tests/demo/bench/onset/bench-onset	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/onset/bench-onset	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,68 @@
+#! /usr/bin/python
+
+from aubio.task import *
+
+from aubio.bench.onset import mmean, stdev, benchonset
+
+class mybenchonset(benchonset):
+
+	def run_bench(self,modes=['dual'],thresholds=[0.5]):
+		from os.path import dirname,basename
+		self.thresholds = thresholds
+		self.pretty_titles()
+		d,e,f,g = [],[],[],[]
+		for mode in modes:
+			self.vlist = []
+			self.params.onsetmode = mode
+			#self.params.localmin = True
+
+			for threshold in self.thresholds:
+				self.params.threshold = threshold
+				self.dir_eval_print()
+				self.vlist.append(self.v)
+			self.plotroc(d)
+			self.plotfmeas(e)
+			self.plotpr(f)
+			#self.plothistcat(g)
+
+
+
+		#self.plotplotroc(d)
+		#self.plotplotfmeas(e)
+		#self.plotplotpr(f)
+		outplot = basename(self.datadir)
+		for ext in ("png","svg","ps"):
+			self.plotplotroc(d,outplot=outplot,extension=ext)
+			self.plotplotfmeas(e,outplot=outplot,extension=ext)
+			self.plotplotpr(f,outplot=outplot,extension=ext)
+			#self.plotplothistcat(g,outplot=outplot,extension=ext)
+
+if __name__ == "__main__":
+	import sys
+	if len(sys.argv) > 1: datapath = sys.argv[1]
+	else: print "ERR: a path is required"; sys.exit(1)
+	modes = ['complex', 'energy', 'phase', 'hfc', 'specdiff', 'kl', 'mkl', 'dual']
+	thresholds = [ 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]
+	#modes = [ 'hfc' ]
+	#thresholds = [0.5]
+
+	#datapath = "%s%s" % (DATADIR,'/onset/DB/*/')
+	respath = '/var/tmp/DB-testings'
+
+	benchonset = mybenchonset(datapath,respath,checkres=True,checkanno=True)
+	benchonset.params = taskparams()
+	benchonset.params.dcthreshold = -1.
+	benchonset.params.silence = -100.
+	benchonset.params.delay = 5. 
+	benchonset.params.bufsize = 1024 
+	benchonset.params.hopsize = 256 
+	benchonset.params.step = float(benchonset.params.hopsize)/float(benchonset.params.samplerate)
+	benchonset.params.mintol = 4.1 
+	benchonset.task = taskonset
+	benchonset.valuesdict = {}
+
+	try:
+		#benchonset.auto_learn2(modes=modes)
+		benchonset.run_bench(modes=modes,thresholds=thresholds)
+	except KeyboardInterrupt:
+		sys.exit(1)
Index: tests/demo/bench/onset/bench-window
===================================================================
--- tests/demo/bench/onset/bench-window	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/onset/bench-window	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,59 @@
+#! /usr/bin/python
+
+from aubio.bench.onset import benchonset
+from aubio.task.onset import taskonset
+from aubio.task.params import taskparams
+
+class mybenchonset(benchonset):
+
+	def run_bench(self,modes=['dual'],thresholds=[0.5]):
+		from os.path import dirname,basename
+		self.thresholds = thresholds
+		self.pretty_titles()
+
+		for mode in modes:
+
+			self.params.onsetmode = mode
+			self.params.localmin = True
+			self.params.delay = 1. 
+			self.params.threshold = thresholds[0]
+			self.params.localmin = False 
+			#
+			for delay in (0., 4.):
+				d = []
+				self.params.delay = delay 
+				for buf in (2048, 1024, 512):
+					for hop in (buf/2, buf/4):
+						self.params.bufsize = buf 
+						self.params.hopsize = hop 
+						self.params.step = float(self.params.hopsize)/float(self.params.samplerate)
+						self.dir_eval_print()
+						self.plotdiffs(d,plottitle="%s %s" % (buf,hop))
+				#plotplotdiffs(d)
+				outplot = "_-_".join(("window",mode,"delay-%s" % int(delay),
+					basename(self.datadir) ))
+				for ext in ("png","svg","ps"):
+					self.plotplotdiffs(d,outplot=outplot,extension=ext)
+
+if __name__ == "__main__":
+	import sys
+	if len(sys.argv) > 1: datapath = sys.argv[1]
+	else: print "ERR: a path is required"; sys.exit(1)
+	modes = ['complex', 'energy', 'phase', 'hfc', 'specdiff', 'kl', 'mkl', 'dual']
+	#thresholds = [ 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]
+	#modes = [ 'hfc' ]
+	thresholds = [0.5]
+
+	#datapath = "%s%s" % (DATADIR,'/onset/DB/*/')
+	respath = '/var/tmp/DB-testings'
+
+	benchonset = mybenchonset(datapath,respath,checkres=True,checkanno=True)
+	benchonset.params = taskparams()
+	benchonset.task = taskonset
+	benchonset.valuesdict = {}
+
+	try:
+		#benchonset.auto_learn2(modes=modes)
+		benchonset.run_bench(modes=modes,thresholds=thresholds)
+	except KeyboardInterrupt:
+		sys.exit(1)
Index: tests/demo/bench/pitch/Makefile.am
===================================================================
--- tests/demo/bench/pitch/Makefile.am	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/pitch/Makefile.am	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,59 @@
+export AUBIODIR=../../../..
+export PYTHONPATH=$(AUBIODIR)/python
+export LD_LIBRARY_PATH=$(AUBIODIR)/src/.libs:$(AUBIODIR)/ext/.libs
+
+CP=cp -a
+
+SOURCE = \
+	$(BASEDIR)/isolated/vibraphone \
+	$(BASEDIR)/isolated/clavinet \
+	$(BASEDIR)/isolated/elecguitar \
+	$(BASEDIR)/isolated/piano \
+	$(BASEDIR)/isolated/rhodes \
+	$(BASEDIR)/isolated
+
+
+MONOSOURCE = \
+	$(BASEDIR)/monophonic/Mirex04/daisy \
+	$(BASEDIR)/monophonic/Mirex04/midi \
+	$(BASEDIR)/monophonic/Mirex04/jazz \
+	$(BASEDIR)/monophonic/Mirex04/pop \
+	$(BASEDIR)/monophonic/Mirex04/opera \
+	$(BASEDIR)/monophonic/Mirex04
+
+POLYSOURCE = \
+	$(BASEDIR)/polyphonic/Mirex04/daisy \
+	$(BASEDIR)/polyphonic/Mirex04/midi \
+	$(BASEDIR)/polyphonic/Mirex04/jazz \
+	$(BASEDIR)/polyphonic/Mirex04/pop \
+	$(BASEDIR)/polyphonic/Mirex04/opera \
+	$(BASEDIR)/polyphonic/Mirex04
+
+test-aubiopitch-isolated:    $(patsubst %, %.aubiopitch-isolated, $(SOURCE))
+test-aubiopitch-monophonic:  $(patsubst %, %.aubiopitch-monophonic, $(MONOSOURCE))
+test-aubiopitch-polyphonic:  $(patsubst %, %.aubiopitch-polyphonic, $(POLYSOURCE))
+
+plotpitch:
+	../../../aubiopitch -m fcomb,mcomb,yinfft,yin,schmitt -i jazz2REF.wav -p -t 0.2 -l 100 -M 600 -O jazz2REF.ps
+	../../../aubiopitch -m fcomb,mcomb,yinfft,yin,schmitt -p -t 0.2 -l 300 -M 900 -i opera_fem2REF.wav -O opera_fem2REF.ps
+
+timings:
+	./bench-timings $(BASEDIR)/polyphonic/Mirex04/opera
+
+%.aubiopitch-isolated: %
+	$(CP) isolated/`basename $@` isolated/`basename $@`.old
+	./bench-pitch-isolated $< | tee isolated/`basename $@`
+	-diff isolated/`basename $@`.old isolated/`basename $@`
+	-diff isolated/`basename $@`.ref isolated/`basename $@`
+
+%.aubiopitch-monophonic: %
+	$(CP) monophonic/`basename $@` monophonic/`basename $@`.old
+	./bench-pitch-monophonic $< | tee monophonic/`basename $@`
+	-diff monophonic/`basename $@`.ref monophonic/`basename $@`
+	-diff monophonic/`basename $@`.old monophonic/`basename $@`
+
+%.aubiopitch-polyphonic: %
+	$(CP) polyphonic/`basename $@` polyphonic/`basename $@`.old
+	./bench-pitch-polyphonic $< | tee polyphonic/`basename $@`
+	-diff polyphonic/`basename $@`.ref polyphonic/`basename $@`
+	-diff polyphonic/`basename $@`.old polyphonic/`basename $@`
Index: tests/demo/bench/pitch/bench-pitch-isolated
===================================================================
--- tests/demo/bench/pitch/bench-pitch-isolated	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/pitch/bench-pitch-isolated	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,198 @@
+#! /usr/bin/python
+
+from aubio.bench.node import *
+from aubio.task import *
+
+class benchpitch(bench):
+	
+	""" list of values to store per file """
+	valuenames = ['mode']
+	""" list of lists to store per file """
+	valuelists = ['truth', 'osil', 'esil', 'opit', 'epit', 'echr', 
+               'Msil', 'Mpit', 'Mchr',
+	       'TotalPit', 'TotalPit', 'TotalChr' ]
+	""" list of values to print per dir """
+	printnames_total = [ 'mode', 'MinPit', 'MaxPit', 'TotalSil', 'TotalPit', 'TotalChr']
+	printnames_notes = [ 'mode', 'Note', 'Sil', 'Pit', 'Chr']
+	printnames = printnames_notes 
+
+	""" per dir """
+	formats = {'mode': "%12s" , 
+		'truth': "%s",
+		'osil': "%s", 'esil': "%s", 
+		'opit': "%s", 'epit': "%s", 'echr': "%s",
+    'Note': "%s", 'Sil': "%s", 'Chr': "%s", 'Pit': "%s",
+		'TotalPit': "%s", 'TotalSil': "%s", 'TotalChr': "%s",
+		'MinPit': "%s", 'MaxPit': "%s",
+		'Msil': "%s", 'Mpit': "%s", 'Mchr': "%s"}
+
+	def dir_eval(self):
+		""" evaluate statistical data over the directory """
+		v = self.v
+		v['mode']      = self.params.pitchmode
+
+	def file_exec(self,input,output):
+		filetask = self.task(input,params=self.params)
+		computed_data = filetask.compute_all()
+ 		osil, esil, opit, epit, echr = filetask.eval(computed_data,tol=0.5)
+		self.v['truth'].append(int(filetask.truth))
+		assert opit > 0
+		
+		self.v['osil'].append(osil)
+		self.v['esil'].append(esil)
+		self.v['opit'].append(opit)
+		self.v['epit'].append(epit)
+		self.v['echr'].append(echr)
+
+		self.v['Msil'].append(esil/float(osil)*100.)
+		self.v['Mpit'].append(epit/float(opit)*100.)
+		self.v['Mchr'].append(echr/float(opit)*100.)
+		#print results#, computed_data
+		#print input, results, results - float(input.split('.')[-2])
+			
+	def run_bench(self,modes=['schmitt'],multiplot=0):
+		from os.path import basename
+		self.modes = modes
+		self.pretty_titles()
+		d = []
+		for mode in self.modes:
+			self.params.pitchmode = mode
+			self.dir_exec()
+			self.dir_eval()
+			truth   = [i for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allOsil = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allEsil = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allOpit = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allEpit = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allEchr = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allMsil = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allMpit = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			allMchr = [0 for i in range(min(self.v['truth']),max(self.v['truth'])+1)]
+			for i in range(len(self.v['truth'])):
+				allOsil[self.v['truth'][i]-min(self.v['truth'])] += self.v['osil'][i]
+				allEsil[self.v['truth'][i]-min(self.v['truth'])] += self.v['esil'][i]
+				allOpit[self.v['truth'][i]-min(self.v['truth'])] += self.v['opit'][i]
+				allEpit[self.v['truth'][i]-min(self.v['truth'])] += self.v['epit'][i]
+				allEchr[self.v['truth'][i]-min(self.v['truth'])] += self.v['echr'][i]
+			for i in range(len(truth)):
+				allOsil[i] = max(1,allOsil[i])
+				allOpit[i] = max(1,allOpit[i])
+				allMsil[i] = allEsil[i]/float(allOsil[i])*100.
+				allMpit[i] = allEpit[i]/float(allOpit[i])*100.
+				allMchr[i] = allEchr[i]/float(allOpit[i])*100.
+				self.v['Sil'], self.v['Pit'], self.v['Chr'] = allMsil[i], allMpit[i], allMchr[i]
+				self.v['Note'] = truth[i]
+				#self.printnames = self.printnames_notes
+				self.pretty_print()
+			self.v['TotalSil'] = sum(allMsil)/len(truth)
+			self.v['TotalPit'] = sum(allMpit)/len(truth)
+			self.v['TotalChr'] = sum(allMchr)/len(truth)
+			self.v['MinPit'] = min(truth) 
+			self.v['MaxPit'] = max(truth) 
+			#self.printnames = self.printnames_total
+			#self.pretty_print()
+
+			plot = []
+			self.plotpitchtessiture(plot,
+				truth, 
+				allMpit,
+				plottitle="%s %s" % (self.v['mode'],self.params.bufsize),
+				plotmode='lines')
+			"""
+			self.plotpitchtessiture(plot,
+				truth, 
+				allMchr,
+				plottitle="%s %s" % (self.v['mode'],"%12"),
+				plotmode='lines')
+			self.plotpitchtessiture(plot,
+				truth, 
+				allMsil,
+				plottitle="%s %s" % (self.v['mode'],"sil"),
+				plotmode='lines')
+			"""
+			title = basename(self.datadir)
+			if multiplot:
+				d.append(plot)
+			else:
+				d += plot
+		outplot = "_-_".join(('pitchtessiture',title))
+		self.xmin = min(self.v['truth']) #20.
+		self.xmax = max(self.v['truth'])
+		for ext in ('ps','png','svg'): #,''):
+			self.plotplotpitchtessiture(d,
+				plottitle="".join(['Performance against MIDI Note number (',
+					title,
+					", %s" % len(self.sndlist), " samples)"]),
+				outplot=outplot,
+				extension=ext,multiplot=multiplot)
+		#d.append('beta = .25,orig(x) title \"-2 octave\"')
+		#d.append('beta = .50,orig(x) title \"-1 octave\"')
+		#d.append('beta = 1.0,orig(x) title \"original\"')
+		#d.append('beta = 2.0,orig(x) title \"+1 octave\"')
+
+	"""
+	Plot functions 
+	"""
+
+	def plotpitchtessiture(self,d,lx,ly,plottitle="",plotmode='linespoints'):
+		import Gnuplot, Gnuplot.funcutils
+		d.append(Gnuplot.Data(lx, ly, with=plotmode, title="%s" % (plottitle) ))
+
+	def plotplotpitchtessiture(self,d,plottitle='',outplot=0,extension='',multiplot=1):
+		from aubio.gnuplot import gnuplot_create
+		g = gnuplot_create(outplot=outplot,extension=extension) 
+		#g.title(plottitle)
+		#g('orig(x) = beta*x')
+		g.title(plottitle)
+		g('set yrange [50:100]')
+		# erase axis
+		g('set xrange [%f:%f]' % (self.xmin,self.xmax)) #(self.xmax - (self.xmax-self.xmin)*5./4.,self.xmax))
+		#g.plot(*d)
+		g('set border 3')
+		g('set xtics nomirror')
+		g('set ytics nomirror')
+		g('set key bottom')
+		if multiplot:
+			g('set multiplot')
+			for i in range(len(d)):
+				# plot onset detection functions
+				g('set size   1,%f' % ( 1.0/float(len(d)) ) )
+				g('set origin 0,%f' % ( 1.0*float(len(d)-i-1)/float(len(d)) ) )
+				#g.ylabel('%Correct detections')
+				g('set xrange [%f:%f]' % (self.xmin,self.xmax)) #(self.xmax - (self.xmax-self.xmin)*5./4.,self.xmax))
+				g.plot(*d[i])
+				g('unset title')
+			g('unset multiplot')
+		else:
+			g.plot(*d)
+
+
+if __name__ == "__main__":
+	import sys
+	if len(sys.argv) > 1: datapath = sys.argv[1]
+	else: print "error: a path is required"; sys.exit(1)
+	if len(sys.argv) > 2:
+		for each in sys.argv[3:-1]: print each
+	modes = ['schmitt', 'yin', 'yinfft', 'mcomb', 'fcomb']
+	#modes = ['mcomb']
+
+	params = taskparams()
+	params.bufsize = 2048 # 4096 
+	params.hopsize = 256
+	params.silence = -60.
+	params.pitchsmooth = 0 
+	params.pitchmax = 20000
+	params.pitchmin = 20
+	params.pitchyinfft = 0.95
+	benchpitch = benchpitch(datapath,params=params)
+	benchpitch.task = taskpitch
+
+	#benchpitch.titles  = [ 'mode', 'thres', 'avg', 'avgdist' ]
+	#benchpitch.formats = ["%12s" , "| %6s", "| %6s", "| %6s", "| %6s", "| %6s" ]
+	try:
+		benchpitch.run_bench(modes=modes)
+	except KeyboardInterrupt:
+		print "Interrupted by user"
+		sys.exit(1)
+
+	sys.exit(0)
Index: tests/demo/bench/pitch/bench-pitch-plot-isolated
===================================================================
--- tests/demo/bench/pitch/bench-pitch-plot-isolated	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/pitch/bench-pitch-plot-isolated	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,63 @@
+#! /usr/bin/python
+
+if __name__ == '__main__':
+  import sys, Gnuplot
+  from aubio.gnuplot import gnuplot_create
+  from aubio.txtfile import read_datafile
+  from aubio.plot.keyboard import draw_keyboard
+  lines = []
+  titles = []
+  for file in range(len(sys.argv)-1):
+    l = read_datafile(sys.argv[file+1])
+    notes, score = [],[]
+    for i in range(len(l)):
+      notes.append(l[i][0])
+      score.append(l[i][2])
+    lines.append(Gnuplot.Data(notes,score,
+      with='linespoints',
+      title=sys.argv[file+1].split('.')[-1]))
+    titles.append(sys.argv[file+1].split('.')[-1])
+  blacks,whites = draw_keyboard(firstnote = notes[0], lastnote = notes[-1], 
+    y0= 40, y1 = 50)
+
+  g = gnuplot_create(sys.argv[file+1].split('.')[-3],'ps')
+  #g = gnuplot_create('','')
+  #g = gnuplot_create('/tmp/test','eps')
+  g('set yrange [40:100]')
+  #g('set xrange [%f:%f]' % (notes[0],notes[-1]+60))
+  g('set size 0.5')
+  g('set key outside')
+
+  g('set border 3')
+  g('set xtics nomirror')
+  g('set ytics nomirror')
+  multiplot = 1
+  oplots = lines
+  g('set size 1,2')
+  if multiplot:
+    height = 2.
+    g('set lmargin 10')
+    #g('set rmargin 15')
+    g('set multiplot')
+    g('set yrange [50:100]')
+    g('set xrange [%f:%f]' % (notes[0],notes[-1]))
+    g('set xtics %f,12' % notes[0])
+    g('set nokey')
+    for i in range(len(oplots)):
+      g.ylabel(titles[i])
+      g('set size %f,%f' % (1.,height*.85/float(len(oplots))))
+      g('set origin 0,%f' % (height*(.15+.85*float(len(oplots)-i-1)/float(len(oplots)))))
+      g.plot(oplots[i])
+    g('set title "Raw pitch accuracy (%) against midi note numbers"')
+    g('set noxtics')
+    g('set noytics')
+    g('set size %f,%f' % (1.,.15*height))
+    g('set origin 0,%f' % 0)
+    g('set yrange [40:50]')
+    g('set xrange [%f:%f]' % (notes[0],notes[-1]))
+    g.xlabel('')
+    g.ylabel('')
+    g.plot(whites,blacks)
+    g('unset multiplot')
+  else:
+    g.plot(whites,blacks,*lines)
Index: tests/demo/bench/tempo/demo-tempo
===================================================================
--- tests/demo/bench/tempo/demo-tempo	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/tempo/demo-tempo	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,313 @@
+#! /usr/bin/python
+
+""" this file was written by Paul Brossier 
+  it is released under the GNU/GPL license.
+"""
+
+import sys,time
+from aubio.task import taskbeat,taskparams
+from aubio.aubioclass import fvec, aubio_autocorr
+from aubio.gnuplot import gnuplot_create, gnuplot_addargs
+from aubio.aubiowrapper import *
+from math import exp,log
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+def parse_args():
+        from optparse import OptionParser
+        parser = OptionParser(usage=usage)
+        parser.add_option("-i","--input",
+                          action="store", dest="filename", 
+                          help="input sound file")
+        parser.add_option("-n","--printframe",
+                          action="store", dest="printframe", default=-1, 
+                          help="make a plot of the n_th frame")
+        gnuplot_addargs(parser)
+        (options, args) = parser.parse_args()
+        if not options.filename: 
+                 print "no file name given\n", usage
+                 sys.exit(1)
+        return options, args
+
+def plotdata(x,y,plottitle="",**keyw):
+	import Gnuplot
+	return Gnuplot.Data(x, y, title="%s" % plottitle,**keyw)
+
+options, args = parse_args()
+filename = options.filename
+xsize = float(options.xsize)
+ysize = float(options.ysize)
+
+printframe = int(options.printframe)
+
+if options.outplot and printframe > 0: 
+  extension = options.outplot.split('.')[-1] 
+  outplot = '.'.join(options.outplot.split('.')[:-1])
+else: 
+  extension = ''
+  outplot = None
+f = gnuplot_create(outplot=outplot,extension=extension,options=options)
+
+params = taskparams()
+params.onsetmode = 'specdiff'
+task = taskbeat(filename,params=params)
+
+hopsize = params.hopsize
+bufsize = params.bufsize
+btstep = task.btstep
+winlen = task.btwinlen
+laglen = winlen/4
+step = winlen/4
+
+timesig = 0
+maxnumelem = 4
+gp = 0
+counter = 0
+flagconst = 0
+constthresh = 3.901
+g_var      = 3.901
+rp = 0
+rp1 = 0
+rp2 = 0
+g_mu = 0
+
+rayparam = 48/512.*winlen
+
+#t     = [i for i in range(hopsize)]
+#tlong = [i for i in range(hopsize*(btstep-1))]
+#tall  = [i for i in range(hopsize*btstep)]
+#a     = [0 for i in range(hopsize*btstep)]
+dfx = [i for i in range(winlen)]
+dfframe = [0 for i in range(winlen)]
+dfrev = [0 for i in range(winlen)]
+acframe = [0 for i in range(winlen)]
+
+localacf = [0 for i in range(winlen)]
+inds = [0 for i in range(maxnumelem)]
+
+acx = [i for i in range(laglen)]
+acfout  = [0 for i in range(laglen)]
+
+phwv  = [0 for i in range(2*laglen)]
+phwvx = [i for i in range(2*laglen)]
+
+dfwvnorm = exp(log(2.0)*(winlen+2.)/rayparam);
+dfwv = [exp(log(2.)*(i+1.)/rayparam)/dfwvnorm for i in range(winlen)]
+
+gwv = [exp(-.5*(j+1.-g_mu)**2/g_var**2) for j in range(laglen)]
+rwv = [(i+1.)/rayparam**2 * exp(-(i+1.)**2 / (2.*rayparam)**2)
+        for i in range(0,laglen)] 
+acf = fvec(winlen,1)
+
+nrframe = 0
+while (task.readsize == params.hopsize):
+  task()
+  #print task.pos2
+  #a[:-hopsize] = [i for i in a[-(btstep-1)*hopsize:]]
+  #a[-hopsize:] = [task.myvec.get(i,0) for i in t]
+
+  #g('set xrange [%f:%f]' % (t[0],t[-1]))
+  #time.sleep(.2)
+  if task.pos2==btstep-1:
+    nrframe += 1
+    dfframe = [task.dfframe.get(i,0) for i in range(winlen)]
+    if printframe == nrframe or printframe == -1:
+      d  = [[plotdata(range(-winlen,0),dfframe,plottitle="onset detection", with='lines')]]
+    # start beattracking_do
+    for i in range(winlen):
+      dfrev[winlen-1-i] = 0.
+      dfrev[winlen-1-i] = dfframe[i]*dfwv[i]
+    aubio_autocorr(task.dfframe(),acf()); 
+    acframe = [acf.get(i,0) for i in range(winlen)]
+    if not timesig:
+      numelem = 4
+    else:
+      numelem = timesig
+
+    old = 0
+    acfout = [0 for i in range(winlen/4)]
+    for i in range(1,laglen-1):
+      for a in range(1,numelem+1):
+        for b in range (1-a,a):
+          acfout[i] += acframe[a*(i+1)+b-1] * 1./(2.*a-1.)*rwv[i]
+          if old < acfout[i]:
+            old = acfout[i]
+            maxi = i
+    rp = max(maxi,1);
+
+    if printframe == nrframe or printframe == -1:
+      rwvs = [rwv[i]*max(acframe) for i in range(len(rwv))]
+      d += [[plotdata(acx,acfout,plottitle="comb filterbank", with='lines', axes='x1y1'),
+          plotdata([rp,rp],[1.2*old,min(acfout)],plottitle="period", with='impulses', axes='x1y1'),
+          plotdata(acx,rwvs,plottitle="L_w", with='lines', axes='x1y1')]]
+
+    # getperiod
+    inds = [0 for i in range(maxnumelem)]
+    localacf = [0 for i in range(winlen)]
+    period = 0
+    for a in range(1,4+1):
+      for b in range(1-a,a):
+        localacf[a*rp+b-1] = acframe[a*rp+b-1]
+    for i in range(numelem):
+      maxindex = 0
+      maxval = 0.0
+      for j in range(rp*(i+1)+i):
+        if localacf[j] > maxval:
+          maxval = localacf[j]
+          maxind = j
+        localacf[j] = 0
+      inds[i] = maxind
+    for i in range(numelem):
+      period += inds[i]/(i+1.)
+    period = period/numelem
+    #print "period", period
+
+    # checkstate 
+    if gp:
+      # context dependant model
+      acfout = [0 for i in range(winlen/4)]
+      old = 0
+      for i in range(laglen-1):
+        for a in range(timesig):
+          for b in range(1-a,a):
+            acfout[i] += acframe[a*(i+1)+b-1] * gwv[i]
+        if old < acfout[i]:
+          old = acfout[i]
+          maxi = i
+      gp = maxi
+    else:
+      # general model
+      gp = 0
+    #print "gp", gp
+    if printframe == nrframe or printframe == -1:
+      gwvs = [gwv[i]*max(acfout) for i in range(len(gwv))]
+      d += [[plotdata(acx,acfout,plottitle="comb filterbank", with='lines', axes='x1y1'),
+          plotdata(gp,old,plottitle="period", with='impulses', axes='x1y1'),
+          plotdata(acx,gwvs,plottitle="L_{gw}", with='lines', axes='x1y1')]]
+
+    if counter == 0:
+      # initial step
+      if abs(gp-rp) > 2.*constthresh:
+        flagstep = 1
+        counter  = 3
+      else:
+        flagstep = 0
+    #print "flagstep", flagstep
+    #print "rp2,rp1,rp", rp2,rp1,rp
+    acfw = [dfframe[i]*dfwv[i] for i in range(winlen)]
+
+    if counter == 1 and flagstep == 1:
+      # "3rd frame after flagstep set"
+      if abs(2.*rp-rp1- rp2) < constthresh:
+        flagconst = 1
+        counter = 0
+      else:
+        flagconst = 0
+        counter = 2
+    elif counter > 0:
+      counter -= 1
+
+    rp2 = rp1; rp1 = rp
+
+    if flagconst:
+      # "first run of new hypothesis"
+      gp = rp
+      g_mu = gp
+      timesig = 4 #FIXME
+      gwv = [exp(-.5*(j+1.-g_mu)**2/g_var**2) for j in range(laglen)]
+      flagconst = 0
+      bp = gp
+      phwv = [1 for i in range(2*laglen)]
+    elif timesig:
+      # "contex dependant"
+      bp = gp
+      if step > lastbeat:
+        phwv = [exp(-.5*(1.+j-step+lastbeat)**2/(bp/8.)) for j in range(2*laglen)]
+      else:
+        print "NOT using phase weighting"
+        phwv = [1 for i in range(2*laglen)]
+    else:
+      # "initial state"
+      bp = rp
+      phwv = [1 for i in range(2*laglen)]
+
+    while bp < 25:
+      print "WARNING, doubling the beat period"
+      bp *= 2
+
+    # 
+    phout = [0. for i in range(winlen)]
+
+    kmax = int(winlen/float(bp));
+
+    old = 0
+    for i in range(bp):
+      phout[i] = 0.
+      for k in range(kmax):
+        phout[i] += dfrev[i+bp*k] * phwv[i]
+      if phout[i] > old:
+        old = phout[i]
+        maxi = i
+    maxindex = maxi 
+    if (maxindex == winlen - 1): maxindex = 0
+    phase = 1 + maxindex
+    i = 1
+    beat = bp - phase
+    beats= []
+    if beat >= 0: beats.append(beat)
+    while beat+bp < step: 
+      beat += bp
+      beats.append(beat)
+    lastbeat = beat
+    #print beats,
+    #print "the lastbeat is", lastbeat
+
+    # plot all this
+    if printframe == nrframe or printframe == -1:
+      phwvs = [phwv[i]*max(phout) for i in range(len(phwv))]
+      d += [[plotdata(range(-laglen,0),phwvs[laglen:0:-1],plottitle="A_{gw}", with='lines',axes='x1y1'),
+          plotdata(range(-laglen,0),phout[laglen:0:-1],plottitle="df", with='lines'),
+          plotdata(-phase,old,plottitle="phase", with='impulses', axes='x1y1'),
+          plotdata([i for i in beats],[old for i in beats],plottitle="predicted", with='impulses')
+          ]]
+    #d += [[plotdata(dfx,dfwv,plottitle="phase weighting", with='lines', axes='x1y2'),
+    #    plotdata(dfx,dfrev,plottitle="df reverse", with='lines', axes='x1y1')]]
+    #d += [[plotdata(dfx,phout,plottitle="phase", with='lines', axes='x1y2')]]
+    #d += [[plotdata(dfx,dfwv,plottitle="phase weighting", with='lines', axes='x1y2'),
+    #    plotdata(dfx,dfrev,plottitle="df reverse", with='lines', axes='x1y1')]]
+    #d += [[plotdata(dfx,phout,plottitle="phase", with='lines', axes='x1y2')]]
+
+      f('set lmargin 4')
+      f('set rmargin 4')
+      f('set size %f,%f' % (1.0*xsize,1.0*ysize) )
+      f('set key spacing 1.3')
+      f('set multiplot')
+
+      f('set size %f,%f' % (1.0*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.0*xsize,0.66*ysize) )
+      f('set xrange [%f:%f]' % (-winlen,0) )
+      f.title('Onset detection function')
+      f.xlabel('time (df samples)')
+      f.plot(*d[0])
+      f('set size %f,%f' % (0.5*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.0*xsize,0.33*ysize) )
+      f('set xrange [%f:%f]' % (0,laglen) )
+      f.title('Period detection: Rayleygh weighting')
+      f.xlabel('lag (df samples)')
+      f.plot(*d[1])
+      f('set size %f,%f' % (0.5*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.5*xsize,0.33*ysize) )
+      f('set xrange [%f:%f]' % (0,laglen) )
+      f.title('Period detection: Gaussian weighting')
+      f.xlabel('lag (df samples)')
+      f.plot(*d[2])
+      f('set size %f,%f' % (1.0*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.0*xsize,0.00*ysize) )
+      f('set xrange [%f:%f]' % (-laglen,laglen) )
+      f.title('Phase detection and predicted beats')
+      f.xlabel('time (df samples)')
+      f.plot(*d[3])
+      f('set nomultiplot')
+    if printframe == -1: a = sys.stdin.read()
+    elif 0 < printframe and printframe < nrframe:
+      break
Index: tests/demo/bench/tempo/demo-tempo-acf
===================================================================
--- tests/demo/bench/tempo/demo-tempo-acf	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
+++ tests/demo/bench/tempo/demo-tempo-acf	(revision 974dddc7e5fc66721c791c6dac2582395f1f39ea)
@@ -0,0 +1,157 @@
+#! /usr/bin/python
+
+""" this file was written by Paul Brossier 
+  it is released under the GNU/GPL license.
+"""
+
+import sys,time
+from aubio.task import taskbeat,taskparams
+from aubio.aubioclass import fvec, aubio_autocorr
+from aubio.gnuplot import gnuplot_create, gnuplot_addargs
+from aubio.aubiowrapper import *
+from math import exp,log
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+def parse_args():
+        from optparse import OptionParser
+        parser = OptionParser(usage=usage)
+        parser.add_option("-i","--input",
+                          action="store", dest="filename", 
+                          help="input sound file")
+        parser.add_option("-n","--printframe",
+                          action="store", dest="printframe", default=-1, 
+                          help="make a plot of the n_th frame")
+        gnuplot_addargs(parser)
+        (options, args) = parser.parse_args()
+        if not options.filename: 
+                 print "no file name given\n", usage
+                 sys.exit(1)
+        return options, args
+
+def plotdata(x,y,plottitle="",**keyw):
+	import Gnuplot
+	return Gnuplot.Data(x, y, title="%s" % plottitle,**keyw)
+
+options, args = parse_args()
+filename = options.filename
+xsize = float(options.xsize)
+ysize = float(options.ysize)
+
+printframe = int(options.printframe)
+
+if options.outplot and printframe > 0: 
+  extension = options.outplot.split('.')[-1] 
+  outplot = '.'.join(options.outplot.split('.')[:-1])
+else: 
+  extension = ''
+  outplot = None
+f = gnuplot_create(outplot,extension,options)
+
+params = taskparams()
+params.onsetmode = 'specdiff'
+task = taskbeat(filename,params=params)
+
+hopsize = params.hopsize
+bufsize = params.bufsize
+btstep = task.btstep
+winlen = task.btwinlen
+laglen = winlen/4
+step = winlen/4
+
+timesig = 0
+maxnumelem = 4
+gp = 0
+counter = 0
+flagconst = 0
+constthresh = 3.901
+g_var      = 3.901
+rp = 0
+rp1 = 0
+rp2 = 0
+g_mu = 0
+
+rayparam = 48/512.*winlen
+
+t     = [i for i in range(hopsize)]
+#tlong = [i for i in range(hopsize*(btstep-1))]
+#tall  = [i for i in range(hopsize*btstep)]
+sig    = [0 for i in range(hopsize*btstep*4)]
+dfx = [i for i in range(winlen)]
+dfframe = [0 for i in range(winlen)]
+dfrev = [0 for i in range(winlen)]
+acframe = [0 for i in range(winlen/2)]
+
+localacf = [0 for i in range(winlen)]
+inds = [0 for i in range(maxnumelem)]
+
+acx = [i for i in range(laglen)]
+acfout  = [0 for i in range(laglen)]
+
+phwv  = [0 for i in range(2*laglen)]
+phwvx = [i for i in range(2*laglen)]
+
+dfwvnorm = exp(log(2.0)*(winlen+2.)/rayparam);
+dfwv = [exp(log(2.)*(i+1.)/rayparam)/dfwvnorm for i in range(winlen)]
+
+gwv = [exp(-.5*(j+1.-g_mu)**2/g_var**2) for j in range(laglen)]
+rwv = [(i+1.)/rayparam**2 * exp(-(i+1.)**2 / (2.*rayparam)**2)
+        for i in range(0,laglen)] 
+acf = fvec(winlen,1)
+
+nrframe = 0
+while (task.readsize == params.hopsize):
+  task()
+  #print task.pos2
+  sig[:-hopsize] = [i for i in sig[-(btstep*4-1)*hopsize:]]
+  sig[-hopsize:] = [task.myvec.get(i,0) for i in t]
+
+  #g('set xrange [%f:%f]' % (t[0],t[-1]))
+  #time.sleep(.2)
+  if task.pos2==btstep-1:
+    nrframe += 1
+    dfframe = [task.dfframe.get(i,0) for i in range(winlen)]
+    # start beattracking_do
+    for i in range(winlen):
+      dfrev[winlen-1-i] = 0.
+      dfrev[winlen-1-i] = dfframe[i]*dfwv[i]
+    aubio_autocorr(task.dfframe(),acf()); 
+    acframe = [acf.get(i,0) for i in range(winlen/2)]
+    if printframe == nrframe or printframe == -1:
+      d  = [[plotdata(range(0,btstep*hopsize*4,4),sig[0:-1:4],plottitle="input signal", with='lines')]]
+      d  += [[plotdata(range(-winlen,0),dfframe,plottitle="onset detection", with='lines')]]
+      d  += [[plotdata(range(winlen/2),acframe,plottitle="autocorrelation", with='lines')]]
+
+    # plot all this
+    if printframe == nrframe or printframe == -1:
+
+      f('set lmargin 4')
+      f('set rmargin 4')
+      f('set size %f,%f' % (1.0*xsize,1.0*ysize) )
+      f('set key spacing 1.3')
+      f('set multiplot')
+
+      f('set size %f,%f' % (1.0*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.0*xsize,0.66*ysize) )
+      f('set xrange [%f:%f]' % (0,btstep*hopsize*4) )
+      f('set yrange [%f:%f]' % (-1.2*max(sig),1.2*max(sig)) )
+      f.title('Input signal')
+      f.xlabel('time (samples)')
+      f.plot(*d[0])
+      f('set size %f,%f' % (1.0*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.0*xsize,0.33*ysize) )
+      f('set xrange [%f:%f]' % (-winlen,0) )
+      f('set autoscale y')
+      f.title('Onset detection function')
+      f.xlabel('time (df samples)')
+      f.plot(*d[1])
+      f('set size %f,%f' % (1.0*xsize,0.33*ysize) )
+      f('set orig %f,%f' % (0.0*xsize,0.00*ysize) )
+      f('set xrange [%f:%f]' % (0,winlen/2) )
+      f.title('Autocorrelation')
+      f.xlabel('lag (df samples)')
+      f.plot(*d[2])
+      f('set nomultiplot')
+    if printframe == -1: a = sys.stdin.read()
+    elif 0 < printframe and printframe < nrframe:
+      break
