'Numpy Convolution implementation for mode = same

I hope I chose the right platform for this question (wonders if it’s more related to math exchange or computer science).

In any regard, I’ve read about convolution in signal processing and I want to try to implement it. I was able to calculate convolution to the length of N+M-1.

This can be done with the following function (Python):

def convolve(x, h):
    xLen = len(x)
    hLen = len(h)
    if xLen == 0 or hLen == 0:
        return None

    totalLength = xLen + hLen - 1
    init = 0

    y = [0] * totalLength
    for n in range(init, totalLength):
        yn = 0
        k = max(0, n + 1 - xLen)
        j = n - k
        while k < hLen and j >= 0:
            yn += x[j] * h[k]
            j -= 1
            k += 1
        y[n] = yn
    return y

This is the the same as using numpy.convolve with mode=full.

My issue is that I don’t understand numpys mode=same, which performs the convolution till MAX(n, m). How can I calculate the convolution until that length without distorting the signal ?

In other words, I’d love to know how numpy implemented mode=same.

Thanks a lot!



Solution 1:[1]

If you read the documentation in detail https://numpy.org/doc/stable/reference/generated/numpy.convolve.html you can see that it states :

"same: Mode ‘same’ returns output of length max(M, N). Boundary effects are still visible."

So this mode is distorting the signal

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tbeolet