{ "cells": [ { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as pp\n", "import matplotlib.pyplot as plt\n", "\n", "\n", "import numpy as np\n", "pp.rcParams.update({'font.size': 14})\n", "pp.rcParams['figure.figsize'] = [10, 5]\n", "\n", "from matplotlib import animation, rc\n", "from IPython.display import HTML" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def wave_equation(u0,v0,N,M,T,c=1):\n", " from scipy import sparse\n", " k = T/M\n", " h = 1/(N+1)\n", " lam = c*k/h\n", "\n", " x = np.linspace(0,1,N+2)\n", " t = np.linspace(0,T,M+1)\n", " \n", " u = np.zeros((N+2,M+1))\n", " \n", " u[:,0] = u0(x)\n", " u[:,1] = u[:,0]+k*v0(x)\n", "\n", " B = np.zeros((3,N))\n", " B[0,:] = lam*lam\n", " B[1,:] = 2*(1-lam*lam)\n", " B[2,:] = lam*lam\n", "\n", " B = sparse.spdiags(B,[1,0,-1],N,N)\n", " \n", " for k in range(2,M+1):\n", " u_pprev = u[1:N+1,k-2]\n", " u_prev = u[1:N+1,k-1]\n", "\n", " u_next = B.dot(u_prev) - u_pprev\n", " u[1:N+1,k] = u_next\n", " return (x,t,u)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "def anim_wave(u0, v0, N, M, T, ylim):\n", " (x,t,u) = wave_equation(u0,v0,N=N,M=M,T=T)\n", "\n", " fig, ax = plt.subplots()\n", " ax.set_xlim(( 0, 1))\n", " ax.set_ylim(ylim)\n", " line, = ax.plot([], [], lw=2)\n", "\n", " # initialization function: plot the background of each frame\n", " def init():\n", " line.set_data([], [])\n", " return (line, )\n", "\n", " # animation function. This is called sequentially\n", " def animate(i):\n", " line.set_data(x, u[:,i])\n", " return (line,)\n", "\n", " anim = animation.FuncAnimation(fig, animate, init_func=init,\n", " frames=M, interval=20, blit=True)\n", " return anim" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "