はじめに
本記事では、線形時不変システム(LTIシステム)における畳み込みの仕組みを視覚的に理解するための、Pythonによるアニメーションコードを解説します。
入力信号とインパルス応答の関係がどのように出力を生み出すのかを、段階的に確認できるよう工夫されています。
Colab上で実行・再生・ダウンロードが可能なコードも紹介していますので、ぜひ手を動かしながら学んでみてください。
参考リンクまとめ
Pythonコード
# --- ffmpegをインストール(必要な場合のみ)---
!apt-get -y install ffmpeg
# --- ライブラリのインポート ---
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from google.colab import files
from IPython.display import HTML
# === 時間軸設定 ===
t = np.linspace(0, 100, 1000)
dt = t[1] - t[0]
# === インパルス応答 h(t) ===
h = np.exp(-0.1 * t)
# === 入力信号 x(t) ===
x = np.zeros_like(t)
x[(t >= 10) & (t < 30)] = 1
x[(t >= 50) & (t < 70)] = 1
# === 出力格納配列 ===
y = np.zeros_like(t)
# === プロットの準備 ===
fig, axs = plt.subplots(4, 1, figsize=(10, 10), sharex=True)
lines = []
# 1. Impulse response
lines.append(axs[0].plot(t, h, color='orange')[0])
axs[0].set_title("Impulse Response: h(t)")
axs[0].set_ylim(-5, 5)
axs[0].grid()
# 2. Input signal
input_line, = axs[1].plot(t, x, color='blue')
point_dot, = axs[1].plot([], [], 'ro')
lines.append(input_line)
lines.append(point_dot)
axs[1].set_title("Input Signal: x(t)")
axs[1].set_ylim(-5, 5)
axs[1].grid()
# 3. Area: x(u) * h(t-u)
area_line, = axs[2].plot([], [], 'red')
axs[2].set_ylim(-5, 5)
axs[2].set_title('Area: x(u) * h(t - u) ("u" is the delay)')
axs[2].grid()
# 4. Output signal
output_line, = axs[3].plot([], [], color='blue')
axs[3].set_title(r'Output: $y(t) = \int x(u) h(t - u) du$')
axs[3].set_ylim(0, 25)
axs[3].grid()
# === アニメーション関数 ===
def update(frame):
t_now = t[frame]
h_shifted = np.zeros_like(t)
if frame > 0:
h_shifted[:frame] = h[frame - 1::-1]
area = x * h_shifted
y[frame] = np.sum(area * dt)
area_line.set_data(t, area)
point_dot.set_data([t_now], [x[frame]])
output_line.set_data(t[:frame], y[:frame])
return lines + [area_line, point_dot, output_line]
# === アニメーション作成 ===
ani = FuncAnimation(fig, update, frames=len(t), interval=15, blit=True)
# === MP4ファイルとして保存 ===
ani.save("convolution.mp4", writer="ffmpeg", fps=30)
# === ダウンロードリンクを表示 ===
files.download("convolution.mp4")