Debian Codegraph @

python/test/unit/fem/test_assembler.py

raw
1 """Unit tests for assembly"""
2
3 # Copyright (C) 2011-2014 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 Marie E. Rognes 2011
21 # Modified by Anders Logg 2011
22 # Modified by Martin Alnes 2014
23
24 import pytest
25 import os
26 import numpy
27 from dolfin import *
28
29 from dolfin_utils.test import skip_in_parallel, filedir, pushpop_parameters
30
31
32 def test_cell_size_assembly_1D():
33 mesh = UnitIntervalMesh(10)
34 assert round(assemble(2*Circumradius(mesh)*dx) - 0.1, 12) == 0
35 assert round(assemble(CellDiameter(mesh)*dx) - 0.1, 12) == 0
36 assert round(assemble(CellVolume(mesh)*dx) - 0.1, 12) == 0
37
38
39 def test_cell_assembly_1D():
40 mesh = UnitIntervalMesh(48)
41 V = FunctionSpace(mesh, "CG", 1)
42
43 v = TestFunction(V)
44 u = TrialFunction(V)
45 f = Constant(10.0)
46
47 a = inner(grad(v), grad(u))*dx
48 L = inner(v, f)*dx
49
50 A_frobenius_norm = 811.75365721381274397572
51 b_l2_norm = 1.43583841167606474087
52
53 # Assemble A and b
54 assert round(assemble(a).norm("frobenius") - A_frobenius_norm, 10) == 0
55 assert round(assemble(L).norm("l2") - b_l2_norm, 10) == 0
56
57
58 def test_cell_assembly():
59 mesh = UnitCubeMesh(4, 4, 4)
60 V = VectorFunctionSpace(mesh, "DG", 1)
61
62 v = TestFunction(V)
63 u = TrialFunction(V)
64 f = Constant((10, 20, 30))
65
66 def epsilon(v):
67 return 0.5*(grad(v) + grad(v).T)
68
69 a = inner(epsilon(v), epsilon(u))*dx
70 L = inner(v, f)*dx
71
72 A_frobenius_norm = 4.3969686527582512
73 b_l2_norm = 0.95470326978246278
74
75 # Assemble A and b
76 assert round(assemble(a).norm("frobenius") - A_frobenius_norm, 10) == 0
77 assert round(assemble(L).norm("l2") - b_l2_norm, 10) == 0
78
79
80 def test_facet_assembly(pushpop_parameters):
81 parameters["ghost_mode"] = "shared_facet"
82 mesh = UnitSquareMesh(24, 24)
83 V = FunctionSpace(mesh, "DG", 1)
84
85 # Define test and trial functions
86 v = TestFunction(V)
87 u = TrialFunction(V)
88
89 # Define normal component, mesh size and right-hand side
90 n = FacetNormal(mesh)
91 h = 2*Circumradius(mesh)
92 h_avg = (h('+') + h('-'))/2
93 f = Expression("500.0*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)", degree=1)
94
95 # Define bilinear form
96 a = dot(grad(v), grad(u))*dx \
97 - dot(avg(grad(v)), jump(u, n))*dS \
98 - dot(jump(v, n), avg(grad(u)))*dS \
99 + 4.0/h_avg*dot(jump(v, n), jump(u, n))*dS \
100 - dot(grad(v), u*n)*ds \
101 - dot(v*n, grad(u))*ds \
102 + 8.0/h*v*u*ds
103
104 # Define linear form
105 L = v*f*dx
106
107 # Reference values
108 A_frobenius_norm = 157.867392938645
109 b_l2_norm = 1.48087142738768
110
111 # Assemble A and b
112 assert round(assemble(a).norm("frobenius") - A_frobenius_norm, 10) == 0
113 assert round(assemble(L).norm("l2") - b_l2_norm, 10) == 0
114
115
116 def test_ghost_mode_handling(pushpop_parameters):
117 def _form():
118 # Return form with trivial interior facet integral
119 mesh = UnitSquareMesh(10, 10)
120 ff = MeshFunction('size_t', mesh, mesh.topology().dim()-1, 0)
121 AutoSubDomain(lambda x: near(x[0], 0.5)).mark(ff, 1)
122 return Constant(1.0)*dS(domain=mesh, subdomain_data=ff, subdomain_id=1)
123
124 # Not-ghosted mesh won't work in parallel and assembler should raise
125 parameters["ghost_mode"] = "none"
126 if MPI.size(MPI.comm_world) == 1:
127 assert numpy.isclose(assemble(_form()), 1.0)
128 else:
129 form = _form()
130 with pytest.raises(RuntimeError) as excinfo:
131 assemble(form)
132 assert "Incorrect mesh ghost mode" in repr(excinfo.value)
133
134 # Ghosted meshes work everytime
135 parameters["ghost_mode"] = "shared_vertex"
136 assert numpy.isclose(assemble(_form()), 1.0)
137 parameters["ghost_mode"] = "shared_facet"
138 assert numpy.isclose(assemble(_form()), 1.0)
139
140 @pytest.mark.parametrize('mesh_factory, facet_area', [((UnitSquareMesh, (4, 4)), 4.0),
141 ((UnitCubeMesh, (2, 2, 2)), 6.0),
142 ((UnitSquareMesh.create, (4, 4, CellType.Type.quadrilateral)), 4.0),
143 ((UnitCubeMesh.create, (2, 2, 2, CellType.Type.hexahedron)), 6.0)])
144 def test_functional_assembly(mesh_factory, facet_area):
145 func, args = mesh_factory
146 mesh = func(*args)
147
148 f = Constant(1.0)
149 M0 = f*dx(mesh)
150 assert round(assemble(M0) - 1.0, 7) == 0
151
152 M1 = f*ds(mesh)
153 assert round(assemble(M1) - facet_area, 7) == 0
154
155
156 @pytest.mark.parametrize('mesh_factory', [(UnitCubeMesh, (4, 4, 4)), (UnitCubeMesh.create, (4, 4, 4, CellType.Type.hexahedron))])
157 def test_subdomain_and_fulldomain_assembly_meshdomains(mesh_factory):
158 """Test assembly over subdomains AND the full domain with markers
159 stored as part of the mesh.
160 """
161
162 # Create a mesh of the unit cube
163 func, args = mesh_factory
164 mesh = func(*args)
165
166 # Define subdomains for 3 faces of the unit cube
167 class F0(SubDomain):
168 def inside(self, x, inside):
169 return near(x[0], 0.0)
170
171 class F1(SubDomain):
172 def inside(self, x, inside):
173 return near(x[1], 0.0)
174
175 class F2(SubDomain):
176 def inside(self, x, inside):
177 return near(x[2], 0.0)
178
179 # Define subdomains for 3 parts of the unit cube
180 class S0(SubDomain):
181 def inside(self, x, inside):
182 return x[0] > 0.25
183
184 class S1(SubDomain):
185 def inside(self, x, inside):
186 return x[0] > 0.5
187
188 class S2(SubDomain):
189 def inside(self, x, inside):
190 return x[0] > 0.75
191
192 # Mark mesh
193 f0 = F0()
194 f1 = F1()
195 f2 = F2()
196 f0.mark_facets(mesh, 0)
197 f1.mark_facets(mesh, 1)
198 f2.mark_facets(mesh, 3) # NB! 3, to leave a gap
199
200 s0 = S0()
201 s1 = S1()
202 s2 = S2()
203 s0.mark_cells(mesh, 0)
204 s1.mark_cells(mesh, 1)
205 s2.mark_cells(mesh, 3) # NB! 3, to leave a gap
206
207 # Assemble forms on subdomains and full domain and compare
208 krange = list(range(5))
209 for dmu in (dx, ds):
210 full = assemble(Constant(3.0)*dmu(mesh))
211 subplusfull = [assemble(Constant(3.0)*dmu(mesh) +
212 Constant(1.0)*dmu(k, domain=mesh))
213 for k in krange]
214 sub = [assemble(Constant(1.0)*dmu(k, domain=mesh)) for k in krange]
215 for k in krange:
216 # print sub[k] + full, subplusfull[k]
217 assert round(sub[k] + full - subplusfull[k], 7) == 0
218
219
220 @skip_in_parallel
221 def test_subdomain_assembly_form_1():
222 "Test assembly over subdomains with markers stored as part of form"
223
224 mesh = UnitSquareMesh(4, 4)
225
226 # Define cell/facet function
227 class Left(SubDomain):
228 def inside(self, x, on_boundary):
229 return x[0] < 0.49
230 subdomains = MeshFunction("size_t", mesh, mesh.topology().dim())
231 subdomains.set_all(0)
232 left = Left()
233 left.mark(subdomains, 1)
234
235 class RightBoundary(SubDomain):
236 def inside(self, x, on_boundary):
237 return x[0] > 0.95
238 boundaries = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
239 boundaries.set_all(0)
240 right = RightBoundary()
241 right.mark(boundaries, 1)
242
243 V = FunctionSpace(mesh, "CG", 2)
244 f = Expression("x[0] + 2", degree=1)
245 g = Expression("x[1] + 1", degree=1)
246
247 f = interpolate(f, V)
248 g = interpolate(g, V)
249
250 mesh1 = subdomains.mesh()
251 mesh2 = boundaries.mesh()
252 assert mesh1.id() == mesh2.id()
253 assert mesh1.ufl_domain().ufl_id() == mesh2.ufl_domain().ufl_id()
254
255 dxs = dx(subdomain_data=subdomains)
256 dss = ds(subdomain_data=boundaries)
257 assert dxs.ufl_domain() == None
258 assert dss.ufl_domain() == None
259 assert dxs.subdomain_data() == subdomains
260 assert dss.subdomain_data() == boundaries
261
262 M = f*f*dxs(0) + g*f*dxs(1) + f*f*dss(1)
263 assert M.ufl_domains() == (mesh.ufl_domain(),)
264 sd = M.subdomain_data()[mesh.ufl_domain()]
265 assert sd["cell"] == subdomains
266 assert sd["exterior_facet"] == boundaries
267
268 # Check that subdomains are respected
269 reference = 15.0
270 assert round(assemble(M) - reference, 10) == 0
271
272 # Check that the form itself assembles as before
273 assert round(assemble(M) - reference, 10) == 0
274
275 # Take action of derivative of M on f
276 df = TestFunction(V)
277 L = derivative(M, f, df)
278 dg = TrialFunction(V)
279 F = derivative(L, g, dg)
280 b = action(F, f)
281
282 # Check that domain data carries across transformations:
283 reference = 0.136477465659
284 assert round(assemble(b).norm("l2") - reference, 8) == 0
285
286
287 def test_subdomain_assembly_form_2():
288 "Test assembly over subdomains with markers stored as part of form"
289
290 # Define mesh
291 mesh = UnitSquareMesh(8, 8)
292
293 # Define domain for lower left corner
294 class MyDomain(SubDomain):
295 def inside(self, x, on_boundary):
296 return x[0] < 0.5 + DOLFIN_EPS and x[1] < 0.5 + DOLFIN_EPS
297 my_domain = MyDomain()
298
299 # Define boundary for lower left corner
300 class MyBoundary(SubDomain):
301 def inside(self, x, on_boundary):
302 return (x[0] < 0.5 + DOLFIN_EPS and x[1] < DOLFIN_EPS) or \
303 (x[1] < 0.5 + DOLFIN_EPS and x[0] < DOLFIN_EPS)
304 my_boundary = MyBoundary()
305
306 # Mark mesh functions
307 D = mesh.topology().dim()
308 cell_domains = MeshFunction("size_t", mesh, D)
309 exterior_facet_domains = MeshFunction("size_t", mesh, D - 1)
310 cell_domains.set_all(1)
311 exterior_facet_domains.set_all(1)
312 my_domain.mark(cell_domains, 0)
313 my_boundary.mark(exterior_facet_domains, 0)
314
315 # Define forms
316 c = Constant(1.0)
317
318 a0 = c*dx(0, domain=mesh, subdomain_data=cell_domains)
319 a1 = c*ds(0, domain=mesh, subdomain_data=exterior_facet_domains)
320
321 assert round(assemble(a0) - 0.25, 7) == 0
322 assert round(assemble(a1) - 1.0, 7) == 0
323
324
325 def test_nonsquare_assembly():
326 """Test assembly of a rectangular matrix"""
327
328 mesh = UnitSquareMesh(16, 16)
329
330 V = VectorElement("Lagrange", mesh.ufl_cell(), 2)
331 Q = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
332 W = V*Q
333 V = FunctionSpace(mesh, V)
334 Q = FunctionSpace(mesh, Q)
335 W = FunctionSpace(mesh, W)
336
337 (v, q) = TestFunctions(W)
338 (u, p) = TrialFunctions(W)
339 a = div(v)*p*dx
340 A_frobenius_norm = 9.6420303878382718e-01
341 assert round(assemble(a).norm("frobenius") - A_frobenius_norm, 10) == 0
342
343 v = TestFunction(V)
344 p = TrialFunction(Q)
345 a = inner(grad(p), v)*dx
346 A_frobenius_norm = 0.935414346693
347 assert round(assemble(a).norm("frobenius") - A_frobenius_norm, 10) == 0
348
349
350 @skip_in_parallel
351 def test_reference_assembly(filedir, pushpop_parameters):
352 "Test assembly against a reference solution"
353
354 # NOTE: This test is not robust as it relies on specific
355 # DOF order, which cannot be guaranteed
356 parameters["reorder_dofs_serial"] = False
357
358 # Load reference mesh (just a simple tetrahedron)
359 mesh = Mesh(os.path.join(filedir, "tetrahedron.xml"))
360
361 # Assemble stiffness and mass matrices
362 V = FunctionSpace(mesh, "Lagrange", 1)
363 u, v = TrialFunction(V), TestFunction(V)
364 A, M = EigenMatrix(), EigenMatrix()
365 assemble(dot(grad(v), grad(u))*dx, tensor=A)
366 assemble(v*u*dx, tensor=M)
367
368 # Run test (requires SciPy)
369 try:
370 import scipy
371 A = A.sparray().todense()
372 M = M.sparray().todense()
373
374 # Create reference matrices and set entries
375 A0 = numpy.array([[1.0/2.0, -1.0/6.0, -1.0/6.0, -1.0/6.0],
376 [-1.0/6.0, 1.0/6.0, 0.0, 0.0],
377 [-1.0/6.0, 0.0, 1.0/6.0, 0.0],
378 [-1.0/6.0, 0.0, 0.0, 1.0/6.0]])
379 M0 = numpy.array([[1.0/60.0, 1.0/120.0, 1.0/120.0, 1.0/120.0],
380 [1.0/120.0, 1.0/60.0, 1.0/120.0, 1.0/120.0],
381 [1.0/120.0, 1.0/120.0, 1.0/60.0, 1.0/120.0],
382 [1.0/120.0, 1.0/120.0, 1.0/120.0, 1.0/60.0]])
383
384 C = A - A0
385 assert round(numpy.linalg.norm(C, 'fro') - 0.0, 7) == 0
386 D = M - M0
387 assert round(numpy.linalg.norm(D, 'fro') - 0.0, 7) == 0
388
389 except:
390 print("Cannot run this test without SciPy")
391
392
393 def test_ways_to_pass_mesh_to_assembler():
394 mesh = UnitSquareMesh(16, 16)
395
396 # Geometry with mesh (ufl.Domain with mesh in domain data)
397 x = SpatialCoordinate(mesh)
398 n = FacetNormal(mesh)
399
400 # Geometry with just cell (no reference to mesh, for backwards
401 # compatibility)
402 x2 = SpatialCoordinate(mesh)
403 n2 = FacetNormal(mesh)
404
405 # A function equal to x[0] for comparison
406 V = FunctionSpace(mesh, "CG", 1)
407 f = Function(V)
408 f.interpolate(Expression("x[0]", degree=1))
409
410 # An expression equal to x[0], with different geometry info:
411 e = Expression("x[0]", degree=1) # nothing
412 e2 = Expression("x[0]", cell=mesh.ufl_cell(), degree=1) # cell
413 e3 = Expression("x[0]", element=V.ufl_element()) # ufl element
414 e4 = Expression("x[0]", domain=mesh, degree=1) # mesh
415
416 # Provide mesh in measure:
417 dx2 = Measure("dx", domain=mesh)
418 assert round(1.0 - assemble(1*dx(mesh)), 7) == 0
419 assert round(1.0 - assemble(Constant(1.0)*dx(mesh)), 7) == 0
420 assert round(1.0 - assemble(Constant(1.0)*dx2), 7) == 0
421
422 # Try with cell argument to Constant as well:
423 assert round(1.0 - assemble(Constant(1.0,
424 cell=mesh.ufl_cell())*dx(mesh))) == 0
425 assert round(1.0 - assemble(Constant(1.0, cell=mesh.ufl_cell())*dx2)) == 0
426 assert round(1.0 - assemble(Constant(1.0,
427 cell=mesh.ufl_cell())*dx(mesh))) == 0
428 assert round(1.0 - assemble(Constant(1.0, cell=mesh.ufl_cell())*dx2)) == 0
429
430 # Geometric quantities with mesh in domain:
431 assert round(0.5 - assemble(x[0]*dx), 7) == 0
432 assert round(0.5 - assemble(x[0]*dx(mesh)), 7) == 0
433
434 # Geometric quantities without mesh in domain:
435 assert round(0.5 - assemble(x2[0]*dx(mesh)), 7) == 0
436
437 # Functions with mesh in domain:
438 assert round(0.5 - assemble(f*dx), 7) == 0
439 assert round(0.5 - assemble(f*dx(mesh)), 7) == 0
440
441 # Expressions with and without mesh in domain:
442 assert round(0.5 - assemble(e*dx(mesh)), 7) == 0
443 assert round(0.5 - assemble(e2*dx(mesh)), 7) == 0
444 assert round(0.5 - assemble(e3*dx(mesh)), 7) == 0
445 assert round(0.5 - assemble(e4*dx), 7) == 0 # e4 has a domain with mesh reference
446 assert round(0.5 - assemble(e4*dx(mesh)), 7) == 0
447
448 # Geometric quantities with mesh in domain:
449 assert round(0.0 - assemble(n[0]*ds), 7) == 0
450 assert round(0.0 - assemble(n[0]*ds(mesh)), 7) == 0
451
452 # Geometric quantities without mesh in domain:
453 assert round(0.0 - assemble(n2[0]*ds(mesh)), 7) == 0