python 自相关函数,使用Python估计自相关

I would like to perform Autocorrelation on the signal shown below. The time between two consecutive points is 2.5ms (or a repetition rate of 400Hz).

4e6507d85383dfc525fe1ff11d075d44.png

This is the equation for estimating autoacrrelation that I would like to use (Taken from http://en.wikipedia.org/wiki/Autocorrelation, section Estimation):

3f26487bdf86059cf74766dffdbf986d.png

What is the simplest method of finding the estimated autocorrelation of my data in python? Is there something similar to numpy.correlate that I can use?

Or should I just calculate the mean and variance?

Edit:

With help from unutbu, I have written:

from numpy import *

import numpy as N

import pylab as P

fn = 'data.txt'

x = loadtxt(fn,unpack=True,usecols=[1])

time = loadtxt(fn,unpack=True,usecols=[0])

def estimated_autocorrelation(x):

n = len(x)

variance = x.var()

x = x-x.mean()

r = N.correlate(x, x, mode = 'full')[-n:]

#assert N.allclose(r, N.array([(x[:n-k]*x[-(n-k):]).sum() for k in range(n)]))

result = r/(variance*(N.arange(n, 0, -1)))

return result

P.plot(time,estimated_autocorrelation(x))

P.xlabel('time (s)')

P.ylabel('autocorrelation')

P.show()

解决方案

I don't think there is a NumPy function for this particular calculation. Here is how I would write it:

def estimated_autocorrelation(x):

"""

http://stackoverflow.com/q/14297012/190597

http://en.wikipedia.org/wiki/Autocorrelation#Estimation

"""

n = len(x)

variance = x.var()

x = x-x.mean()

r = np.correlate(x, x, mode = 'full')[-n:]

assert np.allclose(r, np.array([(x[:n-k]*x[-(n-k):]).sum() for k in range(n)]))

result = r/(variance*(np.arange(n, 0, -1)))

return result

The assert statement is there to both check the calculation and to document its intent.

When you are confident this function is behaving as expected, you can comment-out the assert statement, or run your script with python -O. (The -O flag tells Python to ignore assert statements.)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值