Estimate the delay between two signals

Introduction

For two similar signals, their delay times are estimated by calculating the cross-correlation function. Python's Numpy is used to calculate the cross-correlation function.

Creating a signal

As an example, create two signals, one with and without delay, on the target signal with normal distribution and the noise with normal distribution.

import numpy as np

target_sig = np.random.normal(size=1000) * 1.0
delay = 800
sig1 = np.random.normal(size=2000) * 0.2
sig1[delay:delay+1000] += target_sig
sig2 = np.random.normal(size=2000) * 0.2
sig2[:1000] += target_sig

sig12.png

Calculation of cross-correlation function

Calculate the cross-correlation function of the two created signals with `np.correlate ()`. The maximum position of the cross-correlation function is the delay time. One caveat is that ** if the mean of the signal is far from 0 **, it will affect the calculation of the cross-correlation function.

sig1 = sig1 - sig1.mean()And so on**Set the average to 0**It is necessary to add processing such as.



```python
import numpy as np

corr = np.correlate(sig1, sig2, "full")
estimated_delay = corr.argmax() - (len(sig2) - 1)
print("estimated delay is " + str(estimated_delay))
estimated delay is 800

drawing

Draw at the end. You can see that there is a large peak in the part showing the delay time in the value of the cross-correlation function.

import matplotlib.pyplot as plt

plt.subplot(4, 1, 1)
plt.ylabel("sig1")
plt.plot(sig1)

plt.subplot(4, 1, 2)
plt.ylabel("sig2")
plt.plot(sig2, color="g")

plt.subplot(4, 1, 3)
plt.ylabel("fit")
plt.plot(np.arange(len(sig1)), sig1)
plt.plot(np.arange(len(sig2)) + estimated_delay, sig2 )
plt.xlim([0, len(sig1)])

plt.subplot(4, 1, 4)
plt.ylabel("corr")
plt.plot(np.arange(len(corr)) - len(sig2) + 1, corr, color="r")
plt.xlim([0, len(sig1)])

plt.show()

res.png

Recommended Posts

Estimate the delay between two signals
Examine the relationship between two variables (2)
Examine the relationship between two variables (1)
Bayesian modeling-estimation of the difference between the two groups-