File: test_custom_basix_element.py

package info (click to toggle)
fenics-dolfinx 1%3A0.9.0-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,376 kB
  • sloc: cpp: 33,701; python: 22,338; makefile: 230; sh: 170; xml: 55
file content (369 lines) | stat: -rw-r--r-- 11,087 bytes parent folder | download | duplicates (2)
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
# Copyright (C) 2024 Matthew W. Scroggs Garth N. Wells
#
# This file is part of DOLFINx (https://www.fenicsproject.org)
#
# SPDX-License-Identifier:    LGPL-3.0-or-later

from mpi4py import MPI

import numpy as np
import pytest

import basix
import basix.ufl
import ufl
from dolfinx import default_real_type, la
from dolfinx.fem import (
    Function,
    apply_lifting,
    assemble_matrix,
    assemble_scalar,
    assemble_vector,
    dirichletbc,
    form,
    functionspace,
    locate_dofs_topological,
)
from dolfinx.mesh import CellType, create_unit_cube, create_unit_square, exterior_facet_indices
from ufl import SpatialCoordinate, TestFunction, TrialFunction, div, dx, grad, inner


def run_scalar_test(V, degree, dtype, cg_solver, rtol=None):
    mesh = V.mesh
    u, v = TrialFunction(V), TestFunction(V)
    a = inner(grad(u), grad(v)) * dx

    # Get quadrature degree for bilinear form integrand (ignores effect of non-affine map)
    a = inner(grad(u), grad(v)) * dx(metadata={"quadrature_degree": -1})
    a.integrals()[0].metadata()["quadrature_degree"] = (
        ufl.algorithms.estimate_total_polynomial_degree(a)
    )
    a = form(a, dtype=dtype)

    # Source term
    x = SpatialCoordinate(mesh)
    u_exact = x[1] ** degree
    f = -div(grad(u_exact))

    # Set quadrature degree for linear form integrand (ignores effect of non-affine map)
    L = inner(f, v) * dx(metadata={"quadrature_degree": -1})
    L.integrals()[0].metadata()["quadrature_degree"] = (
        ufl.algorithms.estimate_total_polynomial_degree(L)
    )
    L = form(L, dtype=dtype)

    u_bc = Function(V, dtype=dtype)
    u_bc.interpolate(lambda x: x[1] ** degree)

    # Create Dirichlet boundary condition
    facetdim = mesh.topology.dim - 1
    mesh.topology.create_connectivity(facetdim, mesh.topology.dim)
    bndry_facets = exterior_facet_indices(mesh.topology)
    bdofs = locate_dofs_topological(V, facetdim, bndry_facets)
    bc = dirichletbc(u_bc, bdofs)

    b = assemble_vector(L)
    apply_lifting(b.array, [a], bcs=[[bc]])
    b.scatter_reverse(la.InsertMode.add)
    bc.set(b.array)

    a = form(a, dtype=dtype)
    A = assemble_matrix(a, bcs=[bc])
    A.scatter_reverse()

    uh = Function(V, dtype=dtype)
    cg_solver(mesh.comm, A, b, uh.x, rtol=rtol)
    uh.x.scatter_forward()

    M = (u_exact - uh) ** 2 * dx
    M = form(M, dtype=dtype)
    error = mesh.comm.allreduce(assemble_scalar(M), op=MPI.SUM)

    eps = np.sqrt(np.finfo(dtype).eps)
    assert np.isclose(error, 0, atol=eps)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize("degree", range(1, 6))
def test_basix_element_wrapper(degree, dtype, cg_solver):
    ufl_element = basix.ufl.element(
        basix.ElementFamily.P,
        basix.CellType.triangle,
        degree,
        basix.LagrangeVariant.gll_isaac,
        dtype=dtype,
    )
    mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, dtype=dtype)
    V = functionspace(mesh, ufl_element)
    run_scalar_test(V, degree, dtype, cg_solver)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
