I have an assignment where I need to convolve different real functions and make an animated gif out of it (similar to the one below). I wrote the program, but I got stuck in the part where I needed to make the animations. Can somebody give me a hint on how to do it? Thank you very much.
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
# defining functions
def rectangle(x: float, center: float = 1, length: float = 1, height: float = 1):
return (
np.heaviside(x - center + length / 2, 1) * height
- np.heaviside(x - center - length / 2, 1) * height
)
def triangle(x: float, center: float = 1, length: float = 1, height: float = 1):
res = np.where(
x < center,
height / length * x - height / length * (center - length),
height / length * center
- height / length * (x - center)
- height / length * (center - length),
)
return np.where(res > 0, res, 0)
def exponential(x: float, center: float = 1, length: float = 1, height: float = 1):
return height * np.where(x > center, np.exp(-(x - center)), 0)
def combi_func(
x: float,
func1,
center1: float,
length1: float,
height1: float,
func2,
center2: float,
length2: float,
height2: float,
):
return func1(x, center=center1, length=length1, height=height1) * func2(
x, center=center2, length=length2, height=height2
)
def convolution(
func1,
offset: float,
length1: float,
height1: float,
func2,
center2: float,
length2: float,
height2: float,
):
conv = np.zeros_like(offset)
for count, i in enumerate(offset):
conv[count] = integrate.quad(
combi_func,
0,
1,
args=(
func1,
offset[count],
length1,
height1,
func2,
center2,
length2,
height2,
),
)[0]
return conv
x = np.linspace(0, 1, 100)
centers = np.linspace(0, 1, 20)
conv = convolution(rectangle, centers, 0.25, 0.25, triangle, 0.5, 0.25, 0.25)
print(conv)
plt.figure()
plt.plot(x, triangle(x, center=0.5, length=0.25, height=0.25))
for count, center in enumerate(centers):
plt.plot(x, rectangle(x, center=centers[count], height=0.25, length=0.25))
plt.plot(centers, conv)
#plt.show()
# calling the animation function
?
# saves the animation in our desktop
writergif = animation.PillowWriter(fps=30)
anim.save('ConvolutionAnimation.gif',writer=writergif)
The animation I want to get: