Debian Codegraph @

python/test/unit/fem/test_dirichlet_bc.py

raw
1 """Unit tests for Dirichlet boundary conditions"""
2
3 # Copyright (C) 2011-2017 Garth N. Wells
4 #
5 # This file is part of DOLFIN.
6 #
7 # DOLFIN is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Lesser General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # DOLFIN is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public License
18 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
19 #
20 # Modified by Kent-Andre Mardal 2011
21 # Modified by Anders Logg 2011
22 # Modified by Martin Alnaes 2012
23
24 import os
25
26 import pytest
27 import numpy
28
29 from dolfin import *
30 from dolfin_utils.test import skip_in_parallel, datadir
31
32
33 def test_instantiation():
34 """ A rudimentary test for instantiation"""
35 # FIXME: Needs to be expanded
36 mesh = UnitCubeMesh(8, 8, 8)
37 V = FunctionSpace(mesh, "CG", 1)
38
39 bc0 = DirichletBC(V, 1, "x[0]<0")
40 bc1 = DirichletBC(bc0)
41 assert bc0.function_space() == bc1.function_space()
42
43
44 def test_director_lifetime():
45 """Test for any problems with objects with directors going out
46 of scope"""
47
48 class Boundary(SubDomain):
49 def inside(self, x, on_boundary): return on_boundary
50
51 class BoundaryFunction(UserExpression):
52 def eval(self, values, x): values[0] = 1.0
53
54 mesh = UnitSquareMesh(8, 8)
55 V = FunctionSpace(mesh, "Lagrange", 1)
56 v, u = TestFunction(V), TrialFunction(V)
57
58 A0 = assemble(v*u*dx)
59 bc0 = DirichletBC(V, BoundaryFunction(degree=1), Boundary())
60 bc0.apply(A0)
61
62 bc1 = DirichletBC(V, Expression("1.0", degree=0), CompiledSubDomain("on_boundary"))
63 A1 = assemble(v*u*dx)
64 bc1.apply(A1)
65
66 assert round(A1.norm("frobenius") - A0.norm("frobenius"), 7) == 0
67
68
69 def test_get_values():
70 mesh = UnitSquareMesh(8, 8)
71 dofs = numpy.zeros(3, dtype="I")
72
73 def upper(x, on_boundary):
74 return x[1] > 0.5 + DOLFIN_EPS
75
76 V = FunctionSpace(mesh, "CG", 1)
77 bc = DirichletBC(V, 0.0, upper)
78 bc_values = bc.get_boundary_values()
79
80
81 def test_user_meshfunction_domains():
82 mesh0 = UnitSquareMesh(12, 12)
83 mesh1 = UnitSquareMesh(12, 12)
84 V = FunctionSpace(mesh0, "CG", 1)
85
86 DirichletBC(V, Constant(0.0), MeshFunction("size_t", mesh0, 1), 0)
87 DirichletBC(V, Constant(0.0), MeshFunction("size_t", mesh0, mesh0.topology().dim()-1), 0)
88 with pytest.raises(RuntimeError):
89 DirichletBC(V, 0.0, MeshFunction("size_t", mesh0, mesh0.topology().dim()), 0)
90 DirichletBC(V, 0.0, MeshFunction("size_t", mesh0, 0), 0)
91 DirichletBC(V, 0.0, MeshFunction("size_t", mesh1, mesh1.topology().dim()-1), 0)
92
93
94 @skip_in_parallel
95 @pytest.mark.parametrize("degree", [1, 2])
96 @pytest.mark.parametrize("element_type",
97 ["RT", "DRT", "BDM", "N1curl", "N2curl"])
98 def test_bc_for_piola_on_manifolds(element_type, degree):
99 """Testing DirichletBC for piolas over standard domains vs manifolds.
100
101 """
102 n = 4
103 side = CompiledSubDomain("near(x[2], 0.0)")
104 mesh = SubMesh(BoundaryMesh(UnitCubeMesh(n, n, n), "exterior"), side)
105 mesh.init_cell_orientations(Expression(("0.0", "0.0", "1.0"), degree=0))
106 square = UnitSquareMesh(n, n)
107
108 V = FunctionSpace(mesh, element_type, degree)
109 bc = DirichletBC(V, (1.0, 0.0, 0.0), "on_boundary")
110 u = Function(V)
111 bc.apply(u.vector())
112 b0 = assemble(inner(u, u)*dx)
113
114 V = FunctionSpace(square, element_type, degree)
115 bc = DirichletBC(V, (1.0, 0.0), "on_boundary")
116 u = Function(V)
117 bc.apply(u.vector())
118 b1 = assemble(inner(u, u)*dx)
119 assert round(b0 - b1, 7) == 0
120
121
122 def test_zero():
123 mesh = UnitSquareMesh(4, 4)
124 V = FunctionSpace(mesh, "CG", 1)
125 u1 = interpolate(Constant(1.0), V)
126
127 bc = DirichletBC(V, 0, "on_boundary")
128
129 # Create arbitrary matrix of size V.dim()
130 #
131 # Note: Identity matrix would suffice, but there doesn't seem
132 # an easy way to construct it in dolfin
133
134 v, u = TestFunction(V), TrialFunction(V)
135 A0 = assemble(u*v*dx)
136
137 # Zero rows at boundary dofs
138 bc.zero(A0)
139
140 u1_zero = Function(V)
141 u1_zero.vector()[:] = A0 * u1.vector()
142
143 boundaryIntegral = assemble(u1_zero * ds)
144 assert near(boundaryIntegral, 0.0)
145
146
147 @skip_in_parallel
148 def test_zero_columns_offdiag():
149 """Test zero_columns applied to offdiagonal block"""
150 mesh = UnitSquareMesh(20, 20)
151 V = VectorFunctionSpace(mesh, "P", 2)
152 Q = FunctionSpace(mesh, "P", 1)
153 u = TrialFunction(V)
154 q = TestFunction(Q)
155 a = inner(div(u), q)*dx
156 L = inner(Constant(0), q)*dx
157 A = assemble(a)
158 b = assemble(L)
159
160 bc = DirichletBC(V, Constant((-32.23333, 43243.1)), 'on_boundary')
161
162 # Compute residual with x satisfying bc before zero_columns
163 u = Function(V)
164 x = u.vector()
165 bc.apply(x)
166 r0 = A*x - b
167
168 bc.zero_columns(A, b)
169
170 # Test that A gets zero columns
171 bc_dict = bc.get_boundary_values()
172 for i in range(*A.local_range(0)):
173 cols, vals = A.getrow(i)
174 for j, v in zip(cols, vals):
175 if j in bc_dict:
176 assert v == 0.0
177
178 # Compute residual with x satisfying bc after zero_columns
179 # and check that it is preserved
180 r1 = A*x - b
181 assert numpy.isclose((r1-r0).norm('linf'), 0.0)
182
183
184 @skip_in_parallel
185 def test_zero_columns_square():
186 """Test zero_columns applied to square matrix"""
187 mesh = UnitSquareMesh(20, 20)
188 V = FunctionSpace(mesh, "P", 1)
189 u, v = TrialFunction(V), TestFunction(V)
190 a = inner(grad(u), grad(v))*dx
191 L = Constant(0)*v*dx
192 A = assemble(a)
193 b = assemble(L)
194 u = Function(V)
195 x = u.vector()
196
197 bc = DirichletBC(V, 666.0, 'on_boundary')
198 bc.zero_columns(A, b, 42.0)
199
200 # Check that A gets zeros in bc rows and bc columns and 42 on
201 # diagonal
202 bc_dict = bc.get_boundary_values()
203 for i in range(*A.local_range(0)):
204 cols, vals = A.getrow(i)
205 for j, v in zip(cols, vals):
206 if i in bc_dict or j in bc_dict:
207 if i == j:
208 assert numpy.isclose(v, 42.0)
209 else:
210 assert v == 0.0
211
212 # Check that solution of linear system works
213 solve(A, x, b)
214 assert numpy.isclose((b-A*x).norm('linf'), 0.0)
215 x1 = x.copy()
216 bc.apply(x1)
217 x1 -= x
218 assert numpy.isclose(x1.norm('linf'), 0.0)
219
220
221 def test_homogenize_consistency():
222 mesh = UnitIntervalMesh(10)
223 V = FunctionSpace(mesh, "CG", 1)
224
225 for method in ['topological', 'geometric', 'pointwise']:
226 bc = DirichletBC(V, Constant(0), "on_boundary", method=method)
227 bc_new = DirichletBC(bc)
228 bc_new.homogenize()
229 assert bc_new.method() == bc.method()
230
231
232 def test_nocaching_values():
233 """There might be caching of dof indices in DirichletBC.
234 But caching of values is _not_ allowed."""
235 mesh = UnitSquareMesh(4, 4)
236 V = FunctionSpace(mesh, "P", 1)
237 u = Function(V)
238 x = u.vector()
239
240 for method in ["topological", "geometric", "pointwise"]:
241 bc = DirichletBC(V, 0.0, lambda x, b: True, method=method)
242
243 x.zero()
244 bc.set_value(Constant(1.0))
245 bc.apply(x)
246 assert numpy.allclose(x.get_local(), 1.0)
247
248 x.zero()
249 bc.set_value(Constant(2.0))
250 bc.apply(x)
251 assert numpy.allclose(x.get_local(), 2.0)
252
253
254 def test_get_value():
255 mesh = UnitSquareMesh(4, 4)
256
257 vspace_dim = 4
258 V = VectorFunctionSpace(mesh, "CG", 1, dim=vspace_dim)
259
260 boundary_constant = Constant((0.0, 1.0, 2.0, 3.0))
261 bc = DirichletBC(V, boundary_constant, "on_boundary")
262
263 assert bc.value() == boundary_constant.cpp_object()
264 for j in range(vspace_dim):
265 assert bc.value().values()[j] == boundary_constant.values()[j]