-
Notifications
You must be signed in to change notification settings - Fork 0
/
nSG_CNsolver_python.py
119 lines (83 loc) · 2.71 KB
/
nSG_CNsolver_python.py
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
114
115
116
117
118
119
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from scipy.optimize import newton_krylov
from numpy import cosh, zeros_like, mgrid, zeros
import matplotlib.pyplot as plt
from multiprocessing import Pool
# parameters
l = 1
def residual(P, u0, h, dt):
d2x = zeros_like(P) + 0.j
d2u = zeros_like(P) + 0.j
h2 = h*h
d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) /h2
d2x[0] = (P[1] - 2*P[0] + P[-1]) /h2
d2x[-1] = (P[0] - 2*P[-1] + P[-2]) /h2
d2u[1:-1] = (u0[2:] - 2*u0[1:-1] + u0[:-2]) /h2
d2u[0] = (u0[1] - 2*u0[0] + u0[-1]) /h2
d2u[-1] = (u0[0] - 2*u0[-1] + u0[-2]) /h2
return 2.j * (P - u0)/dt + d2u + d2x - l*(np.abs(u0)**2*u0 + np.abs(P)**2*P)
# solve
def u0(x):
return np.exp(1.j*x)
def ana_u(x, t):
return np.exp(1.j*x + 1.j*(-l - 1)*t)
def nSG_solve(N, xa, xe, ta, te, dt, func_u0):
h = (xe - xa) / (N+1)
x = np.arange(xa+h, xe+h/2, h)
u0 = func_u0(x)
print l*dt/2.0
t = [ta]
while (ta < te):
u0 = newton_krylov(lambda a: residual(a, u0, h, dt), u0)
ta += dt
t.append(ta)
return u0, x, np.array(t)
def test_plot():
u, x, t = nSG_solve(15, -np.pi, np.pi, 0, 1, 0.01, u0)
plt.plot(x, np.abs(u)**2 )
plt.ylim(0.9, 1.1)
plt.plot(x, np.abs( ana_u(x, t[-1]) )**2 )
plt.show()
def nSG_l1_space_error(n):
u, x, t = nSG_solve(n, -np.pi, np.pi, 0, 1, 0.01, u0)
return np.sum(np.abs( u - ana_u(x, t[-1]) ))
def nSG_l1_time_error(t):
u, x, T = nSG_solve(400, -np.pi, np.pi, 0, 1, t, u0)
return np.sum(np.abs( u - ana_u(x, T[-1]) ))
def nSG_space_conv_plot():
N = [50, 100, 150, 200, 250, 300, 350, 400]
p = Pool()
err = p.map(nSG_l1_space_error, N)
print err
h = 2*np.pi/(np.array(N)+1)
plt.loglog(h, h*np.array(err), linewidth=4.0, label="Err")
plt.plot(h, h**2, '--', linewidth=4.0, label=r'$h^2$')
plt.ylabel(r'$e(h)$', fontsize=30)
plt.xlabel(r'$h$', fontsize=30)
plt.xlim(10**-2, 0.15)
plt.tick_params(labelsize=25)
plt.legend(loc='best', fontsize=40)
plt.show()
def nSG_time_conv_plot():
T = np.array([0.2, 0.1, 0.05, 0.01, 0.005, 0.001, 0.0005])
p = Pool()
err = p.map(nSG_l1_time_error, T)
print err
plt.loglog(T, T*np.array(err), linewidth=4.0, label="Err")
plt.plot(T, T**2, '--', linewidth=4.0, label=r'$dt^2$')
plt.ylabel(r'$e(dt)$', fontsize=30)
plt.xlabel(r'$dt$', fontsize=30)
plt.tick_params(labelsize=25)
plt.legend(loc='best', fontsize=40)
plt.show()
def main(args):
#test_plot()
nSG_space_conv_plot()
nSG_time_conv_plot()
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))