Skip to content

Implement conv in python #408

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions contents/convolutions/code/python/conv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import math
from scipy.fftpack import fft, ifft

def conv(signal1, signal2):
"""Discrete convolution by definition"""

n = len(signal1) + len(signal2) - 1
out = []

for i in range(n):
s = 0

for j in range(i + 1):
if j < len(signal1) and i - j < len(signal2):
s += signal1[j] * signal2[i - j]

out.append(s)

return out


def conv_fft(signal1, signal2):
"""Convolution using fft and convolutional theorem"""

signal1 = signal1.copy()
signal2 = signal2.copy()

# pad signals to same len
max_len = max(len(signal1), len(signal2))

for i in range(max_len - len(signal1)):
signal1.append(0)
for i in range(max_len - len(signal2)):
signal2.append(0)

fft_s1 = fft(signal1)
fft_s2 = fft(signal2)
out = []

for i in range(len(signal1)):
out.append(fft_s1[i] * fft_s2[i])

return list(ifft(out))


def main():
# Example convolution with sin and cos
s1 = [math.sin(x) for x in range(5)]
s2 = [math.cos(x) for x in range(5)]

print("Discrete Convolution")
print(conv(s1, s2))

print("FFT Convolution")
print(conv_fft(s1, s2))


if __name__ == "__main__":
main()

4 changes: 4 additions & 0 deletions contents/convolutions/convolutions.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ In code, this looks something like:
[import:5-18, lang:"c_cpp"](code/c/convolutions.c)
{% sample lang="cpp"%}
[import:68-88, lang:"c_cpp"](code/c++/convolutions.cpp)
{% sample lang="python"%}
[import:4-19, lang:"python"](code/python/conv.py)
{% endmethod %}

Note that in this case, the output array will be the size of `f[n]` and `g[n]` put together.
Expand Down Expand Up @@ -93,6 +95,8 @@ Where the `.*` operator is an element-wise multiplication.
[import:20-30, lang:"c_cpp"](code/c/convolutions.c)
{% sample lang="cpp"%}
[import:90-105, lang:"c_cpp"](code/c++/convolutions.cpp)
{% sample lang="python"%}
[import:22-43, lang:"python"](code/python/conv.py)
{% endmethod %}

This method also has the added advantage that it will *always output an array of the size of your signal*; however, if your signals are not of equal size, we need to pad the smaller signal with zeros.
Expand Down