Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion adapt_common/mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import firedrake as fd
import ufl

__all__ = ["cell_volume", "patch_volume"]
__all__ = [
"cell_volume",
"patch_volume",
]


# TODO: Upstream as a cached_property of MeshGeometry in Firedrake (#17)
Expand Down Expand Up @@ -32,3 +35,23 @@ def patch_volume(mesh):
"""
patch_vol = fd.Function(fd.FunctionSpace(mesh, "Lagrange", 1))
return patch_vol.interpolate(ufl.CellVolume(mesh), access=fd.INC)


def _boundary_submesh(mesh, surface_id):
"""Construct a submesh of the boundary facets of a mesh.

:arg mesh: the mesh to take the boundary submesh of
:type mesh: :class:`firedrake.mesh.MeshGeometry`
:arg surface_id: the boundary facet marker to submesh, or None for all
exterior facets ("on_boundary")
:type surface_id: str or tuple[int]
:return: the boundary submesh
:rtype: :class:`firedrake.mesh.MeshGeometry`
"""
if mesh.topological_dimension < 2:
raise ValueError(
"Boundary Clement interpolation is not supported in 1D: "
"boundary facets are points and Submesh is not defined for them."
)
subdomain_id = "on_boundary" if surface_id is None else surface_id
return fd.Submesh(mesh, subdomain_id=subdomain_id)
69 changes: 67 additions & 2 deletions adapt_common/transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import ufl
from firedrake.petsc import PETSc

from adapt_common.mesh import patch_volume
from adapt_common.mesh import _boundary_submesh, patch_volume
from adapt_common.utility import (
cofunction2function,
function2cofunction,
get_function_space,
)

__all__ = ["clement_interpolant"]
__all__ = ["clement_interpolant", "clement_interpolant_boundary"]


def _process_source(source):
Expand Down Expand Up @@ -137,3 +137,68 @@ def clement_interpolant(source, target=None):
if is_cofunction:
return function2cofunction(target)
return target


@PETSc.Log.EventDecorator()
def clement_interpolant_boundary(source, target=None, surface_id=None):
r"""Compute the Clement interpolant of a :math:`\mathbb P0` source field on the
domain boundary.

i.e. take the volume average over neighbouring boundary facets at each vertex.
This is done by constructing a submesh of the boundary facets, applying the
volume :func:`clement_interpolant` on that submesh (where each boundary facet
is a cell, so corner elements are single-valued), and interpolating the result
back onto the volume mesh.

When `target` is None, the target's shape is inferred from the source space. If the
user requested a dual/cofunction target, a Cofunction will be returned; otherwise a
Function is returned.

