Debian Codegraph @

python/test/unit/fem/test_manifolds.py

raw
1 """Unit tests for the solve function on manifolds
2 embedded in higher dimensional spaces."""
3
4 # Copyright (C) 2012 Imperial College London and others.
5 #
6 # This file is part of DOLFIN.
7 #
8 # DOLFIN is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Lesser General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # DOLFIN is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public License
19 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
20 #
21 # Modified by David Ham 2012
22
23 # MER: The solving test should be moved into test/regression/..., the
24 # evaluatebasis part should be moved into test/unit/FiniteElement.py
25
26 import pytest
27 from dolfin import *
28 import os
29 import numpy
30 from dolfin_utils.test import *
31
32
33 # Subdomain to extract bottom boundary.
34 class BottomEdge(SubDomain):
35 def inside(self, x, on_boundary):
36 return near(x[2], 0.0)
37
38
39 class Rotation:
40 """Class implementing rotations of the unit plane through an angle
41 of phi about the x axis followed by theta about the z axis."""
42 def __init__(self, phi, theta):
43 self.theta = theta
44 self.mat = numpy.dot(self._zmat(theta), self._xmat(phi))
45 self.invmat = numpy.dot(self._xmat(-phi), self._zmat(-theta))
46
47 def _zmat(self, theta):
48 return numpy.array([[numpy.cos(theta), -numpy.sin(theta), 0.0],
49 [numpy.sin(theta), numpy.cos(theta), 0.0],
50 [0.0, 0.0, 1.0]])
51
52 def _xmat(self, phi):
53 return numpy.array([[1.0, 0.0, 0.0],
54 [0.0, numpy.cos(phi), -numpy.sin(phi)],
55 [0.0, numpy.sin(phi), numpy.cos(phi)]])
56
57 def to_plane(self, x):
58 """Map the point x back to the horizontal plane."""
59 return numpy.dot(self.invmat, x)
60
61 def x(self, i):
62 """Produce a C expression for the ith component
63 of the image of x mapped back to the horizontal plane."""
64
65 return "("+" + ".join(["%.17f * x[%d]" % (a, j)
66 for (j, a) in enumerate(self.invmat[i, :])])+")"
67
68 def rotate(self, mesh):
69 """Rotate mesh through phi then theta."""
70
71 mesh.coordinates()[:, :] = \
72 numpy.dot(mesh.coordinates()[:, :], self.mat.T)
73
74 def rotate_point(self, point):
75 """Rotate point through phi then theta."""
76
77 return numpy.dot(point, self.mat.T)
78
79
80 def poisson_2d():
81
82 # Create mesh and define function space
83 mesh = UnitSquareMesh(32, 32)
84 V = FunctionSpace(mesh, "Lagrange", 1)
85
86 # Define Dirichlet boundary (x = 0 or x = 1)
87 def boundary(x):
88 return x[0] < DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS
89
90 # Define boundary condition
91 u0 = Constant(0.0)
92 bc = DirichletBC(V, u0, boundary)
93
94 # Define variational problem
95 u = TrialFunction(V)
96 v = TestFunction(V)
97 f = Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)", degree=2)
98 g = Expression("sin(5*x[0])", degree=2)
99 a = inner(grad(u), grad(v))*dx
100 L = f*v*dx + g*v*ds
101
102 # Compute solution
103 u = Function(V)
104 solve(a == L, u, bc)
105
106 return u
107
108
109 def poisson_manifold():
110
111 # Create mesh
112 cubemesh = UnitCubeMesh(32, 32, 2)
113 boundarymesh = BoundaryMesh(cubemesh, "exterior")
114 mesh = SubMesh(boundarymesh, BottomEdge())
115
116 rotation = Rotation(numpy.pi/4, numpy.pi/4)
117 rotation.rotate(mesh)
118
119 # Define function space
120 V = FunctionSpace(mesh, "Lagrange", 1)
121
122 # Define Dirichlet boundary (x = 0 or x = 1)
123 def boundary(x):
124 return rotation.to_plane(x)[0] < DOLFIN_EPS or \
125 rotation.to_plane(x)[0] > 1.0 - DOLFIN_EPS
126
127 # Define boundary condition
128 u0 = Constant(0.0)
129 bc = DirichletBC(V, u0, boundary)
130
131 # Define variational problem
132 u = TrialFunction(V)
133 v = TestFunction(V)
134 f = Expression(("10*exp(-(pow(x[0] - %.17f, 2)" +
135 " + pow(x[1] - %.17f, 2)" +
136 " + pow(x[2] - %.17f, 2)) / 0.02)")
137 % tuple(rotation.rotate_point([0.5, 0.5, 0])), degree=2)
138 g = Expression("sin(5*%s)" % rotation.x(0), degree=2)
139
140 a = inner(grad(u), grad(v))*dx
141 L = f*v*dx + g*v*ds
142
143 # Compute solution
144 u = Function(V)
145 solve(a == L, u, bc)
146
147 return u
148
149
150 def rotate_2d_mesh(theta):
151 """Unit square mesh in 2D rotated through theta about the x and z
152 axes."""
153
154 cubemesh = UnitCubeMesh(1, 1, 1)
155 boundarymesh = BoundaryMesh(cubemesh, "exterior")
156 mesh = SubMesh(boundarymesh, BottomEdge())
157
158 mesh.init_cell_orientations(Expression(("0.", "0.", "1."), degree=0))
159
160 rotation = Rotation(theta, theta)
161 rotation.rotate(mesh)
162
163 return mesh
164
165
166 @skip_in_parallel
167 def test_poisson2D_in_3D():
168 """This test solves Poisson's equation on a unit square in 2D, and
169 then on a unit square embedded in 3D and rotated pi/4 radians
170 about each of the z and x axes.
171
172 """
173
174 u_2D = poisson_2d()
175 u_manifold = poisson_manifold()
176
177 assert round(u_2D.vector().norm("l2") - u_manifold.vector().norm("l2"),
178 10) == 0
179 assert round(u_2D.vector().max() - u_manifold.vector().max(), 10) == 0
180 assert round(u_2D.vector().min() - u_manifold.vector().min(), 10) == 0
181
182
183 # TODO: Use pytest parameterization
184 @skip_in_parallel
185 def test_basis_evaluation_2D_in_3D():
186 """This test checks that basis functions and their derivatives are
187 unaffected by rotations."""
188
189 basemesh = rotate_2d_mesh(0.0)
190 rotmesh = rotate_2d_mesh(numpy.pi/4)
191 rotation = Rotation(numpy.pi/4, numpy.pi/4)
192
193 for i in range(4):
194 basis_test("CG", i + 1, basemesh, rotmesh, rotation)
195 for i in range(5):
196 basis_test("DG", i, basemesh, rotmesh, rotation)
197 for i in range(4):
198 basis_test("RT", i + 1, basemesh, rotmesh, rotation, piola=True,)
199 for i in range(4):
200 basis_test("DRT", i + 1, basemesh, rotmesh, rotation, piola=True)
201 for i in range(4):
202 basis_test("BDM", i + 1, basemesh, rotmesh, rotation, piola=True)
203 for i in range(4):
204 basis_test("N1curl", i + 1, basemesh, rotmesh, rotation, piola=True)
205 basis_test("BDFM", 2, basemesh, rotmesh, rotation, piola=True)
206
207
208 def basis_test(family, degree, basemesh, rotmesh, rotation, piola=False):
209 ffc_option = "no-evaluate_basis_derivatives"
210 basis_derivatives = parameters["form_compiler"][ffc_option]
211 parameters["form_compiler"]["no-evaluate_basis_derivatives"] = False
212
213 f_base = FunctionSpace(basemesh, family, degree)
214 f_rot = FunctionSpace(rotmesh, family, degree)
215
216 points = numpy.array([[1.0, 1.0, 0.0],
217 [0.5, 0.5, 0.0],
218 [0.3, 0.7, 0.0],
219 [0.4, 0.0, 0.0]])
220
221 for cell_base, cell_rot in zip(cells(basemesh), cells(rotmesh)):
222
223 values_base = numpy.zeros(f_base.element().value_dimension(0))
224 derivs_base = numpy.zeros(f_base.element().value_dimension(0)*3)
225 values_rot = numpy.zeros(f_rot.element().value_dimension(0))
226 derivs_rot = numpy.zeros(f_rot.element().value_dimension(0)*3)
227
228 # Get cell vertices
229 vertex_coordinates_base = cell_base.get_vertex_coordinates()
230 vertex_coordinates_rot = cell_rot.get_vertex_coordinates()
231
232 for i in range(f_base.element().space_dimension()):
233 for point in points:
234
235 values_base = f_base.element().evaluate_basis(i,
236 point, vertex_coordinates_base,
237 cell_base.orientation())
238
239 derivs_base = f_base.element().evaluate_basis_derivatives(i, 1,
240 point, vertex_coordinates_base,
241 cell_base.orientation())
242
243 values_rot = f_rot.element().evaluate_basis(i,
244 rotation.rotate_point(point),
245 vertex_coordinates_rot,
246 cell_rot.orientation())
247
248 derivs_rot = f_base.element().evaluate_basis_derivatives(i, 1,
249 rotation.rotate_point(point),
250 vertex_coordinates_rot,
251 cell_rot.orientation())
252
253 if piola:
254 values_cmp = rotation.rotate_point(values_base)
255
256 derivs_rot2 = derivs_rot.reshape(f_rot.element().value_dimension(0),3)
257 derivs_base2 = derivs_base.reshape(f_base.element().value_dimension(0),3)
258 # If D is the unrotated derivative tensor, then
259 # RDR^T is the rotated version.
260 derivs_cmp = numpy.dot(rotation.mat,
261 rotation.rotate_point(derivs_base2))
262 else:
263 values_cmp = values_base
264 # Rotate the derivative for comparison.
265 derivs_cmp = rotation.rotate_point(derivs_base)
266 derivs_rot2 = derivs_rot
267
268 assert round(abs(derivs_rot2-derivs_cmp).max() - 0.0, 10) == 0
269 assert round(abs(values_cmp-values_rot).max() - 0.0, 10) == 0
270
271 parameters["form_compiler"]["no-evaluate_basis_derivatives"] = basis_derivatives
272
273
274 def test_elliptic_eqn_on_intersecting_surface(datadir):
275 """Solves -grad^2 u + u = f on domain of two intersecting square
276 surfaces embedded in 3D with natural bcs. Test passes if at end
277 \int u dx = \int f dx over whole domain
278
279 """
280 # This needs to be odd
281 #num_vertices_side = 31
282 #mesh = make_mesh(num_vertices_side)
283 #file = File("intersecting_surfaces.xml.gz", "compressed")
284 #file << mesh
285 filename = os.path.join(datadir, "intersecting_surfaces.xml")
286 mesh = Mesh(filename)
287
288 # function space, etc
289 V = FunctionSpace(mesh, "CG", 2)
290 u = TrialFunction(V)
291 v = TestFunction(V)
292
293 class Source(UserExpression):
294 def eval(self, value, x):
295 # r0 should be less than 0.5 * sqrt(2) in order for source to be
296 # exactly zero on vertical part of domain
297 r0 = 0.7
298 r = sqrt(x[0] * x[0] + x[1] * x[1])
299 if r < r0:
300 value[0] = 20.0 * pow((r0 - r), 2)
301 else:
302 value[0] = 0.0
303
304 f = Function(V)
305 f.interpolate(Source(degree=2))
306
307 a = inner(grad(u), grad(v))*dx + u*v*dx
308 L = f*v*dx
309
310 u = Function(V)
311 solve(a == L, u)
312
313 f_tot = assemble(f*dx)
314 u_tot = assemble(u*dx)
315
316 # test passes if f_tot = u_tot
317 assert abs(f_tot - u_tot) < 1e-7
318
319
320 def make_mesh(num_vertices_side):
321 # each square has unit side length
322 domain_size = 1.0
323
324 center_index = (num_vertices_side - 1) / 2
325 mesh = Mesh()
326 editor = MeshEditor()
327 editor.open(mesh, 2, 3)
328
329 num_vertices = 2 * num_vertices_side * num_vertices_side - center_index - 1
330 num_cells = 4 * (num_vertices_side - 1) * (num_vertices_side - 1)
331
332 editor.init_vertices(num_vertices)
333 editor.init_cells(num_cells)
334
335 spacing = domain_size / (num_vertices_side - 1.0)
336
337 # array of vertex indices
338 v = [[0]*num_vertices_side for i in range(num_vertices_side)]
339
340 # horizontal part of domain vertices
341 vertex_count = 0
342
343 for i in range(num_vertices_side):
344 y = i * spacing
345 for j in range(num_vertices_side):
346 x = j * spacing
347 p = Point(x, y, 0.0)
348 editor.add_vertex(vertex_count, p)
349 v[i][j] = vertex_count
350 vertex_count += 1
351
352 # cells
353 cell_count = 0
354 for i in range(num_vertices_side - 1):
355 for j in range(num_vertices_side - 1):
356 editor.add_cell(cell_count, v[i][j], v[i][j+1], v[i+1][j])
357 cell_count += 1
358
359 editor.add_cell(cell_count, v[i][j+1], v[i+1][j], v[i+1][j+1])
360 cell_count += 1
361
362 # vertical part of domain
363 # vertices
364 for i in range(num_vertices_side):
365 z = i * spacing - 0.5
366 for j in range(num_vertices_side):
367 x = j * spacing + 0.5
368 if not (i == center_index and j <= center_index):
369 p = Point(x, 0.5, z)
370 editor.add_vertex(vertex_count, p)
371 v[i][j] = vertex_count
372 vertex_count += 1
373 else:
374 v[i][j] += center_index
375
376 # cells
377 for i in range(num_vertices_side - 1):
378 for j in range(num_vertices_side - 1):
379 editor.add_cell(cell_count, v[i][j], v[i][j+1], v[i+1][j])
380 cell_count += 1
381
382 editor.add_cell(cell_count, v[i][j+1], v[i+1][j], v[i+1][j+1])
383 cell_count += 1
384
385 editor.close()
386
387 return mesh