def OnNewBuffer(self, buffer, sampleInterval):
		power = map(lambda x: absolute(x) ** 2.0, fourier(buffer))
		
		leakage = power[9] + power[11]
		
		if leakage < self.bestLeakage:
			self.bestLeakage = leakage
			self.bestInterval = sampleInterval
		
		self.xs.append(sampleInterval)
		self.ys.append(leakage)
		
		if len(self.xs) > 5:
			#fit quadratic to the leakages and sample intervals
			coefficients = polyfit(self.xs, self.ys, 2)
			nextInterval = stats.quadraticMinimum(*coefficients)
			
			self.bestInterval = nextInterval
			#print rawSps / nextInterval
			
		else:
			nextInterval = self.bestInterval * (1.0 + self.initialLeapSize*(random() - 0.5))
			
		print rawSps / nextInterval
			
		return self.bestInterval, nextInterval
def PlotSpillageVsSampleFrequency(rawData, rawSps):
	startOffset = 7
	allData = []
	start = 748
	end = 488
	for offset in range(0, 2500, 100):
		
		xs  =[]
		ys = []
		
		for sps in range(748, 788, 1):
			#sps /= 10.0
			downSampledData = fftDataExtraction.downSample(data, rawSps, sps)[offset+startOffset:offset+128+startOffset]
			
			#pylab.plot([x/float(sps) for x in range(len(downSampledData))], downSampledData); pylab.show()
			
			#print sps, offset, len(downSampledData)
			frequencies = [float(sps) * x / len(downSampledData) for x in range(len(downSampledData)/2+1)]
			
			leakage = getToneLeakage(downSampledData)
			#print 'leakage: %f' % leakage
			#plot(fData, frequencies)
			#print '%d - %f' % (sps, leakage)
			xs.append(sps)
			ys.append(leakage)
		
		allData.append(ys)
			
	pylab.subplot(211)
	for ys in allData:
		pylab.plot(xs, ys)
	
	means = map(stats.mean, zip(*allData))
	pylab.subplot(212)
	pylab.plot(xs, means, '-o')
	pylab.grid(True)
	
	order = 2
	
	coefficients = polyfit(xs, means, order)
	print coefficients, stats.quadraticMinimum(*coefficients)
	generated = []
	for x in xs:
		y = sum([(float(x)**float(order - i)) * c for i, c in enumerate(coefficients)])
		#print x,y
		generated.append(y)
		
	diff = sum([(x1-x2)**2.0 / x1 for x1, x2 in zip(generated, means)])
	print start, end, diff
		
	#pylab.plot(xs, generated)	
	
	
	pylab.show()