:arg source: the :math:`\mathbb P0` source field or dual equivalent
:type source: :class:`firedrake.function.Function` or
:class:`firedrake.cofunction.Cofunction`
:arg target: the target function, function space, cofunction, dual space, or None
:type target: :class:`firedrake.function.Function`,
:class:`firedrake.functionspaceimpl.FunctionSpace`,
:class:`firedrake.cofunction.Counction`,
:class:`firedrake.functionspaceimpl.FiredrakeDualSpace`, or None
:kwarg surface_id: boundary facet marker to interpolate over, or None for all
exterior facets ("on_boundary")
:type surface_id: str or tuple[int]
:return: the interpolated :math:`\mathbb P1` field
:rtype: :class:`firedrake.function.Function` or
:class:`firedrake.cofunction.Cofunction`
"""
if isinstance(source, fd.Cofunction):
source = cofunction2function(source)
Vs = _process_source(source)
mesh = Vs.mesh()
target, is_cofunction = _process_target(Vs, target)
rank = len(Vs.value_shape)
if rank not in (0, 1, 2):
raise ValueError(f"Rank-{rank} tensors are not supported.")

# Transfer the source onto a P0 space on the boundary submesh, where each
# boundary facet is a cell
submesh = _boundary_submesh(mesh, surface_id)
source_sub = fd.Function(get_function_space(submesh, "DG", 0, Vs.value_shape))
source_sub.interpolate(source)

# Volume Clement interpolant on the submesh gives a P1 field on the boundary
target_sub = clement_interpolant(source_sub)

# Interpolate back onto the P1 target on the volume mesh. Degrees of freedom not
# defined on the submesh are left unchanged, so zero the target first; the
# interpolation is evaluated per parent cell, so boundary-adjacent cells
# leak submesh values into interior dofs - mask with a boundary indicator
target.assign(0)
target.interpolate(target_sub, allow_missing_dofs=True)
P1 = fd.FunctionSpace(mesh, "Lagrange", 1)
indicator = fd.Function(P1)
fd.DirichletBC(P1, 1, "on_boundary").apply(indicator)
target.interpolate(target * indicator)

# Map back to Cofunction, if one is requested or was passed originally
if is_cofunction:
return function2cofunction(target)
return target
109 changes: 108 additions & 1 deletion test/test_transfer_clement.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytest
import ufl

from adapt_common.transfer import clement_interpolant
from adapt_common.transfer import clement_interpolant, clement_interpolant_boundary
from adapt_common.utility import cofunction2function, get_function_space


Expand Down Expand Up @@ -156,3 +156,110 @@ def test_volume_average(P0, P1, expression):
def test_volume_average_parallel(P0, P1, expression):
"""Run the Clement interpolation volume average test with MPI parallelism."""
test_volume_average(P0, P1, expression)


def test_facet_average(n, uniform_mesh, shape, P0):
"""Test Clement interpolation over the boundary facets of a uniform mesh."""
if uniform_mesh.topological_dimension == 1:
pytest.skip("Boundary facet average is not supported in 1D.")
x = fd.SpatialCoordinate(uniform_mesh)
if len(shape) == 0:
exact = sum(x)
elif len(shape) == 1:
dim = shape[0]
exact = ufl.as_vector(
x if dim == uniform_mesh.topological_dimension else [x[0]] * dim
)
else:
exact = ufl.as_tensor(
[[sum(x) + i * j for j in range(shape[1])] for i in range(shape[0])]
)
source = fd.Function(P0).project(exact)
target = clement_interpolant_boundary(source)

# Check approximate recovery away from the corners of the domain (corner
# facets carry genuine discretisation error for P0 data). On the boundary
# submesh each boundary facet is a single-valued cell, so corner elements do not
# suffer from the multiple-exterior-facet ambiguity of a ds-based patch volume
h = 1.0 / n
corner = ufl.Or(x[0] < h, x[0] > 1 - h)
for i in range(1, len(x)):
corner = ufl.Or(corner, ufl.Or(x[i] < h, x[i] > 1 - h))
integrand = ufl.conditional(corner, 0, 1) * ufl.inner(
target - source, target - source
)
assert fd.assemble(integrand * ufl.ds) < 5e-3

# Interior degrees of freedom are not defined on the boundary submesh and are
# zeroed
P1 = get_function_space(uniform_mesh, "CG", 1, ())
indicator = fd.Function(P1)
fd.DirichletBC(P1, 1, "on_boundary").apply(indicator)
np.testing.assert_almost_equal(target.dat.data[indicator.dat.data == 0], 0.0)


def test_facet_average_surface_id(n):
"""Test Clement interpolation restricted to an explicitly requested boundary."""
mesh = fd.UnitSquareMesh(n, n)
x = fd.SpatialCoordinate(mesh)
exact = sum(x)
source = fd.Function(fd.FunctionSpace(mesh, "DG", 0)).project(exact)
# Explicitly request the whole exterior boundary by marker name
target = clement_interpolant_boundary(source, surface_id="on_boundary")
coords = np.asarray(mesh.coordinates.dat.data)
on_boundary = np.any(np.isclose(coords, 0.0) | np.isclose(coords, 1.0), axis=1)
# Boundary vertices get boundary averages of the source
assert np.all(target.dat.data[on_boundary] >= 0.0)
# Interior vertices are zero
np.testing.assert_almost_equal(target.dat.data[~on_boundary], 0.0)


@pytest.fixture(params=[2, 3], ids=["2D", "3D"])
def corner_mesh(request):
"""Create a uniform unit hypercube mesh with a corner element at the origin."""
n = 4
return {
2: fd.UnitSquareMesh(n, n, reorder=False),
3: fd.UnitCubeMesh(n, n, n, reorder=False),
}[request.param]


def test_facet_average_corner_exact(corner_mesh):
"""Test that a corner vertex receives the single-valued corner element average.

Corner cells have multiple exterior facets (2 in 2D, 3 in 3D); on the boundary
submesh each is a single cell, so the vertex value must be exactly the corner
element's P0 value rather than a facet-length-weighted mix. For a linear
source on a uniform mesh of size h the corner cell value is the cell average
of sum(x): 2h/3 in 2D and 3h/2 in 3D (the 8 corner tets each span 3h in
sum(x) at their far vertex).
"""
mesh = corner_mesh
n = 4
h = 1.0 / n
x = fd.SpatialCoordinate(mesh)
source = fd.Function(fd.FunctionSpace(mesh, "DG", 0)).project(sum(x))
target = clement_interpolant_boundary(source)
coords = np.asarray(mesh.coordinates.dat.data)
corner = np.where((coords == 0.0).all(axis=1))[0][0]
expected = (2 * h / 3) if mesh.topological_dimension == 2 else (3 * h / 2)
np.testing.assert_almost_equal(target.dat.data[corner], expected)


def test_facet_average_corner_indicator(corner_mesh):
"""Test that a corner element's indicator value reaches the corner vertex once.

With a ds-based patch volume a corner cell (multiple exterior facets) was
counted once per facet; on the boundary submesh it is a single cell, so a P0
indicator in the corner element gives exactly 1 at the corner vertex.
"""
mesh = corner_mesh
x = fd.SpatialCoordinate(mesh)
threshold = 0.3 if mesh.topological_dimension == 2 else 0.4
source = fd.Function(fd.FunctionSpace(mesh, "DG", 0)).project(
ufl.conditional(ufl.lt(sum(x), threshold), 1.0, 0.0)
)
target = clement_interpolant_boundary(source)
coords = np.asarray(mesh.coordinates.dat.data)
corner = np.where((coords == 0.0).all(axis=1))[0][0]
np.testing.assert_almost_equal(target.dat.data[corner], 1.0)
Loading