Last active
January 19, 2022 07:59
-
-
Save fomightez/73f6c7b97e39a95c2eea0d77c68b954b to your computer and use it in GitHub Desktop.
Fixing the artifact of the two plots showing by adding clearing at right point. Via `plt.cla()`. see https://stackoverflow.com/q/70761535/8508004
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scipy.integrate | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import matplotlib.animation as animation | |
plt.rcParams["animation.html"] = "jshtml" | |
plt.rcParams['figure.dpi'] = 150 | |
plt.ioff() | |
def showConvolution(t0, f1, f2): | |
# Calculate the overall convolution result using Simpson integration | |
convolution = np.zeros(len(t)) | |
for n, t_ in enumerate(t): | |
prod = lambda tau: f1(tau) * f2(t_-tau) | |
convolution[n] = scipy.integrate.simps(prod(t), t) | |
# Create the shifted and flipped function | |
f_shift = lambda t: f2(t0-t) | |
prod = lambda tau: f1(tau) * f2(t0-tau) | |
# Plot the curves | |
plt.subplot(211) | |
plt.cla() | |
plt.plot(t, f1(t), label=r'$f_1(\tau)$') | |
plt.plot(t, f_shift(t), label=r'$f_2(t_0-\tau)$') | |
plt.plot(t, prod(t), 'r-', label=r'$f_1(\tau)f_2(t_0-\tau)$') | |
# plot the convolution curve | |
plt.subplot(212) | |
plt.plot(t, convolution, label='$(f_1*f_2)(t)$') | |
# recalculate the value of the convolution integral at the current time-shift t0 | |
current_value = scipy.integrate.simps(prod(t), t) | |
plt.plot(t0, current_value, 'ro') # plot the point | |
Fs = 50 # our sampling frequency for the plotting | |
T = 5 # the time range we are interested in | |
t = np.arange(-T, T, 1/Fs) # the time samples | |
f1 = lambda t: np.maximum(0, 1-abs(t)) | |
f2 = lambda t: (t>0) * np.exp(-2*t) | |
t0 = np.arange(-2.0,2.0, 0.05) | |
fig = plt.figure(figsize=(8,3)) | |
anim = animation.FuncAnimation(fig, showConvolution, frames=t0, fargs=(f1,f2),interval=80) | |
anim |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment