In [1]:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
In [2]:
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave equations, such has the Korteweg–de Vries equation, which has the following analytical solution:
$$ \phi(x,t) = \frac{1}{2} c \mathrm{sech}^2 \left[ \frac{\sqrt{c}}{2} \left(x - ct - a \right) \right] $$The constant c is the velocity and the constant a is the initial location of the soliton.
Define soliton(x, t, c, a) function that computes the value of the soliton wave for the given arguments. Your function should work when the postion x or t are NumPy arrays, in which case it should return a NumPy array itself.
In [5]:
import math
def soliton(x, t, c, a):
"""Return phi(x, t) for a soliton wave with constants c and a."""
# YOUR CODE HERE
phi=(0.5)*c/(np.cosh(((x-c*t-a)*np.sqrt(c)/2)))**2
return phi
In [6]:
assert np.allclose(soliton(np.array([0]),0.0,1.0,0.0), np.array([0.5]))
To create an animation of a soliton propagating in time, we are going to precompute the soliton data and store it in a 2d array. To set this up, we create the following variables and arrays:
In [7]:
tmin = 0.0
tmax = 10.0
tpoints = 200 #jack changed from 100 to 200
t = np.linspace(tmin, tmax, tpoints)
xmin = 0.0
xmax = 10.0
xpoints = 200
x = np.linspace(xmin, xmax, xpoints)
c = 1.0
a = 0.0
Compute a 2d NumPy array called phi:
float.(xpoints, tpoints).phi[i,j] should contain the value $\phi(x[i],t[j])$.
In [8]:
# YOUR CODE HERE
phi=np.ones((xpoints,tpoints))
w=0
z=0
while w < xpoints:
while z < tpoints:
phi[w,z]=soliton(w,z,c,a)
z=z+1
z=0
w=w+1
# phi=np.empty((xpoints,tpoints))
# for i in range(xpoints):
# phi[i,:]=soliton(x[i],t,c,a)
#
# remember the x[i] thing
# how dr granger did it
In [9]:
assert phi.shape==(xpoints, tpoints)
assert phi.ndim==2
assert phi.dtype==np.dtype(float)
assert phi[10,10]==soliton(x[10],t[10],c,a)
Write a plot_soliton_data(i) function that plots the soliton wave $\phi(x, t[i])$. Customize your plot to make it effective and beautiful.
In [10]:
x=0
def plot_soliton_data(i=0):
"""Plot the soliton data at t[i] versus x."""
plt.plot(phi[:,i])
plt.title("Plot of Soliton Wave")
plt.xlabel("Time Axis of Soliton Wave")
plt.ylabel("Value of Soliton Wave Function")
plt.tick_params(direction='out')
plt.yscale("log")
In [11]:
plot_soliton_data(0)
In [12]:
assert True # leave this for grading the plot_soliton_data function
Use interact to animate the plot_soliton_data function versus time.
In [205]:
# YOUR CODE HERE
interact(plot_soliton_data,i=(0,199,10));
In [ ]:
assert True # leave this for grading the interact with plot_soliton_data cell