| 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) = 10*exp(-((x - 0.5)^2 + (y - 0.5)^2) / 0.02) |
| 8 |
|
| 9 |
and boundary conditions given by |
| 10 |
|
| 11 |
u(x, y) = 0 for x = 0 or x = 1 |
| 12 |
du/dn(x, y) = -sin(5*x) for y = 0 or y = 1 |
| 13 |
|
| 14 |
This demo is identical to the Poisson demo with the only difference that |
| 15 |
the source and flux term is expressed using SpatialCoordinates in the |
| 16 |
variational formulation. |
| 17 |
""" |
| 18 |
|
| 19 |
# Copyright (C) 2010 Kristian B. Oelgaard |
| 20 |
# |
| 21 |
# This file is part of DOLFIN. |
| 22 |
# |
| 23 |
# DOLFIN is free software: you can redistribute it and/or modify |
| 24 |
# it under the terms of the GNU Lesser General Public License as published by |
| 25 |
# the Free Software Foundation, either version 3 of the License, or |
| 26 |
# (at your option) any later version. |
| 27 |
# |
| 28 |
# DOLFIN is distributed in the hope that it will be useful, |
| 29 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 30 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 31 |
# GNU Lesser General Public License for more details. |
| 32 |
# |
| 33 |
# You should have received a copy of the GNU Lesser General Public License |
| 34 |
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>. |
| 35 |
# |
| 36 |
# Modified by Anders Logg 2011 |
| 37 |
# |
| 38 |
# First added: 2010-03-05 |
| 39 |
# Last changed: 2012-11-12 |
| 40 |
|
| 41 |
from dolfin import * |
| 42 |
import matplotlib.pyplot as plt |
| 43 |
|
| 44 |
|
| 45 |
# Form compiler options |
| 46 |
parameters["form_compiler"]["optimize"] = True |
| 47 |
parameters["form_compiler"]["cpp_optimize"] = True |
| 48 |
|
| 49 |
# Create mesh and define function space |
| 50 |
mesh = UnitSquareMesh(32, 32) |
| 51 |
V = FunctionSpace(mesh, "CG", 1) |
| 52 |
|
| 53 |
# Define Dirichlet boundary (x = 0 or x = 1) |
| 54 |
def boundary(x): |
| 55 |
return x[0] < DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS |
| 56 |
|
| 57 |
# Define boundary condition |
| 58 |
u0 = Constant(0.0) |
| 59 |
bc = DirichletBC(V, u0, boundary) |
| 60 |
|
| 61 |
# Define variational problem |
| 62 |
x = SpatialCoordinate(mesh) |
| 63 |
u = TrialFunction(V) |
| 64 |
v = TestFunction(V) |
| 65 |
d_x = x[0] - 0.5 |
| 66 |
d_y = x[1] - 0.5 |
| 67 |
f = 10.0*exp(-(d_x*d_x + d_y*d_y) / 0.02) |
| 68 |
g = -sin(5.0*x[0]) |
| 69 |
a = inner(grad(u), grad(v))*dx |
| 70 |
L = f*v*dx + g*v*ds |
| 71 |
|
| 72 |
# Compute solution |
| 73 |
u = Function(V) |
| 74 |
solve(a == L, u, bc) |
| 75 |
|
| 76 |
# Save solution in VTK format |
| 77 |
file = File("spatial-coordinates.pvd") |
| 78 |
file << u |
| 79 |
|
| 80 |
# Plot solution |
| 81 |
plot(u) |
| 82 |
plt.show() |