def fast_autocorrelate(x):
"""
Compute the autocorrelation of the signal, based on the properties of the
power spectral density of the signal.
Note that the input's length may be reduced before the correlation is
performed due to a pathalogical case in numpy.fft:
http://stackoverflow.com/a/23531074/679081
> The FFT algorithm used in np.fft performs very well (meaning O(n log n))
> when the input length has many small prime factors, and very bad
> (meaning a naive DFT requiring O(n^2)) when the input size is a prime
> number.
"""
# This is one simple way to ensure that the input array
# has a length with many small prime factors, although it
# doesn't guarantee that (also hopefully we don't chop too much)
optimal_input_length = int(numpy.sqrt(len(x))) ** 2
x = x[:optimal_input_length]
xp = x - numpy.mean(x)
f = numpy.fft.fft(xp)
p = numpy.absolute(numpy.power(f, 2))
pi = numpy.fft.ifft(p)
result = numpy.real(pi)[:x.size / 2] / numpy.sum(numpy.power(xp, 2))
return result
评论列表
文章目录