File: test_element_integrals.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 (637 lines) | stat: -rw-r--r-- 24,308 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# Copyright (C) 2009-2020 Garth N. Wells, Matthew W. Scroggs and Jorgen S. Dokken
#
# This file is part of DOLFINx (https://www.fenicsproject.org)
#
# SPDX-License-Identifier:    LGPL-3.0-or-later
"""Unit tests for the fem interface"""

import random
from itertools import combinations, product

from mpi4py import MPI

import numpy as np
import pytest

import dolfinx
import ufl
from basix.ufl import element
from dolfinx.fem import (
    Constant,
    Function,
    assemble_matrix,
    assemble_scalar,
    assemble_vector,
    form,
    functionspace,
)
from dolfinx.mesh import CellType, create_mesh, meshtags

parametrize_cell_types = pytest.mark.parametrize(
    "cell_type",
    [
        CellType.interval,
        CellType.triangle,
        CellType.tetrahedron,
        CellType.quadrilateral,
        CellType.hexahedron,
    ],
)

parametrize_dtypes = pytest.mark.parametrize(
    "dtype",
    [
        np.float32,
        np.float64,
        pytest.param(np.complex64, marks=pytest.mark.xfail_win32_complex),
        pytest.param(np.complex128, marks=pytest.mark.xfail_win32_complex),
    ],
)


def unit_cell_points(cell_type, dtype):
    if cell_type == CellType.interval:
        return np.array([[0.0], [1.0]], dtype=dtype)
    if cell_type == CellType.triangle:
        # Define equilateral triangle with area 1
        root = 3**0.25  # 4th root of 3
        return np.array([[0.0, 0.0], [2 / root, 0.0], [1 / root, root]], dtype=dtype)
    if cell_type == CellType.tetrahedron:
        # Define regular tetrahedron with volume 1
        s = 2**0.5 * 3 ** (1 / 3)  # side length
        return np.array(
            [
                [0.0, 0.0, 0.0],
                [s, 0.0, 0.0],
                [s / 2, s * np.sqrt(3) / 2, 0.0],
                [s / 2, s / 2 / np.sqrt(3), s * np.sqrt(2 / 3)],
            ],
            dtype=dtype,
        )
    elif cell_type == CellType.quadrilateral:
        # Define unit quadrilateral (area 1)
        return np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=dtype)
    elif cell_type == CellType.hexahedron:
        # Define unit hexahedron (volume 1)
        return np.array(
            [
                [0.0, 0.0, 0.0],
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [1.0, 1.0, 0.0],
                [0.0, 0.0, 1.0],
                [1.0, 0.0, 1.0],
                [0.0, 1.0, 1.0],
                [1.0, 1.0, 1.0],
            ],
            dtype=dtype,
        )


def unit_cell(cell_type, dtype, random_order=True):
    points = unit_cell_points(cell_type, dtype)
    num_points = len(points)

    # Randomly number the points and create the mesh
    order = list(range(num_points))
    if random_order:
        random.shuffle(order)
    ordered_points = np.zeros(points.shape, dtype=dtype)
    for i, j in enumerate(order):
        ordered_points[j] = points[i]
    cells = np.array([order])

    domain = ufl.Mesh(
        element("Lagrange", cell_type.name, 1, shape=(ordered_points.shape[1],), dtype=dtype)
    )
    mesh = create_mesh(MPI.COMM_WORLD, cells, ordered_points, domain)
    return mesh


