Debian Codegraph @

python/test/unit/fem/test_system_assembler.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """Unit tests for class SystemAssembler"""
2
3 # Copyright (C) 2011-2013 Garth N. Wells, 2013 Jan Blechta
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 Marie E. Rognes 2011
21 # Modified by Anders Logg 2011
22
23 import pytest
24 import numpy
25 import os
26 from dolfin import *
27 from dolfin_utils.test import *
28
29
30 def test_cell_assembly():
31
32 mesh = UnitCubeMesh(4, 4, 4)
33 V = VectorFunctionSpace(mesh, "DG", 1)
34
35 v = TestFunction(V)
36 u = TrialFunction(V)
37 f = Constant((10, 20, 30))
38
39 def epsilon(v):
40 return 0.5*(grad(v) + grad(v).T)
41
42 a = inner(epsilon(v), epsilon(u))*dx
43 L = inner(v, f)*dx
44
45 A_frobenius_norm = 4.3969686527582512
46 b_l2_norm = 0.95470326978246278
47
48 # Assemble system
49 A, b = assemble_system(a, L)
50 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
51 assert round(b.norm("l2") - b_l2_norm, 10) == 0
52
53 # SystemAssembler construction
54 assembler = SystemAssembler(a, L)
55
56 # Test SystemAssembler for LHS and RHS
57 A = Matrix()
58 b = Vector()
59 assembler.assemble(A, b)
60 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
61 assert round(b.norm("l2") - b_l2_norm, 10) == 0
62
63 A = Matrix()
64 b = Vector()
65
66 assembler.assemble(A)
67 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
68
69 assembler.assemble(b)
70 assert round(b.norm("l2") - b_l2_norm, 10) == 0
71
72
73 def test_cell_assembly_bc():
74
75 mesh = UnitCubeMesh(4, 4, 4)
76 V = FunctionSpace(mesh, "Lagrange", 1)
77 bc = DirichletBC(V, 1.0, "on_boundary")
78
79 u, v = TrialFunction(V), TestFunction(V)
80 f = Constant(10)
81
82 a = inner(grad(u), grad(v))*dx
83 L = inner(f, v)*dx
84
85 A_frobenius_norm = 96.847818767384
86 b_l2_norm = 96.564760289080
87
88 # Assemble system
89 A, b = assemble_system(a, L, bc)
90 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
91 assert round(b.norm("l2") - b_l2_norm, 10) == 0
92
93 # Create assembler
94 assembler = SystemAssembler(a, L, bc)
95
96 # Test for assembling A and b via assembler object
97 A, b = Matrix(), Vector()
98 assembler.assemble(A, b)
99 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
100 assert round(b.norm("l2") - b_l2_norm, 10) == 0
101
102 # Assemble LHS only (first time)
103 A = Matrix()
104 assembler.assemble(A)
105 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
106
107 # Assemble LHS only (second time)
108 assembler.assemble(A)
109 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
110
111 # Assemble RHS only (first time)
112 b = Vector()
113 assembler.assemble(b)
114 assert round(b.norm("l2") - b_l2_norm, 10) == 0
115
116 # Assemble RHS only (second time time)
117 assembler.assemble(b)
118 assert round(b.norm("l2") - b_l2_norm, 10) == 0
119
120
121 def test_facet_assembly():
122
123 def test(mesh):
124 V = FunctionSpace(mesh, "DG", 1)
125
126 # Define test and trial functions
127 v = TestFunction(V)
128 u = TrialFunction(V)
129
130 # Define normal component, mesh size and right-hand side
131 n = FacetNormal(mesh)
132 h = 2*Circumradius(mesh)
133 h_avg = (h('+') + h('-'))/2
134 f = Expression("500.0*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)", degree=1)
135
136 # Define bilinear form
137 a = dot(grad(v), grad(u))*dx \
138 - dot(avg(grad(v)), jump(u, n))*dS \
139 - dot(jump(v, n), avg(grad(u)))*dS \
140 + 4.0/h_avg*dot(jump(v, n), jump(u, n))*dS \
141 - dot(grad(v), u*n)*ds \
142 - dot(v*n, grad(u))*ds \
143 + 8.0/h*v*u*ds
144
145 # Define linear form
146 L = v*f*dx
147
148 # Reference values
149 A_frobenius_norm = 157.867392938645
150 b_l2_norm = 1.48087142738768
151
152 # Assemble system
153 A, b = assemble_system(a, L)
154 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
155 assert round(b.norm("l2") - b_l2_norm, 10) == 0
156
157 # Test SystemAssembler
158 assembler = SystemAssembler(a, L)
159 A = Matrix()
160 b = Vector()
161
162 assembler.assemble(A, b)
163 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
164 assert round(b.norm("l2") - b_l2_norm, 10) == 0
165
166 A = Matrix()
167 b = Vector()
168 assembler.assemble(A)
169 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
170 assembler.assemble(b)
171 assert round(b.norm("l2") - b_l2_norm, 10) == 0
172
173 parameters["ghost_mode"] = "shared_facet"
174 mesh = UnitSquareMesh(24, 24)
175 test(mesh)
176
177 parameters["ghost_mode"] = "shared_vertex"
178 mesh = UnitSquareMesh(24, 24)
179 test(mesh)
180
181 parameters["ghost_mode"] = "none"
182
183
184 def test_vertex_assembly():
185
186 # Create mesh and define function space
187 mesh = UnitSquareMesh(32, 32)
188 V = FunctionSpace(mesh, "Lagrange", 1)
189
190 # Define Dirichlet boundary (x = 0 or x = 1)
191 def boundary(x):
192 return x[0] < DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS
193
194 def center_func(x):
195 return 0.25 <= x[0] and x[0] <= 0.75 and near(x[1], 0.5)
196
197 # Define domain for point integral
198 center_domain = MeshFunction("size_t", mesh, 0, 0)
199 center = AutoSubDomain(center_func)
200 center.mark(center_domain, 1)
201 dPP = dP(subdomain_data=center_domain)
202
203 # Define variational problem
204 u = TrialFunction(V)
205 v = TestFunction(V)
206 f = Constant(.4)
207 a = inner(grad(u), grad(v))*dx
208 L = f*v*dPP(1)
209
210 with pytest.raises(RuntimeError):
211 A, b = assemble_system(a, L)
212
213
214 @pytest.mark.parametrize('mesh_factory', [(UnitSquareMesh, (20, 20)),
215 (UnitSquareMesh.create, (20, 20, CellType.Type.quadrilateral))])
216 def test_incremental_assembly(mesh_factory):
217
218 for f in [Constant(0.0), Constant(1e4)]:
219
220 # Laplace/Poisson problem
221 func, args = mesh_factory
222 mesh = func(*args)
223 V = FunctionSpace(mesh, 'CG', 1)
224 u, v = TrialFunction(V), TestFunction(V)
225 a, L = inner(grad(u), grad(v))*dx, f*v*dx
226 uD = Expression("42.0*(2.0*x[0]-1.0)", degree=1)
227 bc = DirichletBC(V, uD, "on_boundary")
228
229 # Initialize initial guess by some number
230 u = Function(V)
231 x = u.vector()
232 x[:] = 30.0
233
234 # Assemble incremental system
235 assembler = SystemAssembler(a, -L, bc)
236 A, b = Matrix(), Vector()
237 assembler.assemble(A, b, x)
238
239 # Solve for (negative) increment
240 Dx = Vector(x)
241 Dx.zero()
242 solve(A, Dx, b)
243
244 # Update solution
245 x[:] -= Dx[:]
246
247 # Check solution
248 u_true = Function(V)
249 solve(a == L, u_true, bc)
250 u.vector()[:] -= u_true.vector()[:]
251 error = norm(u.vector(), 'linf')
252 assert round(error - 0.0, 7) == 0
253
254
255 @skip_in_parallel
256 @pytest.mark.parametrize('mesh_factory', [
257 (UnitSquareMesh.create, (24, 24, CellType.Type.triangle)),
258 (UnitSquareMesh.create, (24, 24, CellType.Type.quadrilateral)),
259 ])
260 def test_domains(mesh_factory):
261
262 class RightSubDomain(SubDomain):
263 def inside(self, x, on_boundary):
264 return x[0] > 0.5
265
266 func, args = mesh_factory
267 mesh = func(*args)
268
269 sub_domains = MeshFunction("size_t", mesh, mesh.topology().dim())
270 sub_domains.set_all(1)
271 right = RightSubDomain()
272 right.mark(sub_domains, 2)
273
274 V = FunctionSpace(mesh, "DG", 1)
275 v = TestFunction(V)
276 u = TrialFunction(V)
277
278 # the numerical answer (initialized to some number)
279 x = Function(V)
280 x.vector()[:] = 30.0
281
282 dx = Measure("dx", subdomain_data=sub_domains)
283 # the forms
284 a = v*u*dx(1) + 2*v*u*dx(2)
285 L = v*Constant(1.0)*dx(1) + v*Constant(2.0)*dx(2)
286 # test cell-wise assembly
287 assembler = SystemAssembler(a, L)
288
289 A0 = Matrix()
290 b = Vector()
291 assembler.assemble(A0, b)
292
293 solve(A0, x.vector(), b)
294
295 # check solution
296 x.vector()[:] -= 1.0
297 error = norm(x.vector(), 'linf')
298 assert round(error - 0.0, 7) == 0
299
300 # now give the form some internal facet integrals
301 a += v('+')*u('+')*Constant(0.0)('+')*dS
302 assembler = SystemAssembler(a, L)
303 A1 = Matrix()
304 # test facet-wise assembly
305 assembler.assemble(A1, b)
306
307 # reset solution vector to some number
308 x.vector()[:] = 30.0
309 solve(A1, x.vector(), b)
310
311 # check solution
312 x.vector()[:] -= 1.0
313 error = norm(x.vector(), 'linf')
314 assert round(error - 0.0, 7) == 0
315
316
317 @skip_in_parallel
318 def test_facet_assembly_cellwise_insertion(filedir):
319
320 def run_test(mesh):
321 c_f = FunctionSpace(mesh, "DG", 0)
322 v = Constant((-1.0,))
323 dt = Constant(1.0)
324
325 c_t = TestFunction(c_f)
326 c_a = TrialFunction(c_f)
327
328 n = FacetNormal(mesh)
329 vn = dot(v, n)
330 vout = 0.5*(vn + abs(vn))
331
332 # forms:
333 # a has no facet integrals
334 a = c_t*c_a*dx
335 # L has facet integrals so we end up in facet wise assembly
336 L = c_t('+')*vout('+')*dt('+')*dS + c_t('-')*vout('-')*dt('-')*dS \
337 + c_t*vout*dt*ds
338 # but have to use cell wise insertion because the sparsity
339 # pattern doesn't support the macro element
340
341 A = Matrix()
342 b = Vector()
343
344 assembler = SystemAssembler(a, L)
345 assembler.assemble(A, b)
346
347 A_frobenius_norm = ((0.1**2)*10)**0.5
348 A_linf_norm = 0.1
349 b_l2_norm = 10.0**0.5
350 b_linf_norm = 1.0
351
352 assert round(A.norm("frobenius") - A_frobenius_norm, 10) == 0
353 assert round(b.norm("l2") - b_l2_norm, 10) == 0
354 assert round(A.norm("linf") - A_linf_norm, 10) == 0
355 assert round(b.norm("linf") - b_linf_norm, 10) == 0
356
357 x = Function(c_f)
358 x.vector()[:] = 30.0
359
360 solver_worked = True
361 try:
362 solve(A, x.vector(), b)
363 except:
364 solver_worked = False
365 assert solver_worked
366
367 x.vector()[:] -= 10.0
368 error = norm(x.vector(), 'linf')
369 assert round(error - 0.0, 7) == 0
370
371 # Run tests
372 run_test(UnitIntervalMesh(10))
373 run_test(Mesh(os.path.join(filedir, "gmsh_unit_interval.xml")))
374
375
376 @pytest.mark.parametrize('mesh_factory', [(UnitSquareMesh, (24, 24)),
377 (UnitSquareMesh.create, (24, 24, CellType.Type.quadrilateral))])
378 def test_non_square_assembly(mesh_factory):
379 func, args = mesh_factory
380 mesh = func(*args)
381
382 def bound(x):
383 return (x[0] == 0)
384
385 # Assemble four blocks in VxV, VxQ, QxV and VxV
386 P2 = VectorElement("Lagrange", mesh.ufl_cell(), 2)
387 P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
388 Q = FunctionSpace(mesh, P1)
389 V = FunctionSpace(mesh, P2)
390 u = TrialFunction(V)
391 v = TestFunction(V)
392 p = TrialFunction(Q)
393 q = TestFunction(Q)
394
395 a00 = inner(grad(u), grad(v))*dx
396 a01 = dot(grad(p), v)*dx
397 a10 = q*div(u)*dx
398 a11 = p*q*dx
399 L0 = dot(Constant((0.0, 0.0)), v)*dx
400 L1 = Constant(0.0)*q*dx
401 bc = DirichletBC(V.sub(0), Constant(1.0), bound)
402
403 assembler = SystemAssembler([a00, a01, a10, a11], [L0, L1], [[bc], []])
404 A00 = Matrix()
405 A01 = Matrix()
406 A10 = Matrix()
407 A11 = Matrix()
408 b0 = Vector()
409 b1 = Vector()
410 assembler.assemble([A00, A01, A10, A11], [b0, b1])
411 Anorm1 = A00.norm("frobenius")**2
412 Anorm1 += A01.norm("frobenius")**2
413 Anorm1 += A10.norm("frobenius")**2
414 Anorm1 += A11.norm("frobenius")**2
415 bnorm1 = b0.norm("l2")**2 + b1.norm("l2")**2
416
417 # Same problem as a MixedFunctionSpace
418 W = FunctionSpace(mesh, P2*P1)
419 u, p = TrialFunctions(W)
420 v, q = TestFunctions(W)
421
422 a = inner(grad(u), grad(v))*dx + dot(grad(p), v)*dx + q*div(u)*dx + p*q*dx
423 L = dot(Constant((0.0, 0.0)), v)*dx + Constant(0.0)*q*dx
424 bc = DirichletBC(W.sub(0).sub(0), Constant(1.0), bound)
425 assembler = SystemAssembler(a, L, bc)
426 A = Matrix()
427 b = Vector()
428 assembler.assemble(A, b)
429
430 bnorm2 = b.norm("l2")**2
431 Anorm2 = A.norm("frobenius")**2
432 assert round(1.0 - bnorm1/bnorm2, 10) == 0
433 assert round(1.0 - Anorm1/Anorm2, 10) == 0
434
435
436 def test_ghost_mode_handling(pushpop_parameters):
437 def _forms():
438 # Return forms with interior facet integral
439 mesh = UnitSquareMesh(10, 10)
440 V = FunctionSpace(mesh, "P", 1)
441 u, v = TrialFunction(V), TestFunction(V)
442 a, L = u('+')*v('+')*dS, v('+')*dS
443 return a, L
444
445 def _check_value(forms):
446 A, b = assemble_system(*forms)
447 # Test by vector of ones; gives length of interior facets
448 x = Vector()
449 A.init_vector(x, 1)
450 x[:] = 1.0
451 assert numpy.isclose(b.inner(x), 18.0+10*2.0**0.5)
452 assert numpy.isclose((A*x).inner(x), 18.0+10*2.0**0.5)
453
454 # Not-ghosted mesh won't work in parallel and assembler should raise
455 parameters["ghost_mode"] = "none"
456 if MPI.size(MPI.comm_world) == 1:
457 _check_value(_forms())
458 else:
459 assembler = SystemAssembler(*_forms())
460 A, b = Matrix(), Vector()
461 with pytest.raises(RuntimeError) as excinfo:
462 assembler.assemble(A, b)
463 assert "Incorrect mesh ghost mode" in repr(excinfo.value)
464
465 # Ghosted meshes work everytime
466 parameters["ghost_mode"] = "shared_vertex"
467 _check_value(_forms())
468 parameters["ghost_mode"] = "shared_facet"
469 _check_value(_forms())