-
Notifications
You must be signed in to change notification settings - Fork 0
/
EX8_DiffEq.jl
113 lines (91 loc) · 2.38 KB
/
EX8_DiffEq.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#######################
# basic setup
#######################
# simulation time and interval
tmin = 0.0
tmax = 4.0
dt = 0.01
# domain and spacing
xmin = -π
xmax = π
dx = 0.02
c = π/2 # celerity
λ² = (c*dt/dx)^2
nx = convert(Int64, round((xmax-xmin)/dx) + 1)
nt = convert(Int64, round((tmax-tmin)/dt) + 1)
X = collect(Float64, LinRange(xmin, xmax, nx))
T = collect(Float64, LinRange(tmin, tmax, nt))
#######################
#######################
# general solution
#######################
# Gaussian distribution
σ = 1/sqrt(2pi)
U(x,t) = 0.5*(1/(sqrt(2pi)σ))*exp(-(x-c*t)^2/(2σ^2)) + 0.5*(1/(sqrt(2pi)σ))*exp(-(x+c*t)^2/(2σ^2))
u_solution = [ U(x,t) for x in X, t in T ]
#######################
#######################
# numerical simulation
#######################
# preallocate
u = zeros(nx, nt)
# initial condition
# Gaussian distribution
f(x) = 1/(sqrt(2pi)σ)*exp(-x^2/(2σ^2))
u_0 = map(f, X)
u[:,1] = u_0
# 2nd step
#u[:,2] = u[:,1]
for x in 2:nx-1
u[x,2] = 2(1-λ²)*u[x,1] -u[x,1] +λ²*(u[x-1,1]+u[x+1,1])
#u[x,2] = u[x,1] + λ²*(u[x+1,1] - 2u[x,1] + u[x-1,1])
end
# Neumann boundary condition
u[1,2] = u[2,2]
u[nx,2] = u[nx-1,2]
#
for t = 3:nt
for x in 2:nx-1
u[x,t] = 2(1-λ²)*u[x,t-1] -u[x,t-2] +λ²*(u[x-1,t-1]+u[x+1,t-1])
end
# Neumann boundary condition
u[1,t] = u[2,t]
u[nx,t] = u[nx-1,t]
end
#######################
#######################
# plot
#######################
# directory where figures are printed
figdir="./fig"
if !isdir(figdir); mkdir(figdir); end
using Printf
using Plots
pyplot()
# 軸目盛り
xt = -π:π/2:π
xtl = ["-π","-π/2","0","π/2","π"]
# profiles
d = 50
plt = plot3d(repeat(X,outer=(1,length(1:d:nt))),
permutedims(repeat(T[1:d:nt],outer=(1,nx))),
u[:,1:d:nt],
legend=false,
)
plt = plot3d!(plt, aspect_ratio=1.0, view_angle=(55,35))
plt = plot3d!(plt, xlabel="space", ylabel="time", guidefont=9, xtick=(xt, xtl))
savefig(joinpath(figdir,"WaveProfiles.svg"))
##
##
# animation
anim = @animate for t = 1:5:nt
@printf("%d, ",t)
Plots.plot(X, u[:,t], linestyle=:solid, lw=2.0,
ylim=(-0.5,1.0), xtick=(xt, xtl), tickfont=10,
title=@sprintf("%0.3f s", (t-1)*dt), legend=false)
end
gifname = joinpath(figdir,"WaveEq.gif")
if isfile(gifname); rm(gifname); end
gif(anim, gifname, fps=20) #save the animation
##
#######################