简体   繁体   English

Python:一维数组循环卷积

[英]Python: 1d array circular convolution

I wonder if there's a function in numpy/scipy for 1d array circular convolution.我想知道 numpy/scipy 中是否有用于一维数组循环卷积的函数。 The scipy.signal.convolve() function only provides "mode" but not "boundary", while the signal.convolve2d() function needs 2d array as input. scipy.signal.convolve()函数只提供“模式”而不提供“边界”,而signal.convolve2d()函数需要二维数组作为输入。

I need to do this to compare open vs circular convolution as part of a time series homework.我需要这样做来比较开放与循环卷积作为时间序列作业的一部分。

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) ))

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 .通过卷积的定义,如果追加信号给自己,然后AAB之间的卷积将包含ab的循环卷积内。

Eg, 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));

在此处输入图片说明

That is the standard convolution.那就是标准的卷积。 Now this, however然而现在这

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

在此处输入图片说明

In this last figure, try to see where is the result of the circular convolution, and how to generalize this.在最后一张图中,试着看看循环卷积的结果在哪里,以及如何推广它。

Code for this that you can copy-paste, in the spirit of StackOverflow:本着 StackOverflow 的精神,您可以复制粘贴此代码:

n = a.shape[0]
np.convolve(np.tile(a, 2), b)[n:2 * n]

This assumes that a, b have the same shape.这假设 a, b 具有相同的形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM