Debian Codegraph @

python/test/unit/ts/test_sundials.py

raw
1 #!/usr/bin/python3
2
3 import numpy
4 from dolfin import *
5 from dolfin_utils.test import skip_if_not_SUNDIALS
6
7
8 @skip_if_not_SUNDIALS
9 def test_sundials_adams():
10
11 class MyCVode(CVode):
12
13 def derivs(self, t, u, udot):
14 udot[:] = -u[:]
15
16 def jacobian(self, v, Jv, t, y, fy):
17 Jv[:] = v[:]
18 return 0
19
20 def psolve(self, t, u, udot, r, z, gamma, x, y):
21 z[:] = r[:]
22 return 0
23
24 phi = Vector(MPI.comm_world, 10)
25 phi[:] = 1.0
26
27 cv = MyCVode(CVode.LMM.CV_ADAMS, CVode.ITER.CV_FUNCTIONAL)
28 cv.init(phi, 1e-7, 1e-7)
29
30 nstep = 200
31 dt = 0.01
32 for i in range(nstep):
33 t = cv.step(dt)
34 assert (exp(-t) - phi[0]) < 1e-6
35
36 @skip_if_not_SUNDIALS
37 def test_sundials_newton():
38
39 class MyCVode(CVode):
40
41 def derivs(self, t, u, udot):
42 udot[:] = -u[:]
43
44 def jacobian(self, v, Jv, t, y, fy):
45 Jv[:] = v[:]
46 return 0
47
48 def psolve(self, t, u, udot, r, z, gamma, x, y):
49 z[:] = r[:]
50 return 0
51
52 phi = Vector(MPI.comm_world, 10)
53 phi[:] = 1.0
54
55 cv = MyCVode(CVode.LMM.CV_BDF, CVode.ITER.CV_NEWTON)
56 cv.init(phi, 1e-7, 1e-7)
57
58 nstep = 200
59 dt = 0.01
60 for i in range(nstep):
61 t = cv.step(dt)
62 assert (exp(-t) - phi[0]) < 1e-6
63
64 @skip_if_not_SUNDIALS
65 def test_sundials_diffusion_1d():
66 # Finite difference test
67 mesh = UnitIntervalMesh(MPI.comm_world, 100)
68 Q = FunctionSpace(mesh, "CG", 1)
69 F = Function(Q)
70 b = 2.0
71 F.interpolate(Expression("exp(-b*pow(x[0] - 0.5, 2))", b=b, degree=1))
72 phi = F.vector()
73
74 class tmp_test(CVode):
75 def derivs(self, t, phi, phidot):
76 p = phi[:]
77 pd = numpy.zeros_like(p)
78 for i in range(1, len(p)-1):
79 pd[i] = p[i-1] - 2*p[i] + p[i+1]
80 phidot[:] = pd
81
82 def jacobian(self, v, Jv, t, y, fy):
83 Jv[:] = v[:]
84 return 0
85 def psolve(self, t, u, udot, r, z, gamma, x, y):
86 z[:] = r[:]
87 return 0
88
89 cv = tmp_test(CVode.LMM.CV_BDF, CVode.ITER.CV_NEWTON)
90 cv.init(phi, 1e-7, 1e-7)
91
92 t0 = 1.0/(4.0*b)
93 cv.set_time(t0)
94
95 nstep = 200
96 dt = 0.25
97 for i in range(nstep):
98 t = cv.step(dt)
99 print(t, phi.max(), phi.sum(), sqrt(t)*phi.max())