File: test_manifolds.py

package info (click to toggle)
dolfin 2018.1.0.post1-16
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 28,764 kB
  • sloc: xml: 104,040; cpp: 98,856; python: 22,511; makefile: 204; sh: 182
file content (387 lines) | stat: -rw-r--r-- 13,059 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""Unit tests for the solve function on manifolds
embedded in higher dimensional spaces."""

# Copyright (C) 2012 Imperial College London and others.
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# Modified by David Ham 2012

# MER: The solving test should be moved into test/regression/..., the
# evaluatebasis part should be moved into test/unit/FiniteElement.py

import pytest
from dolfin import *
import os
import numpy
from dolfin_utils.test import *


# Subdomain to extract bottom boundary.
class BottomEdge(SubDomain):
    def inside(self, x, on_boundary):
        return near(x[2], 0.0)


class Rotation:
    """Class implementing rotations of the unit plane through an angle
    of phi about the x axis followed by theta about the z axis."""
    def __init__(self, phi, theta):
        self.theta = theta
        self.mat = numpy.dot(self._zmat(theta), self._xmat(phi))
        self.invmat = numpy.dot(self._xmat(-phi), self._zmat(-theta))

    def _zmat(self, theta):
        return numpy.array([[numpy.cos(theta), -numpy.sin(theta), 0.0],
                            [numpy.sin(theta),  numpy.cos(theta), 0.0],
                            [0.0,           0.0,          1.0]])

    def _xmat(self, phi):
        return numpy.array([[1.0,           0.0,           0.0],
                            [0.0,  numpy.cos(phi), -numpy.sin(phi)],
                            [0.0,  numpy.sin(phi),  numpy.cos(phi)]])

    def to_plane(self, x):
        """Map the point x back to the horizontal plane."""
        return numpy.dot(self.invmat, x)

    def x(self, i):
        """Produce a C expression for the ith component
        of the image of x mapped back to the horizontal plane."""

        return "("+" + ".join(["%.17f * x[%d]" % (a, j)
                               for (j, a) in enumerate(self.invmat[i, :])])+")"

    def rotate(self, mesh):
        """Rotate mesh through phi then theta."""

        mesh.coordinates()[:, :] = \
            numpy.dot(mesh.coordinates()[:, :], self.mat.T)

    def rotate_point(self, point):
        """Rotate point through phi then theta."""

        return numpy.dot(point, self.mat.T)


def poisson_2d():

    # Create mesh and define function space
    mesh = UnitSquareMesh(32, 32)
    V = FunctionSpace(mesh, "Lagrange", 1)

    # Define Dirichlet boundary (x = 0 or x = 1)
    def boundary(x):
        return x[0] < DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS

    # Define boundary condition
    u0 = Constant(0.0)
    bc = DirichletBC(V, u0, boundary)

    # Define variational problem
    u = TrialFunction(V)
    v = TestFunction(V)
    f = Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)", degree=2)
    g = Expression("sin(5*x[0])", degree=2)
    a = inner(grad(u), grad(v))*dx
    L = f*v*dx + g*v*ds

    # Compute solution
    u = Function(V)
    solve(a == L, u, bc)

    return u


def poisson_manifold():

    # Create mesh
    cubemesh = UnitCubeMesh(32, 32, 2)
    boundarymesh = BoundaryMesh(cubemesh, "exterior")
    mesh = SubMesh(boundarymesh, BottomEdge())

    rotation = Rotation(numpy.pi/4, numpy.pi/4)
    rotation.rotate(mesh)

    # Define function space
    V = FunctionSpace(mesh, "Lagrange", 1)

    # Define Dirichlet boundary (x = 0 or x = 1)
    def boundary(x):
        return rotation.to_plane(x)[0] < DOLFIN_EPS or \
            rotation.to_plane(x)[0] > 1.0 - DOLFIN_EPS

    # Define boundary condition
    u0 = Constant(0.0)
    bc = DirichletBC(V, u0, boundary)

    # Define variational problem
    u = TrialFunction(V)
    v = TestFunction(V)
    f = Expression(("10*exp(-(pow(x[0] - %.17f, 2)" +
                    " + pow(x[1] - %.17f, 2)" +
                    " + pow(x[2] - %.17f, 2)) / 0.02)")
                   % tuple(rotation.rotate_point([0.5, 0.5, 0])), degree=2)
    g = Expression("sin(5*%s)" % rotation.x(0), degree=2)

    a = inner(grad(u), grad(v))*dx
    L = f*v*dx + g*v*ds

    # Compute solution
    u = Function(V)
    solve(a == L, u, bc)

    return u


def rotate_2d_mesh(theta):
    """Unit square mesh in 2D rotated through theta about the x and z
    axes."""

    cubemesh = UnitCubeMesh(1, 1, 1)
    boundarymesh = BoundaryMesh(cubemesh, "exterior")
    mesh = SubMesh(boundarymesh, BottomEdge())

    mesh.init_cell_orientations(Expression(("0.", "0.", "1."), degree=0))

    rotation = Rotation(theta, theta)
    rotation.rotate(mesh)

    return mesh


@skip_in_parallel
def test_poisson2D_in_3D():
    """This test solves Poisson's equation on a unit square in 2D, and
    then on a unit square embedded in 3D and rotated pi/4 radians
    about each of the z and x axes.

    """

    u_2D = poisson_2d()
    u_manifold = poisson_manifold()

    assert round(u_2D.vector().norm("l2") - u_manifold.vector().norm("l2"),
                 10) == 0
    assert round(u_2D.vector().max() - u_manifold.vector().max(), 10) == 0
    assert round(u_2D.vector().min() - u_manifold.vector().min(), 10) == 0


# TODO: Use pytest parameterization
@skip_in_parallel
def test_basis_evaluation_2D_in_3D():
    """This test checks that basis functions and their derivatives are
    unaffected by rotations."""

    basemesh = rotate_2d_mesh(0.0)
    rotmesh = rotate_2d_mesh(numpy.pi/4)
    rotation = Rotation(numpy.pi/4, numpy.pi/4)

    for i in range(4):
        basis_test("CG", i + 1, basemesh, rotmesh, rotation)
    for i in range(5):
        basis_test("DG", i, basemesh, rotmesh, rotation)
    for i in range(4):
        basis_test("RT", i + 1, basemesh, rotmesh, rotation, piola=True,)
    for i in range(4):
        basis_test("DRT", i + 1, basemesh, rotmesh, rotation, piola=True)
    for i in range(4):
        basis_test("BDM", i + 1, basemesh, rotmesh, rotation, piola=True)
    for i in range(4):
        basis_test("N1curl", i + 1, basemesh, rotmesh, rotation, piola=True)
        basis_test("BDFM", 2, basemesh, rotmesh, rotation, piola=True)


def basis_test(family, degree, basemesh, rotmesh, rotation, piola=False):
    ffc_option = "no-evaluate_basis_derivatives"
    basis_derivatives = parameters["form_compiler"][ffc_option]
    parameters["form_compiler"]["no-evaluate_basis_derivatives"] = False

    f_base = FunctionSpace(basemesh, family, degree)
    f_rot = FunctionSpace(rotmesh, family, degree)

    points = numpy.array([[1.0, 1.0, 0.0],
                          [0.5, 0.5, 0.0],
                          [0.3, 0.7, 0.0],
                          [0.4, 0.0, 0.0]])

    for cell_base, cell_rot in zip(cells(basemesh), cells(rotmesh)):

        values_base = numpy.zeros(f_base.element().value_dimension(0))
        derivs_base = numpy.zeros(f_base.element().value_dimension(0)*3)
        values_rot = numpy.zeros(f_rot.element().value_dimension(0))
        derivs_rot = numpy.zeros(f_rot.element().value_dimension(0)*3)

        # Get cell vertices
        vertex_coordinates_base = cell_base.get_vertex_coordinates()
        vertex_coordinates_rot  = cell_rot.get_vertex_coordinates()

        for i in range(f_base.element().space_dimension()):
            for point in points:

                values_base = f_base.element().evaluate_basis(i,
                                       point, vertex_coordinates_base,
                                       cell_base.orientation())

                derivs_base = f_base.element().evaluate_basis_derivatives(i, 1,
                                          point, vertex_coordinates_base,
                                          cell_base.orientation())

                values_rot = f_rot.element().evaluate_basis(i,
                                          rotation.rotate_point(point),
                                          vertex_coordinates_rot,
                                          cell_rot.orientation())

                derivs_rot = f_base.element().evaluate_basis_derivatives(i, 1,
                                          rotation.rotate_point(point),
                                          vertex_coordinates_rot,
                                          cell_rot.orientation())

                if piola:
                    values_cmp = rotation.rotate_point(values_base)

                    derivs_rot2 = derivs_rot.reshape(f_rot.element().value_dimension(0),3)
                    derivs_base2 = derivs_base.reshape(f_base.element().value_dimension(0),3)
                    # If D is the unrotated derivative tensor, then
                    # RDR^T is the rotated version.
                    derivs_cmp = numpy.dot(rotation.mat,
                                            rotation.rotate_point(derivs_base2))
                else:
                    values_cmp = values_base
                    # Rotate the derivative for comparison.
                    derivs_cmp = rotation.rotate_point(derivs_base)
                    derivs_rot2 = derivs_rot

                assert round(abs(derivs_rot2-derivs_cmp).max() - 0.0, 10) == 0
                assert round(abs(values_cmp-values_rot).max() - 0.0, 10) == 0

    parameters["form_compiler"]["no-evaluate_basis_derivatives"] = basis_derivatives


def test_elliptic_eqn_on_intersecting_surface(datadir):
    """Solves -grad^2 u + u = f on domain of two intersecting square
     surfaces embedded in 3D with natural bcs. Test passes if at end
     \int u dx = \int f dx over whole domain

    """
    # This needs to be odd
    #num_vertices_side = 31
    #mesh = make_mesh(num_vertices_side)
    #file = File("intersecting_surfaces.xml.gz", "compressed")
    #file << mesh
    filename = os.path.join(datadir, "intersecting_surfaces.xml")
    mesh = Mesh(filename)

    # function space, etc
    V = FunctionSpace(mesh, "CG", 2)
    u = TrialFunction(V)
    v = TestFunction(V)

    class Source(UserExpression):
        def eval(self, value, x):
            # r0 should be less than 0.5 * sqrt(2) in order for source to be
            # exactly zero on vertical part of domain
            r0 = 0.7
            r = sqrt(x[0] * x[0] + x[1] * x[1])
            if r < r0:
                value[0] = 20.0 * pow((r0 - r), 2)
            else:
                value[0] = 0.0

    f = Function(V)
    f.interpolate(Source(degree=2))

    a = inner(grad(u), grad(v))*dx + u*v*dx
    L = f*v*dx

    u = Function(V)
    solve(a == L, u)

    f_tot = assemble(f*dx)
    u_tot = assemble(u*dx)

    # test passes if f_tot = u_tot
    assert abs(f_tot - u_tot) < 1e-7


def make_mesh(num_vertices_side):
    # each square has unit side length
    domain_size = 1.0

    center_index = (num_vertices_side - 1) / 2
    mesh = Mesh()
    editor = MeshEditor()
    editor.open(mesh, 2, 3)

    num_vertices = 2 * num_vertices_side * num_vertices_side - center_index - 1
    num_cells = 4 * (num_vertices_side - 1) * (num_vertices_side - 1)

    editor.init_vertices(num_vertices)
    editor.init_cells(num_cells)

    spacing = domain_size / (num_vertices_side - 1.0)

    # array of vertex indices
    v = [[0]*num_vertices_side for i in range(num_vertices_side)]

    # horizontal part of domain vertices
    vertex_count = 0

    for i in range(num_vertices_side):
        y = i * spacing
        for j in range(num_vertices_side):
            x = j * spacing
            p = Point(x, y, 0.0)
            editor.add_vertex(vertex_count, p)
            v[i][j] = vertex_count
            vertex_count += 1

    # cells
    cell_count = 0
    for i in range(num_vertices_side - 1):
        for j in range(num_vertices_side - 1):
            editor.add_cell(cell_count, v[i][j], v[i][j+1], v[i+1][j])
            cell_count += 1

            editor.add_cell(cell_count, v[i][j+1], v[i+1][j], v[i+1][j+1])
            cell_count += 1

    # vertical part of domain
    # vertices
    for i in range(num_vertices_side):
        z = i * spacing - 0.5
        for j in range(num_vertices_side):
            x = j * spacing + 0.5
            if not (i == center_index and j <= center_index):
                p = Point(x, 0.5, z)
                editor.add_vertex(vertex_count, p)
                v[i][j] = vertex_count
                vertex_count += 1
            else:
                v[i][j] += center_index

    # cells
    for i in range(num_vertices_side - 1):
        for j in range(num_vertices_side - 1):
            editor.add_cell(cell_count, v[i][j], v[i][j+1], v[i+1][j])
            cell_count += 1

            editor.add_cell(cell_count, v[i][j+1], v[i+1][j], v[i+1][j+1])
            cell_count += 1

    editor.close()

    return mesh