Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 1d array circular convolution

I wonder if there's a function in numpy/scipy for 1d array circular convolution. The scipy.signal.convolve() function only provides "mode" but not "boundary", while the signal.convolve2d() function needs 2d array as input.

I need to do this to compare open vs circular convolution as part of a time series homework.

like image 624
Will Gu Avatar asked Feb 18 '16 06:02

Will Gu


People also ask

What is convolve Python?

convolve() is a built-in numpy library method used to return discrete, linear convolution of two one-dimensional vectors. The numpy convolve() method accepts three arguments which are v1, v2, and mode, and returns discrete the linear convolution of v1 and v2 one-dimensional vectors.

What is the formula for circular convolution?

f[n]⊛g[n] is the circular convolution (Section 7.5) of two periodic signals and is equivalent to the convolution over one interval, i.e. f[n]⊛g[n]=N∑n=0N∑η=0f[η]g[n−η].


2 Answers

By convolution theorem, you can use Fourier Transform to get circular convolution.

import numpy as np
def conv_circ( signal, ker ):
    '''
        signal: real 1D array
        ker: real 1D array
        signal and ker must have same shape
    '''
    return np.real(np.fft.ifft( np.fft.fft(signal)*np.fft.fft(ker) ))
like image 72
Kh40tiK Avatar answered Sep 25 '22 22:09

Kh40tiK


Since this is for homework, I'm leaving out a few details.

By the definition of convolution, if you append a signal a to itself, then the convolution between aa and b will contain inside the cyclic convolution of a and b.

E.g., consider the following:

import numpy as np
from scipy import signal

%pylab inline

a = np.array([1] * 10)
b = np.array([1] * 10)

plot(signal.convolve(a, b));

enter image description here

That is the standard convolution. Now this, however

plot(signal.convolve(a, np.concatenate((b, b))));

enter image description here

In this last figure, try to see where is the result of the circular convolution, and how to generalize this.

like image 33
Ami Tavory Avatar answered Sep 22 '22 22:09

Ami Tavory