Skip to content
Merged
89 changes: 85 additions & 4 deletions adapt_common/recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,40 @@
import ufl
from firedrake.petsc import PETSc

__all__ = ["recover_gradient_l2"]
from adapt_common.transfer import clement_interpolant

__all__ = ["recover_gradient_l2", "recover_hessian_clement"]


@PETSc.Log.EventDecorator()
def recover_gradient(f, target_space=None, method="l2"):
r"""Recover the gradient of a scalar or vector field using the specified method.

:arg f: the scalar or vector field whose derivatives we seek to recover
:type f: :class:`firedrake.function.Function`
:kwarg target_space: the vector-valued function space to recover the gradient in
:type target_space: :class:`firedrake.functionspaceimpl.FunctionSpace`
:kwarg method: the recovery method to use
:type method: str
:returns: recovered gradient
:rtype: :class:`firedrake.function.Function`
"""
method = method.lower()
if method == "l2":
return recover_gradient_l2(f, target_space=target_space)
elif method == "clement":
return recover_gradient_clement(f, target_space=target_space)
elif method == "zz":
raise NotImplementedError("Zienkiewicz-Zhu recovery not yet implemented.")
raise NotImplementedError(f"Gradient recovery method '{method}' not recognised.")


@PETSc.Log.EventDecorator()
def recover_gradient_l2(f, target_space=None):
r"""Recover the gradient of a scalar or vector field using :math:`L^2` projection.

:arg f: the scalar field whose derivatives we seek to recover
:arg f: the scalar or vector field whose derivatives we seek to recover
:type f: :class:`firedrake.function.Function`
:kwarg mesh: the underlying mesh
:type mesh: :class:`firedrake.mesh.MeshGeometry`
:kwarg target_space: the vector-valued function space to recover the gradient in
:type target_space: :class:`firedrake.functionspaceimpl.FunctionSpace`
:returns: recovered gradient
Expand Down Expand Up @@ -51,3 +74,61 @@ def recover_gradient_l2(f, target_space=None):
raise ValueError(val_err)

return fd.project(ufl.grad(f), target_space)


@PETSc.Log.EventDecorator()
def recover_gradient_clement(f, target_space=None):
r"""
Recover the gradient of a scalar field using Clement interpolation.

Note that the field must be :math:`\mathbb P1`.

:arg f: the scalar field whose derivatives we seek to recover
:type f: :class:`firedrake.function.Function`
:kwarg target_space: the vector-valued function space to recover the gradient in
:type target_space: :class:`firedrake.functionspaceimpl.FunctionSpace`
:returns: recovered gradient
:rtype: :class:`firedrake.function.Function`
"""
val_err = (
"Clement interpolation can only be used to compute gradients of Lagrange"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add the word "continuous" - if you supply a DG1 field it's not immediately obvious what's wrong (especially if you're used to "DG", 1 instead of "Discontinuous Lagrange", 1)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Done in 1dd1a0c.

" Functions of degree 1."
)
if not isinstance(f, fd.Function):
raise ValueError(val_err)
if f.ufl_element().family() != "Lagrange" or f.ufl_element().degree() != 1:
raise ValueError(val_err)
mesh = f.function_space().mesh()
rank = len(f.ufl_shape)
if rank > 1:
raise ValueError(
"Clement interpolation can only be used to compute gradients of scalar or"
f" vector Functions, not Functions of rank {rank}."
)

# Recover gradient
if target_space is None:
target_space = [fd.VectorFunctionSpace, fd.TensorFunctionSpace][rank](
mesh, "DG", 0
)
return clement_interpolant(fd.project(ufl.grad(f), target_space))


@PETSc.Log.EventDecorator()
def recover_hessian_clement(f, target_space=None):
r"""
Recover the gradient and Hessian of a scalar field using two applications of
Clement interpolation.

Note that the field must be :math:`\mathbb P1`.

:arg f: the scalar field whose derivatives we seek to recover
:type f: :class:`firedrake.function.Function`
:kwarg target_space: the vector-valued function space to recover the Hessian in
:type target_space: :class:`firedrake.functionspaceimpl.FunctionSpace`
:returns: recovered gradient and Hessian
:rtype: tuple of two :class:`firedrake.function.Function`\s
"""
g = recover_gradient_clement(f)
H = recover_gradient_clement(g, target_space=target_space)
return g, H
102 changes: 102 additions & 0 deletions test/test_recovery_clement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Unit tests for Hessian recovery based on Clement interpolation."""

