Debian Codegraph @

python/demo/documented/periodic/demo_periodic.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 homogeneous Dirichlet boundary conditions
6 # at y = 0, 1 and periodic boundary conditions at x = 0, 1.
7 #
8 # Original implementation: ../cpp/main.cpp by Anders Logg
9 #
10 # Copyright (C) 2007 Kristian B. Oelgaard
11 #
12 # This file is part of DOLFIN.
13 #
14 # DOLFIN is free software: you can redistribute it and/or modify
15 # it under the terms of the GNU Lesser General Public License as published by
16 # the Free Software Foundation, either version 3 of the License, or
17 # (at your option) any later version.
18 #
19 # DOLFIN is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU Lesser General Public License for more details.
23 #
24 # You should have received a copy of the GNU Lesser General Public License
25 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
26 #
27 # Modified by Anders Logg 2011
28 #
29 # First added: 2007-11-15
30 # Last changed: 2012-11-12
31 # Begin demo
32
33 import matplotlib.pyplot as plt
34 from dolfin import *
35
36 # Source term
37 class Source(UserExpression):
38 def eval(self, values, x):
39 dx = x[0] - 0.5
40 dy = x[1] - 0.5
41 values[0] = x[0]*sin(5.0*DOLFIN_PI*x[1]) \
42 + 1.0*exp(-(dx*dx + dy*dy)/0.02)
43
44 # Sub domain for Dirichlet boundary condition
45 class DirichletBoundary(SubDomain):
46 def inside(self, x, on_boundary):
47 return bool((x[1] < DOLFIN_EPS or x[1] > (1.0 - DOLFIN_EPS)) \
48 and on_boundary)
49
50 # Sub domain for Periodic boundary condition
51 class PeriodicBoundary(SubDomain):
52
53 # Left boundary is "target domain" G
54 def inside(self, x, on_boundary):
55 return bool(x[0] < DOLFIN_EPS and x[0] > -DOLFIN_EPS and on_boundary)
56
57 # Map right boundary (H) to left boundary (G)
58 def map(self, x, y):
59 y[0] = x[0] - 1.0
60 y[1] = x[1]
61
62 # Create mesh and finite element
63 mesh = UnitSquareMesh(32, 32)
64 V = FunctionSpace(mesh, "CG", 1, constrained_domain=PeriodicBoundary())
65
66 # Create Dirichlet boundary condition
67 u0 = Constant(0.0)
68 dbc = DirichletBoundary()
69 bc0 = DirichletBC(V, u0, dbc)
70
71 # Collect boundary conditions
72 bcs = [bc0]
73
74 # Define variational problem
75 u = TrialFunction(V)
76 v = TestFunction(V)
77 f = Source(degree=1)
78 a = dot(grad(u), grad(v))*dx
79 L = f*v*dx
80
81 # Compute solution
82 u = Function(V)
83 solve(a == L, u, bcs)
84
85 # Save solution to file
86 file = File("periodic.pvd")
87 file << u
88
89 # Plot solution
90 plot(u)
91 plt.show()