Cyclic Cross-correlation Python

Is it possible to perform circular cross / autocorrelation on 1D arrays with the numpy / scipy / matplotlib function? I looked at numpy.correlate () and matplotlib.pyplot.xcorr (based on the numpy function), and both cannot seem to do circular cross-correlation.

To illustrate the difference, I will use the example array from [1, 2, 3, 4]. With circular correlation, a periodic assumption is made, and lag 1 looks like [2, 3, 4, 1]. I found that python functions seem to use null padding, i.e. [2, 3, 4, 0]. Is there a way to get these functions to perform circular correlation? If not, is there a standard workaround for circular correlations?

+7
python numpy scipy matplotlib signal-processing
source share
2 answers

You can implement periodic (aka circular) cross-correlation using FFT :

from numpy.fft import fft, ifft def periodic_corr(x, y): """Periodic correlation, implemented using the FFT. x and y must be real sequences with the same length. """ return ifft(fft(x) * fft(y).conj()).real 

You can also implement it using np.correlate if you are not against the overhead caused by np.hstack((y[1:], y)) :

 import numpy as np def periodic_corr_np(x, y): """Periodic correlation, implemented using np.correlate. x and y must be real sequences with the same length. """ return np.correlate(x, np.hstack((y[1:], y)), mode='valid') 
+8
source share
 from numpy import roll, correlate x = [1,2,3,4] roll(x, 1) #[4,1,2,3] roll(x, 2) #[3,4,1,2] roll(x, 3) #[2,3,4,1] 

To adjust x with x, by a circular shift by k, you could do

 k = 2 correlate(x, roll(x,k)) 
+2
source share

All Articles