Debian Codegraph @

python/demo/undocumented/adaptive-poisson/demo_adaptive-poisson.py

raw
1 """This demo program solves Poisson's equation
2
3 - div grad u(x, y) = f(x, y)
4
5 on the unit square with source f given by
6
7 f(x, y) = exp(-100(x^2 + y^2))
8
9 and homogeneous Dirichlet boundary conditions.
10
11 Note that we use a simplified error indicator, ignoring
12 edge (jump) terms and the size of the interpolation constant.
13 """
14
15 # Copyright (C) 2008 Rolv Erlend Bredesen
16 #
17 # This file is part of DOLFIN.
18 #
19 # DOLFIN is free software: you can redistribute it and/or modify
20 # it under the terms of the GNU Lesser General Public License as published by
21 # the Free Software Foundation, either version 3 of the License, or
22 # (at your option) any later version.
23 #
24 # DOLFIN is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU Lesser General Public License for more details.
28 #
29 # You should have received a copy of the GNU Lesser General Public License
30 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
31 #
32 # Modified by Anders Logg 2008-2011
33
34
35 from dolfin import *
36 from numpy import array, sqrt
37 from math import pow
38
39 TOL = 5e-4 # Error tolerance
40 REFINE_RATIO = 0.50 # Refine 50 % of the cells in each iteration
41 MAX_ITER = 20 # Maximal number of iterations
42
43 # Create initial mesh
44 mesh = UnitSquareMesh(4, 4)
45 source_str = "exp(-100.0*(pow(x[0], 2) + pow(x[1], 2)))"
46 source = eval("lambda x: " + source_str)
47
48 # Adaptive algorithm
49 for level in range(MAX_ITER):
50
51 # Define variational problem
52 V = FunctionSpace(mesh, "CG", 1)
53 v = TestFunction(V)
54 u = TrialFunction(V)
55 f = Expression(source_str, degree=2)
56 a = dot(grad(v), grad(u))*dx
57 L = v*f*dx
58
59 # Define boundary condition
60 u0 = Constant(0.0)
61 bc = DirichletBC(V, u0, DomainBoundary())
62
63 # Compute solution
64 u = Function(V)
65 solve(a == L, u, bc)
66
67 # Compute error indicators
68 h = array([c.h() for c in cells(mesh)])
69 K = array([c.volume() for c in cells(mesh)])
70 R = array([abs(source([c.midpoint().x(), c.midpoint().y()])) for c in cells(mesh)])
71 gamma = h*R*sqrt(K)
72
73 # Compute error estimate
74 E = sum([g*g for g in gamma])
75 E = sqrt(MPI.sum(mesh.mpi_comm(), E))
76 print("Level %d: E = %g (TOL = %g)" % (level, E, TOL))
77
78 # Check convergence
79 if E < TOL:
80 info("Success, solution converged after %d iterations" % level)
81 break
82
83 # Mark cells for refinement
84 cell_markers = MeshFunction("bool", mesh, mesh.topology().dim())
85 gamma_0 = sorted(gamma, reverse=True)[int(len(gamma)*REFINE_RATIO)]
86 gamma_0 = MPI.max(mesh.mpi_comm(), gamma_0)
87 for c in cells(mesh):
88 cell_markers[c] = gamma[c.index()] > gamma_0
89
90 # Refine mesh
91 mesh = refine(mesh, cell_markers)
92
93 # Plot mesh
94 plot(mesh)