I solve a differential equation with vector inputs
y '= f (t, y), y (t_0) = y_0
where y0 = y (x)
using the explicit Euler method, which states that
y_ (i + 1) = y_i + h * f (t_i, y_i)
where t is the time vector, h is the step size, and f is the right side of the differential equation.
The python code for the method is as follows:
for i in np.arange(0,n-1):
y[i+1,...] = y[i,...] + dt*myode(t[i],y[i,...])
The result is a matrix k, m y , where k is the size of t , and m is the size of y .
The vectors y and t are returned .
t, x y scipy.interpolate.RectBivariateSpline(t, x, y, kx=1, ky=1)
:
g = scipy.interpolate.RectBivariateSpline(t, x, y, kx=1, ky=1)
g
ti,xi ( g(p,q) )
, y_int
, y, , ti xi.
:
RectBivariateSpline __call__
x y:
__call__(x, y[, mth])
,
matplotlib plot_surface :
Axes3D.plot_surface(X, Y, Z, *args, **kwargs)
, X Y , numpy.meshgrid()
.
, , - , . ti,xi
, , , :
ax2.plot_surface(xi, ti, u, cmap=cm.coolwarm)
, , , , , ( ) . , .
, , :
import numpy as np
import matplotlib.pyplot as mplot
import matplotlib.cm as cm
import scipy.sparse as sp
import scipy.interpolate as interp
from mpl_toolkits.mplot3d import Axes3D
import pdb
def eev(myode,tspan,y0,dt):
tspan[1] = tspan[1] + dt
t = np.arange(tspan[0],tspan[1],dt,dtype=float)
n = t.size
m = y0.shape[0]
y = np.zeros((n,m),dtype=float)
y[0,:] = y0
for i in np.arange(0,n-1):
y[i+1,...] = y[i,...] + dt*myode(t[i],y[i,...])
return y,t
def a_matrix(n):
aa = sp.diags([1, -2, 1],[-1,0,1],(n,n))
return aa
def f(t,u):
dydt = np.divide(1,h**2)*A.dot(u)
return dydt
def rbd(t):
ul = np.zeros((t,1))
return ul
def main():
m = 20
x0 = 0
xn = 1
x = np.linspace(x0,xn,m+2)
global h
h = x[1]-x[0]
u0 = np.sin(np.pi*x)
global A
A = a_matrix(m)
t0 = 0
tend = 0.2
dt = 0.0001
tspan = [t0,tend]
r = np.divide(dt,h**2)
if r <= 0.5:
u,t = eev(f,tspan,u0[1:-1],dt)
else:
print('r = ',r)
print('r > 0.5. Explicit Euler method will not be stable.')
rb = rbd(t.size)
u = np.hstack((rb,u,rb))
fi = interp.RectBivariateSpline(t, x, u, kx=1, ky=1)
xi = np.linspace(x[0],x[-1],100)
ti = np.linspace(t0,tend,100)
u_int = fi(ti,xi)
xi,ti = np.meshgrid(xi,ti)
fig3 = mplot.figure(1)
ax3 = fig3.gca(projection='3d')
print('xi.shape =',xi.shape,'ti.shape =',ti.shape,'u_int.shape =',u_int.shape)
ax3.plot_surface(xi, ti, u_int, cmap=cm.coolwarm)
ax3.set_xlabel('xi')
ax3.set_ylabel('ti')
main()
mplot.show()