import firedrake as fd
import pytest
import ufl

from adapt_common.norms import errornorm, norm
from adapt_common.recovery import recover_hessian_clement


@pytest.fixture(params=[1, 2, 3], ids=["1D", "2D", "3D"])
def dim(request):
"""Set the spatial dimension."""
return request.param


@pytest.fixture
def mesh(dim):
"""Create a uniform simplex mesh of [-1, 1]^dim centred on the origin."""
n = 20
length = 2.0
base = {
1: fd.IntervalMesh(n, length),
2: fd.SquareMesh(n, n, length),
3: fd.CubeMesh(n, n, n, length),
}[dim]
coords = fd.Function(base.coordinates)
coords.interpolate(2 * (coords - fd.as_vector([0.5 * length] * dim)))
return fd.Mesh(coords)


def bowl(mesh):
"""Quadratic bowl sensor function."""
return 0.5 * sum([xi**2 for xi in fd.SpatialCoordinate(mesh)])


def relative_error(approx, mesh, ignore_boundary=False):
"""Relative L2 error of the recovered Hessian against the identity."""
d = mesh.topological_dimension
identity = fd.Function(approx.function_space()).interpolate(ufl.Identity(d))
cond = fd.Constant(1.0)
if ignore_boundary:
x = fd.SpatialCoordinate(mesh)
cond = ufl.And(x[0] > -0.8, x[0] < 0.8)
for i in range(1, d):
cond = ufl.And(cond, ufl.And(x[i] > -0.8, x[i] < 0.8))
cond = ufl.conditional(cond, 1, 0)
err = errornorm(identity, approx, norm_type="L2", condition=cond)
err /= norm(identity, norm_type="L2", condition=cond)
return err


def test_recover_hessian_clement_linear(mesh):
"""Test Clement Hessian recovery for a P1 scalar field (linear bowl)."""
f = fd.Function(fd.FunctionSpace(mesh, "CG", 1)).interpolate(bowl(mesh))

g, H = recover_hessian_clement(f)

# Check the function spaces of the recovered gradient and Hessian
g_element = g.function_space().ufl_element()
assert g_element.family() == "Lagrange"
assert g_element.degree() == 1
assert g_element.num_sub_elements == mesh.geometric_dimension
H_element = H.function_space().ufl_element()
assert H_element.family() == "Lagrange"
assert H_element.degree() == 1
assert H_element.num_sub_elements == mesh.geometric_dimension**2

# Verify the accuracy of the recovered Hessian away from the boundary
assert relative_error(H, mesh, ignore_boundary=True) < 1.0e-05


def test_recover_hessian_clement_function_error(mesh):
"""Test that an error is raised for non-Function input."""
val_err = (
"Clement interpolation can only be used to compute gradients of"
" Lagrange Functions of degree 1."
)
with pytest.raises(ValueError, match=val_err):
recover_hessian_clement(bowl(mesh))


def test_recover_hessian_clement_family_error(mesh):
"""Test that an error is raised for non-Lagrange input."""
f = fd.Function(fd.VectorFunctionSpace(mesh, "DG", 1)).assign(1.0)
val_err = (
"Clement interpolation can only be used to compute gradients of"
" Lagrange Functions of degree 1."
)
with pytest.raises(ValueError, match=val_err):
recover_hessian_clement(f)