def two_unit_cells(cell_type, dtype, agree=False, random_order=True, return_order=False):
    if cell_type == CellType.interval:
        points = np.array([[0.0], [1.0], [-1.0]], dtype=dtype)
        if agree:
            cells = [[0, 1], [2, 0]]
        else:
            cells = [[0, 1], [0, 2]]
    if cell_type == CellType.triangle:
        # Define equilateral triangles with area 1
        root = 3**0.25  # 4th root of 3
        points = np.array(
            [[0.0, 0.0], [2 / root, 0.0], [1 / root, root], [1 / root, -root]], dtype=dtype
        )
        if agree:
            cells = [[0, 1, 2], [0, 3, 1]]
        else:
            cells = [[0, 1, 2], [1, 0, 3]]
    elif cell_type == CellType.tetrahedron:
        # Define regular tetrahedra with volume 1
        s = 2**0.5 * 3 ** (1 / 3)  # side length
        points = np.array(
            [
                [0.0, 0.0, 0.0],
                [s, 0.0, 0.0],
                [s / 2, s * np.sqrt(3) / 2, 0.0],
                [s / 2, s / 2 / np.sqrt(3), s * np.sqrt(2 / 3)],
                [s / 2, s / 2 / np.sqrt(3), -s * np.sqrt(2 / 3)],
            ],
            dtype=dtype,
        )
        if agree:
            cells = [[0, 1, 2, 3], [0, 1, 4, 2]]
        else:
            cells = [[0, 1, 2, 3], [0, 2, 1, 4]]
    elif cell_type == CellType.quadrilateral:
        # Define unit quadrilaterals (area 1)
        points = np.array(
            [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, -1.0], [1.0, -1.0]], dtype=dtype
        )
        if agree:
            cells = [[0, 1, 2, 3], [4, 5, 0, 1]]
        else:
            cells = [[0, 1, 2, 3], [5, 1, 4, 0]]
    elif cell_type == CellType.hexahedron:
        # Define unit hexahedra (volume 1)
        points = np.array(
            [
                [0.0, 0.0, 0.0],
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [1.0, 1.0, 0.0],
                [0.0, 0.0, 1.0],
                [1.0, 0.0, 1.0],
                [0.0, 1.0, 1.0],
                [1.0, 1.0, 1.0],
                [0.0, 0.0, -1.0],
                [1.0, 0.0, -1.0],
                [0.0, 1.0, -1.0],
                [1.0, 1.0, -1.0],
            ],
            dtype=dtype,
        )
        if agree:
            cells = [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 0, 1, 2, 3]]
        else:
            cells = [[0, 1, 2, 3, 4, 5, 6, 7], [9, 11, 8, 10, 1, 3, 0, 2]]
    num_points = len(points)

    # Randomly number the points and create the mesh
    order = list(range(num_points))
    if random_order:
        random.shuffle(order)
    ordered_points = np.zeros(points.shape, dtype=dtype)
    for i, j in enumerate(order):
        ordered_points[j] = points[i]
    ordered_cells = np.array([[order[i] for i in c] for c in cells])

    domain = ufl.Mesh(
        element("Lagrange", cell_type.name, 1, shape=(ordered_points.shape[1],), dtype=dtype)
    )
    mesh = create_mesh(MPI.COMM_WORLD, ordered_cells, ordered_points, domain)
    if return_order:
        return mesh, order
    return mesh


@pytest.mark.skip_in_parallel
@parametrize_cell_types
@parametrize_dtypes
def test_facet_integral(cell_type, dtype):
    """Test that the integral of a function over a facet is correct"""
    xtype = np.real(dtype(0)).dtype
    for count in range(5):
        mesh = unit_cell(cell_type, xtype)
        tdim = mesh.topology.dim

        V = functionspace(mesh, ("Lagrange", 2))
        v = Function(V, dtype=dtype)

        mesh.topology.create_entities(tdim - 1)
        map_f = mesh.topology.index_map(tdim - 1)
        num_facets = map_f.size_local + map_f.num_ghosts
        indices = np.arange(0, num_facets)
        values = np.arange(0, num_facets, dtype=np.int32)
        marker = meshtags(mesh, tdim - 1, indices, values)

        # Functions that will have the same integral over each facet
        if cell_type == CellType.triangle:
            root = 3**0.25  # 4th root of 3
            v.interpolate(lambda x: (x[0] - 1 / root) ** 2 + (x[1] - root / 3) ** 2)
        elif cell_type == CellType.quadrilateral:
            v.interpolate(lambda x: x[0] * (1 - x[0]) + x[1] * (1 - x[1]))
        elif cell_type == CellType.tetrahedron:
            s = 2**0.5 * 3 ** (1 / 3)  # side length
            v.interpolate(
                lambda x: (x[0] - s / 2) ** 2
                + (x[1] - s / 2 / np.sqrt(3)) ** 2
                + (x[2] - s * np.sqrt(2 / 3) / 4) ** 2
            )
        elif cell_type == CellType.hexahedron:
            v.interpolate(lambda x: x[0] * (1 - x[0]) + x[1] * (1 - x[1]) + x[2] * (1 - x[2]))

        # Check that integral of these functions over each face are
        # equal
        mesh.topology.create_connectivity(tdim - 1, tdim)
        mesh.topology.create_connectivity(tdim, tdim - 1)
        out = []
        for j in range(num_facets):
            a = form(v * ufl.ds(subdomain_data=marker, subdomain_id=j), dtype=dtype)
            result = assemble_scalar(a)
            out.append(result)
            assert np.isclose(result, out[0], atol=np.finfo(dtype).eps)