def test_custom_element_triangle_degree1(dtype, cg_solver):
    wcoeffs = np.eye(3)
    z = np.zeros((0, 2))
    x = [
        [np.array([[0.0, 0.0]]), np.array([[1.0, 0.0]]), np.array([[0.0, 1.0]])],
        [z, z, z],
        [z],
        [],
    ]
    z = np.zeros((0, 1, 0, 1))
    M = [[np.array([[[[1.0]]]]), np.array([[[[1.0]]]]), np.array([[[[1.0]]]])], [z, z, z], [z], []]
    ufl_element = basix.ufl.custom_element(
        basix.CellType.triangle,
        [],
        wcoeffs,
        x,
        M,
        0,
        basix.MapType.identity,
        basix.SobolevSpace.H1,
        False,
        1,
        1,
        dtype=dtype,
    )
    mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, dtype=dtype)
    V = functionspace(mesh, ufl_element)
    run_scalar_test(V, 1, dtype, cg_solver)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
def test_custom_element_triangle_degree4(dtype, cg_solver):
    wcoeffs = np.eye(15)
    x = [
        [np.array([[0.0, 0.0]]), np.array([[1.0, 0.0]]), np.array([[0.0, 1.0]])],
        [
            np.array([[0.75, 0.25], [0.5, 0.5], [0.25, 0.75]]),
            np.array([[0.0, 0.25], [0.0, 0.5], [0.0, 0.75]]),
            np.array([[0.25, 0.0], [0.5, 0.0], [0.75, 0.0]]),
        ],
        [np.array([[0.25, 0.25], [0.5, 0.25], [0.25, 0.5]])],
        [],
    ]
    id = np.array([[[[1.0], [0.0], [0.0]]], [[[0.0], [1.0], [0.0]]], [[[0.0], [0.0], [1.0]]]])
    M = [
        [np.array([[[[1.0]]]]), np.array([[[[1.0]]]]), np.array([[[[1.0]]]])],
        [id, id, id],
        [id],
        [],
    ]

    ufl_element = basix.ufl.custom_element(
        basix.CellType.triangle,
        [],
        wcoeffs,
        x,
        M,
        0,
        basix.MapType.identity,
        basix.SobolevSpace.H1,
        False,
        4,
        4,
        dtype=dtype,
    )
    mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, dtype=dtype)
    V = functionspace(mesh, ufl_element)
    run_scalar_test(V, 4, dtype, cg_solver)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
def test_custom_element_triangle_degree4_integral(dtype, cg_solver):
    pts, wts = basix.make_quadrature(basix.CellType.interval, 10)
    tab = basix.create_element(
        basix.ElementFamily.P, basix.CellType.interval, 2, dtype=default_real_type
    ).tabulate(0, pts)[0, :, :, 0]
    wcoeffs = np.eye(15)
    x = [
        [np.array([[0.0, 0.0]]), np.array([[1.0, 0.0]]), np.array([[0.0, 1.0]])],
        [
            np.array([[1.0 - p[0], p[0]] for p in pts]),
            np.array([[0.0, p[0]] for p in pts]),
            np.array([[p[0], 0.0] for p in pts]),
        ],
        [np.array([[0.25, 0.25], [0.5, 0.25], [0.25, 0.5]])],
        [],
    ]

    assert pts.shape[0] != 3
    quadrature_mat = np.zeros([3, 1, pts.shape[0], 1])
    for dof in range(3):
        for p in range(pts.shape[0]):
            quadrature_mat[dof, 0, p, 0] = wts[p] * tab[p, dof]

    M = [
        [np.array([[[[1.0]]]]), np.array([[[[1.0]]]]), np.array([[[[1.0]]]])],
        [quadrature_mat, quadrature_mat, quadrature_mat],
        [np.array([[[[1.0], [0.0], [0.0]]], [[[0.0], [1.0], [0.0]]], [[[0.0], [0.0], [1.0]]]])],
        [],
    ]

    ufl_element = basix.ufl.custom_element(
        basix.CellType.triangle,
        [],
        wcoeffs,
        x,
        M,
        0,
        basix.MapType.identity,
        basix.SobolevSpace.H1,
        False,
        4,
        4,
        dtype=dtype,
    )
    mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, dtype=dtype)
    V = functionspace(mesh, ufl_element)
    run_scalar_test(V, 4, dtype, cg_solver, rtol=1e-5)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
