Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

circular cross correlation python

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

To illustrate the difference, I will use the example of an array of [1, 2, 3, 4]. With circular correlation, a periodic assumption is made, and a lag of 1 looks like [2, 3, 4, 1]. The python functions I've found only seem to use zero-padding, i.e., [2, 3, 4, 0]. Is there a way to get these functions to do circular correlation? If not, is there a standard workaround for circular correlations?

like image 251
Lambert_W Avatar asked Feb 02 '15 18:02

Lambert_W


People also ask

What is circular cross-correlation?

The circular cross correlation is: c(k) = sum[a(n)*conj(b(n+k))]/[norm(a)*norm(b)]; where vector b is shifted CIRCULARLY by k samples. The function doesn't check the format of input vectors a and b!

How do you find the cross-correlation of two signals in Python?

In the Numpy program, we can compute cross-correlation of two given arrays with the help of correlate(). In this first parameter and second parameter pass the given arrays it will return the cross-correlation of two given arrays. Parameters : a, v : [array_like] Input sequences.

What does Scipy correlate2d do?

correlate2d. Cross-correlate two 2-dimensional arrays. Cross correlate in1 and in2 with output size determined by mode, and boundary conditions determined by boundary and fillvalue.


1 Answers

You can implement the periodic (a.k.a. circular) cross correlation using the 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 don't mind the overhead incurred 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')
like image 130
Warren Weckesser Avatar answered Oct 05 '22 14:10

Warren Weckesser