@pytest.mark.skip_in_parallel
@parametrize_cell_types
@parametrize_dtypes
def test_facet_normals(cell_type, dtype):
    """Test that FacetNormal is outward facing"""
    xtype = np.real(dtype(0)).dtype
    for count in range(5):
        mesh = unit_cell(cell_type, xtype)
        tdim = mesh.topology.dim
        mesh.topology.create_entities(tdim - 1)

        gdim = mesh.geometry.dim
        V = functionspace(mesh, ("Lagrange", 1, (gdim,)))
        normal = ufl.FacetNormal(mesh)
        v = Function(V, dtype=dtype)

        mesh.topology.create_entities(tdim - 1)
        map_f = mesh.topology.index_map(tdim - 1)
        num_facets = map_f.size_local + map_f.num_ghosts
        indices = np.arange(0, num_facets)
        values = np.arange(0, num_facets, dtype=np.int32)
        marker = meshtags(mesh, tdim - 1, indices, values)

        # For each facet, check that the inner product of the normal and
        # the vector that has a positive normal component on only that
        # facet is positive
        for i in range(num_facets):
            if cell_type == CellType.interval:
                co = mesh.geometry.x[i]
                v.interpolate(lambda x: x[0] - co[0])
            if cell_type == CellType.triangle:
                co = mesh.geometry.x[i]
                # Vector function that is zero at `co` and points away
                # from `co` so that there is no normal component on two
                # edges and the integral over the other edge is 1
                v.interpolate(lambda x: ((x[0] - co[0]) / 2, (x[1] - co[1]) / 2))
            elif cell_type == CellType.tetrahedron:
                co = mesh.geometry.x[i]
                # Vector function that is zero at `co` and points away
                # from `co` so that there is no normal component on
                # three faces and the integral over the other edge is 1
                v.interpolate(
                    lambda x: ((x[0] - co[0]) / 3, (x[1] - co[1]) / 3, (x[2] - co[2]) / 3)
                )
            elif cell_type == CellType.quadrilateral:
                # function that is 0 on one edge and points away from
                # that edge so that there is no normal component on
                # three edges
                v.interpolate(
                    lambda x: tuple(x[j] - i % 2 if j == i // 2 else 0 * x[j] for j in range(2))
                )
            elif cell_type == CellType.hexahedron:
                # function that is 0 on one face and points away from
                # that face so that there is no normal component on five
                # faces
                v.interpolate(
                    lambda x: tuple(x[j] - i % 2 if j == i // 3 else 0 * x[j] for j in range(3))
                )

            # Check that integrals these functions dotted with the
            # normal over a face is 1 on one face and 0 on the others
            ones = 0
            for j in range(num_facets):
                a = form(
                    ufl.inner(v, normal) * ufl.ds(subdomain_data=marker, subdomain_id=j),
                    dtype=dtype,
                )
                result = assemble_scalar(a)
                if np.isclose(result, 1, atol=np.finfo(dtype).eps):
                    ones += 1
                else:
                    assert np.isclose(result, 0, atol=1.0e-6)
            assert ones == 1


@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("space_type", ["Lagrange", "DG"])
@parametrize_cell_types
@parametrize_dtypes
def test_plus_minus(cell_type, space_type, dtype):
    """Test that ('+') and ('-') give the same value for continuous functions"""
    xtype = np.real(dtype(0)).dtype
    results = []
    for count in range(3):
        for agree in [True, False]:
            mesh = two_unit_cells(cell_type, xtype, agree)
            V = functionspace(mesh, (space_type, 1))
            v = Function(V, dtype=dtype)
            v.interpolate(lambda x: x[0] - 2 * x[1])
            # Check that these two integrals are equal
            for pm1, pm2 in product(["+", "-"], repeat=2):
                a = form(v(pm1) * v(pm2) * ufl.dS, dtype=dtype)
                results.append(assemble_scalar(a))
    for i, j in combinations(results, 2):
        assert np.isclose(i, j, atol=np.finfo(dtype).eps)


@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("pm", ["+", "-"])
@parametrize_cell_types
@parametrize_dtypes
def test_plus_minus_simple_vector(cell_type, pm, dtype):
    """Test that ('+') and ('-') match up with the correct DOFs for DG functions"""
    xtype = np.real(dtype(0)).dtype
    results = []
    orders = []
    spaces = []
    for count in range(3):
        for agree in [True, False]:
            # Two cell mesh with randomly numbered points
            mesh, order = two_unit_cells(cell_type, xtype, agree, return_order=True)
            if cell_type in [CellType.interval, CellType.triangle, CellType.tetrahedron]:
                V = functionspace(mesh, ("DG", 1))
            else:
                V = functionspace(mesh, ("DQ", 1))

            # Assemble vectors v['+'] * dS and v['-'] * dS for a few
            # different numberings
            v = ufl.TestFunction(V)
            a = form(ufl.inner(1.0, v(pm)) * ufl.dS, dtype=dtype)
            result = assemble_vector(a)
            spaces.append(V)
            results.append(result.array)
            orders.append(order)

    # Check that the above vectors all have the same values as the first
    # one, but permuted due to differently ordered dofs
    dofmap0 = spaces[0].mesh.geometry.dofmap
    for result, space in zip(results[1:], spaces[1:]):
        # Get the data relating to two results
        dofmap1 = space.mesh.geometry.dofmap

        # For each cell
        for cell in range(2):
            # For each point in cell 0 in the first mesh
            for dof0, point0 in zip(spaces[0].dofmap.cell_dofs(cell), dofmap0[cell]):
                # Find the point in the cell 0 in the second mesh
                for dof1, point1 in zip(space.dofmap.cell_dofs(cell), dofmap1[cell]):
                    if np.allclose(
                        spaces[0].mesh.geometry.x[point0], space.mesh.geometry.x[point1]
                    ):
                        break
                else:
                    # If no matching point found, fail
                    assert False

                assert np.isclose(results[0][dof0], result[dof1], atol=np.finfo(dtype).eps)


@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("pm1", ["+", "-"])
@pytest.mark.parametrize("pm2", ["+", "-"])
@parametrize_cell_types
@parametrize_dtypes
def test_plus_minus_vector(cell_type, pm1, pm2, dtype):
    """Test that ('+') and ('-') match up with the correct DOFs for DG functions"""
    xtype = np.real(dtype(0)).dtype
    results = []
    orders = []
    spaces = []
    for count in range(3):
        for agree in [True, False]:
            # Two cell mesh with randomly numbered points
            mesh, order = two_unit_cells(cell_type, xtype, agree, return_order=True)
            if cell_type in [CellType.interval, CellType.triangle, CellType.tetrahedron]:
                V = functionspace(mesh, ("DG", 1))
            else:
                V = functionspace(mesh, ("DQ", 1))

            # Assemble vectors with combinations of + and - for a few
            # different numberings
            f = Function(V, dtype=dtype)
            f.interpolate(lambda x: x[0] - 2 * x[1])
            v = ufl.TestFunction(V)
            a = form(ufl.inner(f(pm1), v(pm2)) * ufl.dS, dtype=dtype)
            result = assemble_vector(a)
            spaces.append(V)
            results.append(result.array)
            orders.append(order)

    # Check that the above vectors all have the same values as the first
    # one, but permuted due to differently ordered dofs
    dofmap0 = spaces[0].mesh.geometry.dofmap
    for result, space in zip(results[1:], spaces[1:]):
        # Get the data relating to two results
        dofmap1 = space.mesh.geometry.dofmap

        # For each cell
        for cell in range(2):
            # For each point in cell 0 in the first mesh
            for dof0, point0 in zip(spaces[0].dofmap.cell_dofs(cell), dofmap0[cell]):
                # Find the point in the cell 0 in the second mesh
                for dof1, point1 in zip(space.dofmap.cell_dofs(cell), dofmap1[cell]):
                    if np.allclose(
                        spaces[0].mesh.geometry.x[point0], space.mesh.geometry.x[point1]
                    ):
                        break
                else:
                    # If no matching point found, fail
                    assert False

                assert np.isclose(results[0][dof0], result[dof1], atol=1.0e-6)


@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("pm1", ["+", "-"])
@pytest.mark.parametrize("pm2", ["+", "-"])
@parametrize_cell_types
@parametrize_dtypes
def test_plus_minus_matrix(cell_type, pm1, pm2, dtype):
    """Test that ('+') and ('-') match up with the correct DOFs for DG functions"""
    xtype = np.real(dtype(0)).dtype
    results = []
    spaces = []
    orders = []
    for count in range(3):
        for agree in [True, False]:
            # Two cell mesh with randomly numbered points
            mesh, order = two_unit_cells(cell_type, xtype, agree, return_order=True)
            V = functionspace(mesh, ("DG", 1))
            u, v = ufl.TrialFunction(V), ufl.TestFunction(V)

            # Assemble matrices with combinations of + and - for a few
            # different numberings
            a = form(ufl.inner(u(pm1), v(pm2)) * ufl.dS, dtype=dtype)
            result = assemble_matrix(a, [])
            result.scatter_reverse()
            spaces.append(V)
            results.append(result.to_dense())
            orders.append(order)

    # Check that the above matrices all have the same values, but
    # permuted due to differently ordered dofs
    dofmap0 = spaces[0].mesh.geometry.dofmap
    for result, space in zip(results[1:], spaces[1:]):
        # Get the data relating to two results
        dofmap1 = space.mesh.geometry.dofmap
        dof_order = []

        # For each cell
        for cell in range(2):
            # For each point in cell 0 in the first mesh
            for dof0, point0 in zip(spaces[0].dofmap.cell_dofs(cell), dofmap0[cell]):
                # Find the point in the cell 0 in the second mesh
                for dof1, point1 in zip(space.dofmap.cell_dofs(cell), dofmap1[cell]):
                    if np.allclose(
                        spaces[0].mesh.geometry.x[point0], space.mesh.geometry.x[point1]
                    ):
                        break
                else:
                    # If no matching point found, fail
                    assert False

                dof_order.append((dof0, dof1))

        # For all dof pairs, check that entries in the matrix agree
        for a, b in dof_order:
            for c, d in dof_order:
                assert np.isclose(results[0][a, c], result[b, d], atol=np.finfo(dtype).eps)


@pytest.mark.skip(
    reason="Test needs replacing because it assumes the mesh constructor doesn't re-order points."
)
@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("order", [1, 2])
@pytest.mark.parametrize("space_type", ["N1curl", "N2curl"])
@parametrize_dtypes
def test_curl(space_type, order, dtype):
    """Test that curl is consistent for different cell permutations of a tetrahedron."""
    xtype = np.real(dtype(0)).dtype
    tdim = dolfinx.mesh.cell_dim(CellType.tetrahedron)
    points = unit_cell_points(CellType.tetrahedron, xtype)

    spaces = []
    results = []
    cell = list(range(len(points)))
    random.seed(2)

    # Assemble vector on 5 randomly numbered cells
    for i in range(5):
        random.shuffle(cell)
        domain = ufl.Mesh(element("Lagrange", "tetrahedron", 1, shape=(3,), dtype=dtype))
        mesh = create_mesh(MPI.COMM_WORLD, [cell], points, domain)
        V = functionspace(mesh, (space_type, order))
        v = ufl.TestFunction(V)
        f = ufl.as_vector(tuple(1 if i == 0 else 0 for i in range(tdim)))
        L = form(ufl.inner(f, ufl.curl(v)) * ufl.dx)
        result = assemble_vector(L)
        spaces.append(V)
        results.append(result.array)

    # Set data for first space
    V0 = spaces[0]
    c10_0 = V.mesh.topology.connectivity(1, 0)

    # Check that all DOFs on edges agree

    # Loop over cell edges
    for i, edge in enumerate(V0.mesh.topology.connectivity(tdim, 1).links(0)):
        # Get the edge vertices
        vertices0 = c10_0.links(edge)  # Need to map back

        # Get assembled values on edge
        values0 = sorted(
            [result[V0.dofmap.cell_dofs(0)[a]] for a in V0.dofmap.dof_layout.entity_dofs(1, i)]
        )

        for V, result in zip(spaces[1:], results[1:]):
            # Get edge->vertex connectivity
            c10 = V.mesh.topology.connectivity(1, 0)

            # Loop over cell edges
            for j, e in enumerate(V.mesh.topology.connectivity(tdim, 1).links(0)):
                if sorted(c10.links(e)) == sorted(vertices0):  # need to map back c.links(e)
                    values = sorted(
                        [
                            result[V.dofmap.cell_dofs(0)[a]]
                            for a in V.dofmap.dof_layout.entity_dofs(1, j)
                        ]
                    )
                    assert np.allclose(values0, values)
                    break
            else:
                continue
            break


def create_quad_mesh(offset, dtype):
    """Creates a mesh of a single square element if offset = 0, or a
    trapezium element if |offset| > 0."""
    x = np.array([[0, 0], [1, 0], [0, 0.5 + offset], [1, 0.5 - offset]], dtype=dtype)
    cells = np.array([[0, 1, 2, 3]])
    ufl_mesh = ufl.Mesh(element("Lagrange", "quadrilateral", 1, shape=(2,), dtype=dtype))
    mesh = create_mesh(MPI.COMM_WORLD, cells, x, ufl_mesh)
    return mesh


@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("k", [0, 1, 2])
@parametrize_dtypes
def test_div_general_quads_mat(k, dtype):
    """Tests that assembling inner(u, div(w)) * dx, where u is from a
    "DQ" space and w is from an "RTCF" space, gives the same matrix for
    square and trapezoidal elements. This should be the case due to the
    properties of the Piola transform."""
    # Assemble matrix on a mesh of square elements and on a mesh of
    # trapezium elements
    xtype = np.real(dtype(0)).dtype

    def assemble_div_matrix(k, offset):
        mesh = create_quad_mesh(offset, dtype=xtype)
        V = functionspace(mesh, ("DQ", k))
        W = functionspace(mesh, ("RTCF", k + 1))
        u, w = ufl.TrialFunction(V), ufl.TestFunction(W)
        a = form(ufl.inner(u, ufl.div(w)) * ufl.dx, dtype=dtype)
        A = assemble_matrix(a)
        return A.to_dense()

    A_square = assemble_div_matrix(k, 0)
    A_trap = assemble_div_matrix(k, 0.25)

    # Due to the properties of the Piola transform, A_square and A_trap
    # should be equal
    assert np.allclose(A_square, A_trap, atol=1e-6)


@pytest.mark.skip_in_parallel
@pytest.mark.parametrize("k", [0, 1, 2])
@parametrize_dtypes
def test_div_general_quads_vec(k, dtype):
    """Tests that assembling inner(1, div(w)) * dx, where w is from an
    "RTCF" space, gives the same matrix for square and trapezoidal
    elements. This should be the case due to the properties of the Piola
    transform."""
    # Assemble vector on a mesh of square elements and on a mesh of
    # trapezium elements
    xtype = np.real(dtype(0)).dtype

    def assemble_div_vector(k, offset):
        mesh = create_quad_mesh(offset, dtype=xtype)
        V = functionspace(mesh, ("RTCF", k + 1))
        v = ufl.TestFunction(V)
        L = form(ufl.inner(Constant(mesh, dtype(1)), ufl.div(v)) * ufl.dx, dtype=dtype)
        b = assemble_vector(L)
        return b.array

    L_square = assemble_div_vector(k, 0)
    L_trap = assemble_div_vector(k, 0.25)

    # Due to the properties of the Piola transform, L_square and L_trap
    # should be equal
    assert np.allclose(L_square, L_trap, atol=1e-5)