def test_custom_element_quadrilateral_degree1(dtype, cg_solver):
    wcoeffs = np.eye(4)
    z = np.zeros((0, 2))
    x = [
        [
            np.array([[0.0, 0.0]]),
            np.array([[1.0, 0.0]]),
            np.array([[0.0, 1.0]]),
            np.array([[1.0, 1.0]]),
        ],
        [z, z, z, z],
        [z],
        [],
    ]
    z = np.zeros((0, 1, 0, 1))
    M = [
        [
            np.array([[[[1.0]]]]),
            np.array([[[[1.0]]]]),
            np.array([[[[1.0]]]]),
            np.array([[[[1.0]]]]),
        ],
        [z, z, z, z],
        [z],
        [],
    ]
    ufl_element = basix.ufl.custom_element(
        basix.CellType.quadrilateral,
        [],
        wcoeffs,
        x,
        M,
        0,
        basix.MapType.identity,
        basix.SobolevSpace.H1,
        False,
        1,
        1,
        dtype=dtype,
    )
    mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, CellType.quadrilateral, dtype=dtype)
    V = functionspace(mesh, ufl_element)
    run_scalar_test(V, 1, dtype, cg_solver)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize(
    "cell_type",
    [CellType.triangle, CellType.quadrilateral, CellType.tetrahedron, CellType.hexahedron],
)
@pytest.mark.parametrize(
    "element_family",
    [
        basix.ElementFamily.N1E,
        basix.ElementFamily.N2E,
        basix.ElementFamily.RT,
        basix.ElementFamily.BDM,
    ],
)
def test_vector_copy_degree1(cell_type, element_family, dtype):
    if cell_type in [CellType.triangle, CellType.quadrilateral]:
        tdim = 2
        mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, cell_type, dtype=dtype)
    else:
        tdim = 3
        mesh = create_unit_cube(MPI.COMM_WORLD, 5, 5, 5, cell_type, dtype=dtype)

    def func(x):
        return x[:tdim]

    e1 = basix.ufl.element(element_family, getattr(basix.CellType, cell_type.name), 1, dtype=dtype)
    e2 = basix.ufl.custom_element(
        e1._element.cell_type,
        e1._element.value_shape,
        e1._element.wcoeffs,
        e1._element.x,
        e1._element.M,
        0,
        e1._element.map_type,
        e1._element.sobolev_space,
        e1._element.discontinuous,
        e1._element.embedded_subdegree,
        e1._element.embedded_superdegree,
        dtype=dtype,
    )

    space1 = functionspace(mesh, e1)
    space2 = functionspace(mesh, e2)

    f1 = Function(space1, dtype=dtype)
    f2 = Function(space2, dtype=dtype)
    f1.interpolate(func)
    f2.interpolate(func)

    diff = f1 - f2
    error = assemble_scalar(form(ufl.inner(diff, diff) * ufl.dx, dtype=dtype))
    assert np.isclose(error, 0)


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize(
    "cell_type",
    [CellType.triangle, CellType.quadrilateral, CellType.tetrahedron, CellType.hexahedron],
)
@pytest.mark.parametrize("element_family", [basix.ElementFamily.P, basix.ElementFamily.serendipity])
def test_scalar_copy_degree1(cell_type, element_family, dtype):
    if element_family == basix.ElementFamily.serendipity and cell_type in [
        CellType.triangle,
        CellType.tetrahedron,
    ]:
        pytest.xfail("Serendipity elements cannot be created on simplices")

    if cell_type in [CellType.triangle, CellType.quadrilateral]:
        mesh = create_unit_square(MPI.COMM_WORLD, 10, 10, cell_type, dtype=dtype)
    else:
        mesh = create_unit_cube(MPI.COMM_WORLD, 5, 5, 5, cell_type, dtype=dtype)

    def func(x):
        return x[0]

    e1 = basix.ufl.element(element_family, getattr(basix.CellType, cell_type.name), 1, dtype=dtype)
    e2 = basix.ufl.custom_element(
        e1._element.cell_type,
        e1._element.value_shape,
        e1._element.wcoeffs,
        e1._element.x,
        e1._element.M,
        0,
        e1._element.map_type,
        e1._element.sobolev_space,
        e1._element.discontinuous,
        e1._element.embedded_subdegree,
        e1._element.embedded_superdegree,
        dtype=dtype,
    )

    space1 = functionspace(mesh, e1)
    space2 = functionspace(mesh, e2)

    f1 = Function(space1, dtype=dtype)
    f2 = Function(space2, dtype=dtype)
    f1.interpolate(func)
    f2.interpolate(func)

    diff = f1 - f2
    error = assemble_scalar(form(ufl.inner(diff, diff) * ufl.dx, dtype=dtype))
    assert np.isclose(error, 0)