def test_recover_hessian_clement_degree_error(mesh):
"""Test that an error is raised for degree 0 input."""
f = fd.Function(fd.FunctionSpace(mesh, "CG", 2)).assign(1.0)
val_err = (
"Clement interpolation can only be used to compute gradients of"
" Lagrange Functions of degree 1."
)
with pytest.raises(ValueError, match=val_err):
recover_hessian_clement(f)
63 changes: 47 additions & 16 deletions test/test_recovery_l2.py → test/test_recovery_gradient.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""Unit tests for derivative recovery based on L2-projection."""
"""Unit tests for gradient recovery."""

import firedrake as fd
import pytest

from adapt_common.recovery import recover_gradient_l2
from adapt_common.recovery import recover_gradient, recover_gradient_l2


@pytest.fixture(params=[1, 2, 3])
@pytest.fixture(params=[1, 2, 3], ids=["1D", "2D", "3D"])
def dim(request):
"""Set the spatial dimension."""
return request.param
Expand All @@ -23,7 +23,13 @@ def mesh(dim):
}[dim]


def test_recover_gradient_p2_scalar(mesh):
@pytest.fixture(params=["l2", "clement"])
def method(request):
"""Set the recovery method."""
return request.param


def test_recover_gradient_l2_p2_scalar(mesh):
"""Test gradient recovery for a P2 scalar field."""
# Define a scalar function in P2 space
f = fd.Function(fd.FunctionSpace(mesh, "CG", 2))
Expand All @@ -44,7 +50,7 @@ def test_recover_gradient_p2_scalar(mesh):
assert fd.errornorm(expected, grad_f, norm_type="L2") == pytest.approx(0, abs=1e-8)


def test_recover_gradient_p2_vector(mesh):
def test_recover_gradient_l2_p2_vector(mesh):
"""Test gradient recovery for a P2 vector field."""
# Define a vector function in P2 space
f = fd.Function(fd.VectorFunctionSpace(mesh, "CG", 2))
Expand Down Expand Up @@ -73,20 +79,24 @@ def test_recover_gradient_p2_vector(mesh):
assert fd.errornorm(expected, grad_f, norm_type="L2") == pytest.approx(0, abs=1e-8)


def test_recover_gradient_p1_scalar(mesh):
def test_recover_gradient_p1_scalar(mesh, method):
"""Test gradient recovery for a P1 scalar field."""
# Define a scalar function in P1 space
f = fd.Function(fd.FunctionSpace(mesh, "CG", 1))
x = fd.SpatialCoordinate(mesh)
f.interpolate(sum(x))

# Recovery its gradient using L2 projection
grad_f = recover_gradient_l2(f)
grad_f = recover_gradient(f, method=method)

# Check the function space of the recovered gradient
element = grad_f.function_space().ufl_element()
assert element.family() == "Discontinuous Lagrange"
assert element.degree() == 0
if method == "clement":
assert element.family() == "Lagrange"
assert element.degree() == 1
else:
assert element.family() == "Discontinuous Lagrange"
assert element.degree() == 0
assert element.num_sub_elements == mesh.geometric_dimension

# Verify the accuracy of the recovered gradient
Expand All @@ -98,22 +108,43 @@ def test_recover_gradient_invalid_input():
"""Test that an error is raised for invalid input."""
val_err = "If a target space is not provided then the input must be a Function."
with pytest.raises(ValueError, match=val_err):
recover_gradient_l2("not_a_function")
recover_gradient("not_a_function")


def test_recover_gradient_degree_error(mesh):
def test_recover_gradient_degree_error():
"""Test that an error is raised for degree below 1."""
mesh = fd.UnitIntervalMesh(1)
val_err = "Input Function must be at least degree 1."
with pytest.raises(ValueError, match=val_err):
recover_gradient_l2(fd.Function(fd.FunctionSpace(mesh, "DG", 0)))
recover_gradient(fd.Function(fd.FunctionSpace(mesh, "DG", 0)))


def test_recover_gradient_rank_error(mesh):
def test_recover_gradient_rank_error(method):
"""Test that an error is raised for unsupported function ranks."""
f = fd.Function(fd.TensorFunctionSpace(mesh, "CG", 2))
mesh = fd.UnitIntervalMesh(1)
f = fd.Function(fd.TensorFunctionSpace(mesh, "CG", 1))
long_name = "L2 projection" if method == "l2" else "Clement interpolation"
val_err = (
"L2 projection can only be used to compute gradients of scalar or vector"
f"{long_name} can only be used to compute gradients of scalar or vector"
" Functions, not Functions of rank 2."
)
with pytest.raises(ValueError, match=val_err):
recover_gradient_l2(f)
recover_gradient(f, method=method)


def test_recover_hessian_zz_notimplemented_error():
"""Test that an error is raised for an unrecognised method."""
mesh = fd.UnitIntervalMesh(1)
f = fd.Function(fd.FunctionSpace(mesh, "CG", 1)).assign(1.0)
err = "Zienkiewicz-Zhu recovery not yet implemented."
with pytest.raises(NotImplementedError, match=err):
recover_gradient(f, method="zz")


def test_recover_hessian_method_unrecognised_error():
"""Test that an error is raised for an unrecognised method."""
mesh = fd.UnitIntervalMesh(1)
f = fd.Function(fd.FunctionSpace(mesh, "CG", 1)).assign(1.0)
val_err = "Gradient recovery method 'foo' not recognised."
with pytest.raises(NotImplementedError, match=val_err):
recover_gradient(f, method="foo")