From a0b8ab5c8499d9e60ec23c7a4fcc9fecd066237c Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Mon, 16 Nov 2026 13:02:57 +0000 Subject: [PATCH 01/13] Add recover_hessian_clement --- adapt_common/recovery.py | 51 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index f165be0..0757da7 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -4,7 +4,9 @@ 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() @@ -51,3 +53,50 @@ 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_hessian_clement(f): + r""" + Recover the gradient and Hessian of a scalar field using two applications of + Clement interpolation. + + Note that if the field is of degree 2 then projection will be used to obtain the + gradient. If the field is of degree 3 or greater then projection will be used + for the Hessian recovery, too. + + :arg f: the scalar field whose derivatives we seek to recover + :type f: :class:`firedrake.function.Function` + :returns: recovered gradient and Hessian + :rtype: tuple of two :class:`firedrake.function.Function`\s + """ + if not isinstance(f, fd.Function): + raise ValueError( + "Clement interpolation can only be used to compute gradients of" + " Lagrange Functions of degree > 0." + ) + family = f.ufl_element().family() + degree = f.ufl_element().degree() + if family not in ("Lagrange", "Discontinuous Lagrange") or degree == 0: + raise ValueError( + "Clement interpolation can only be used to compute gradients of" + " Lagrange Functions of degree > 0." + ) + mesh = f.function_space().mesh() + + # Recover gradient + if degree <= 1: + V = fd.VectorFunctionSpace(mesh, "DG", 0) + g = clement_interpolant(fd.project(ufl.grad(f), V)) + else: + V = fd.VectorFunctionSpace(mesh, "DG", degree - 1) + g = recover_gradient_l2(f, target_space=V) + + # Recover Hessian + if degree <= 2: + W = fd.TensorFunctionSpace(mesh, "DG", 0) + H = clement_interpolant(fd.project(ufl.grad(g), W)) + else: + W = fd.TensorFunctionSpace(mesh, "DG", degree - 2) + H = recover_gradient_l2(g, target_space=W) + return g, H From 1c4bbc980460777c9fcfe9e132e01d5c2b27eecf Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Mon, 16 Nov 2026 13:48:29 +0000 Subject: [PATCH 02/13] Add tests for Hessian recovery --- test/test_recovery_clement.py | 155 ++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 test/test_recovery_clement.py diff --git a/test/test_recovery_clement.py b/test/test_recovery_clement.py new file mode 100644 index 0000000..f5404e2 --- /dev/null +++ b/test/test_recovery_clement.py @@ -0,0 +1,155 @@ +"""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_quadratic(mesh): + """Test Clement Hessian recovery for a P2 scalar field (quadratic bowl).""" + f = fd.Function(fd.FunctionSpace(mesh, "CG", 2)).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() == "Discontinuous 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-08 + + +def test_recover_hessian_clement_cubic(mesh): + """Test Clement Hessian recovery for a P3 scalar field (quadratic bowl).""" + f = fd.Function(fd.FunctionSpace(mesh, "CG", 3)).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() == "Discontinuous Lagrange" + assert g_element.degree() == 2 + H_element = H.function_space().ufl_element() + assert H_element.family() == "Discontinuous Lagrange" + assert H_element.degree() == 1 + assert H_element.num_sub_elements == mesh.geometric_dimension**2 + + # Verify the accuracy of the recovered gradient, too + x = fd.SpatialCoordinate(mesh) + expected_g = fd.Function(g.function_space()).interpolate(fd.as_vector(list(x))) + assert fd.errornorm(expected_g, g, norm_type="L2") == pytest.approx(0, abs=1e-8) + + # Verify the accuracy of the recovered Hessian + assert relative_error(H, mesh) < 1.0e-07 + + +def test_recover_hessian_clement_dg(mesh): + """Test Clement Hessian recovery for a DG scalar field.""" + f = fd.Function(fd.FunctionSpace(mesh, "DG", 2)).interpolate(bowl(mesh)) + g, H = recover_hessian_clement(f) + assert relative_error(H, mesh) < 1.0e-07 + + +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 > 0." + ) + 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.""" + if mesh.topological_dimension == 1: + pytest.skip("No non-Lagrange vector element on the interval.") + f = fd.Function(fd.VectorFunctionSpace(mesh, "BDM", 1)).assign(1.0) + val_err = ( + "Clement interpolation can only be used to compute gradients of" + " Lagrange Functions of degree > 0." + ) + 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, "DG", 0)).assign(1.0) + val_err = ( + "Clement interpolation can only be used to compute gradients of" + " Lagrange Functions of degree > 0." + ) + with pytest.raises(ValueError, match=val_err): + recover_hessian_clement(f) From 1d56a17de6c0041659d12dd104d37a53a7f1921d Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Wed, 18 Nov 2026 16:21:32 +0000 Subject: [PATCH 03/13] Only allow Clement Hessians for P1 --- adapt_common/recovery.py | 38 +++++++-------------- test/test_recovery_clement.py | 63 +++-------------------------------- 2 files changed, 17 insertions(+), 84 deletions(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 0757da7..543242c 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -61,42 +61,28 @@ def recover_hessian_clement(f): Recover the gradient and Hessian of a scalar field using two applications of Clement interpolation. - Note that if the field is of degree 2 then projection will be used to obtain the - gradient. If the field is of degree 3 or greater then projection will be used - for the Hessian recovery, too. + 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` :returns: recovered gradient and Hessian :rtype: tuple of two :class:`firedrake.function.Function`\s """ + val_err = ( + "Clement interpolation can only be used to compute gradients of Lagrange" + " Functions of degree 1." + ) if not isinstance(f, fd.Function): - raise ValueError( - "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree > 0." - ) - family = f.ufl_element().family() - degree = f.ufl_element().degree() - if family not in ("Lagrange", "Discontinuous Lagrange") or degree == 0: - raise ValueError( - "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree > 0." - ) + 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() # Recover gradient - if degree <= 1: - V = fd.VectorFunctionSpace(mesh, "DG", 0) - g = clement_interpolant(fd.project(ufl.grad(f), V)) - else: - V = fd.VectorFunctionSpace(mesh, "DG", degree - 1) - g = recover_gradient_l2(f, target_space=V) + V = fd.VectorFunctionSpace(mesh, "DG", 0) + g = clement_interpolant(fd.project(ufl.grad(f), V)) # Recover Hessian - if degree <= 2: - W = fd.TensorFunctionSpace(mesh, "DG", 0) - H = clement_interpolant(fd.project(ufl.grad(g), W)) - else: - W = fd.TensorFunctionSpace(mesh, "DG", degree - 2) - H = recover_gradient_l2(g, target_space=W) + W = fd.TensorFunctionSpace(mesh, "DG", 0) + H = clement_interpolant(fd.project(ufl.grad(g), W)) return g, H diff --git a/test/test_recovery_clement.py b/test/test_recovery_clement.py index f5404e2..e588fd7 100644 --- a/test/test_recovery_clement.py +++ b/test/test_recovery_clement.py @@ -70,62 +70,11 @@ def test_recover_hessian_clement_linear(mesh): assert relative_error(H, mesh, ignore_boundary=True) < 1.0e-05 -def test_recover_hessian_clement_quadratic(mesh): - """Test Clement Hessian recovery for a P2 scalar field (quadratic bowl).""" - f = fd.Function(fd.FunctionSpace(mesh, "CG", 2)).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() == "Discontinuous 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-08 - - -def test_recover_hessian_clement_cubic(mesh): - """Test Clement Hessian recovery for a P3 scalar field (quadratic bowl).""" - f = fd.Function(fd.FunctionSpace(mesh, "CG", 3)).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() == "Discontinuous Lagrange" - assert g_element.degree() == 2 - H_element = H.function_space().ufl_element() - assert H_element.family() == "Discontinuous Lagrange" - assert H_element.degree() == 1 - assert H_element.num_sub_elements == mesh.geometric_dimension**2 - - # Verify the accuracy of the recovered gradient, too - x = fd.SpatialCoordinate(mesh) - expected_g = fd.Function(g.function_space()).interpolate(fd.as_vector(list(x))) - assert fd.errornorm(expected_g, g, norm_type="L2") == pytest.approx(0, abs=1e-8) - - # Verify the accuracy of the recovered Hessian - assert relative_error(H, mesh) < 1.0e-07 - - -def test_recover_hessian_clement_dg(mesh): - """Test Clement Hessian recovery for a DG scalar field.""" - f = fd.Function(fd.FunctionSpace(mesh, "DG", 2)).interpolate(bowl(mesh)) - g, H = recover_hessian_clement(f) - assert relative_error(H, mesh) < 1.0e-07 - - 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 > 0." + " Lagrange Functions of degree 1." ) with pytest.raises(ValueError, match=val_err): recover_hessian_clement(bowl(mesh)) @@ -133,12 +82,10 @@ def test_recover_hessian_clement_function_error(mesh): def test_recover_hessian_clement_family_error(mesh): """Test that an error is raised for non-Lagrange input.""" - if mesh.topological_dimension == 1: - pytest.skip("No non-Lagrange vector element on the interval.") - f = fd.Function(fd.VectorFunctionSpace(mesh, "BDM", 1)).assign(1.0) + 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 > 0." + " Lagrange Functions of degree 1." ) with pytest.raises(ValueError, match=val_err): recover_hessian_clement(f) @@ -146,10 +93,10 @@ def test_recover_hessian_clement_family_error(mesh): def test_recover_hessian_clement_degree_error(mesh): """Test that an error is raised for degree 0 input.""" - f = fd.Function(fd.FunctionSpace(mesh, "DG", 0)).assign(1.0) + 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 > 0." + " Lagrange Functions of degree 1." ) with pytest.raises(ValueError, match=val_err): recover_hessian_clement(f) From 13fa774e32001dfd2c2fb2afcda87d4de19f2714 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 10:22:46 +0000 Subject: [PATCH 04/13] Add recover_gradient(_clement) --- adapt_common/recovery.py | 68 ++++++++++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 13 deletions(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 543242c..1f34f85 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -9,14 +9,36 @@ __all__ = ["recover_gradient_l2", "recover_hessian_clement"] +# TODO: Add test for catching errors +@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 @@ -55,18 +77,20 @@ def recover_gradient_l2(f, target_space=None): return fd.project(ufl.grad(f), target_space) +# TODO: Add tests for recover_gradient_clement @PETSc.Log.EventDecorator() -def recover_hessian_clement(f): +def recover_gradient_clement(f, target_space=None): r""" - Recover the gradient and Hessian of a scalar field using two applications of - Clement interpolation. + 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` - :returns: recovered gradient and Hessian - :rtype: tuple of two :class:`firedrake.function.Function`\s + :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" @@ -79,10 +103,28 @@ def recover_hessian_clement(f): mesh = f.function_space().mesh() # Recover gradient - V = fd.VectorFunctionSpace(mesh, "DG", 0) - g = clement_interpolant(fd.project(ufl.grad(f), V)) + if target_space is None: + target_space = fd.VectorFunctionSpace(mesh, "DG", 0) + return clement_interpolant(fd.project(ufl.grad(f), target_space)) + - # Recover Hessian - W = fd.TensorFunctionSpace(mesh, "DG", 0) - H = clement_interpolant(fd.project(ufl.grad(g), W)) +@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) + if target_space is None: + target_space = fd.TensorFunctionSpace(g.function_space().mesh(), "DG", 0) + H = clement_interpolant(fd.project(ufl.grad(g), target_space)) return g, H From 3e3afd23bd5cfe6939f318e71781f49f777d7e0f Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 10:38:52 +0000 Subject: [PATCH 05/13] Add tests for catching errors --- ...covery_l2.py => test_recovery_gradient.py} | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) rename test/{test_recovery_l2.py => test_recovery_gradient.py} (82%) diff --git a/test/test_recovery_l2.py b/test/test_recovery_gradient.py similarity index 82% rename from test/test_recovery_l2.py rename to test/test_recovery_gradient.py index 876aeac..473dbb5 100644 --- a/test/test_recovery_l2.py +++ b/test/test_recovery_gradient.py @@ -1,9 +1,9 @@ -"""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]) @@ -117,3 +117,21 @@ def test_recover_gradient_rank_error(mesh): ) with pytest.raises(ValueError, match=val_err): recover_gradient_l2(f) + + +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 = "Recovery method 'foo' not recognised." + with pytest.raises(NotImplementedError, match=val_err): + recover_gradient(f, method="foo") From 0a7f29c08e42a63230cc563c30f72ceaa531a06f Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 10:40:17 +0000 Subject: [PATCH 06/13] Fail-fast --- test/test_recovery_gradient.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/test/test_recovery_gradient.py b/test/test_recovery_gradient.py index 473dbb5..f27285b 100644 --- a/test/test_recovery_gradient.py +++ b/test/test_recovery_gradient.py @@ -23,7 +23,7 @@ def mesh(dim): }[dim] -def test_recover_gradient_p2_scalar(mesh): +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)) @@ -44,7 +44,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)) @@ -73,7 +73,7 @@ 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_l2_p1_scalar(mesh): """Test gradient recovery for a P1 scalar field.""" # Define a scalar function in P1 space f = fd.Function(fd.FunctionSpace(mesh, "CG", 1)) @@ -98,25 +98,27 @@ 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(): """Test that an error is raised for unsupported function ranks.""" + mesh = fd.UnitIntervalMesh(1) f = fd.Function(fd.TensorFunctionSpace(mesh, "CG", 2)) val_err = ( "L2 projection 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) def test_recover_hessian_zz_notimplemented_error(): @@ -132,6 +134,6 @@ 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 = "Recovery method 'foo' not recognised." + val_err = "Gradient recovery method 'foo' not recognised." with pytest.raises(NotImplementedError, match=val_err): recover_gradient(f, method="foo") From 7834dd464e9cd638fa630d8178fc2fe86d49cb56 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 13:33:42 +0000 Subject: [PATCH 07/13] Test Clement gradient recovery --- test/test_recovery_gradient.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/test/test_recovery_gradient.py b/test/test_recovery_gradient.py index f27285b..f05aa84 100644 --- a/test/test_recovery_gradient.py +++ b/test/test_recovery_gradient.py @@ -23,6 +23,12 @@ def mesh(dim): }[dim] +@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 @@ -73,7 +79,7 @@ def test_recover_gradient_l2_p2_vector(mesh): assert fd.errornorm(expected, grad_f, norm_type="L2") == pytest.approx(0, abs=1e-8) -def test_recover_gradient_l2_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)) @@ -81,12 +87,16 @@ def test_recover_gradient_l2_p1_scalar(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 From 8e543c3378d1b2d584b14b41483703967c91bb1e Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 18:04:29 +0000 Subject: [PATCH 08/13] Use dimension ID for fixtures --- test/test_recovery_gradient.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_recovery_gradient.py b/test/test_recovery_gradient.py index f05aa84..00d1685 100644 --- a/test/test_recovery_gradient.py +++ b/test/test_recovery_gradient.py @@ -6,7 +6,7 @@ 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 From 3b0688fac9c8bc38b176b07a4bb2701042b16b98 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 18:15:18 +0000 Subject: [PATCH 09/13] Use recover_gradient_clement twice for Hessian computation --- adapt_common/recovery.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 1f34f85..7f63828 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -101,10 +101,15 @@ def recover_gradient_clement(f, target_space=None): 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(f"Source function must be rank-0 or rank-1, not rank-{rank}.") # Recover gradient if target_space is None: - target_space = fd.VectorFunctionSpace(mesh, "DG", 0) + target_space = [fd.VectorFunctionSpace, fd.TensorFunctionSpace][rank]( + mesh, "DG", 0 + ) return clement_interpolant(fd.project(ufl.grad(f), target_space)) @@ -124,7 +129,5 @@ def recover_hessian_clement(f, target_space=None): :rtype: tuple of two :class:`firedrake.function.Function`\s """ g = recover_gradient_clement(f) - if target_space is None: - target_space = fd.TensorFunctionSpace(g.function_space().mesh(), "DG", 0) - H = clement_interpolant(fd.project(ufl.grad(g), target_space)) + H = recover_gradient_clement(g, target_space=target_space) return g, H From 895a80c1258a038581f3a29687a47a2a103c275e Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 18:19:59 +0000 Subject: [PATCH 10/13] Extend rank check test to Clement, too --- adapt_common/recovery.py | 5 ++++- test/test_recovery_gradient.py | 9 +++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 7f63828..437e64d 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -103,7 +103,10 @@ def recover_gradient_clement(f, target_space=None): mesh = f.function_space().mesh() rank = len(f.ufl_shape) if rank > 1: - raise ValueError(f"Source function must be rank-0 or rank-1, not rank-{rank}.") + 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: diff --git a/test/test_recovery_gradient.py b/test/test_recovery_gradient.py index 00d1685..478e5ec 100644 --- a/test/test_recovery_gradient.py +++ b/test/test_recovery_gradient.py @@ -119,16 +119,17 @@ def test_recover_gradient_degree_error(): recover_gradient(fd.Function(fd.FunctionSpace(mesh, "DG", 0))) -def test_recover_gradient_rank_error(): +def test_recover_gradient_rank_error(method): """Test that an error is raised for unsupported function ranks.""" mesh = fd.UnitIntervalMesh(1) - f = fd.Function(fd.TensorFunctionSpace(mesh, "CG", 2)) + 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(f) + recover_gradient(f, method=method) def test_recover_hessian_zz_notimplemented_error(): From c944a8a9fb6363a5bf0fba2e6f578eb95e40be04 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 18:20:57 +0000 Subject: [PATCH 11/13] Drop outdated TODO --- adapt_common/recovery.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 437e64d..1e0d713 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -77,7 +77,6 @@ def recover_gradient_l2(f, target_space=None): return fd.project(ufl.grad(f), target_space) -# TODO: Add tests for recover_gradient_clement @PETSc.Log.EventDecorator() def recover_gradient_clement(f, target_space=None): r""" From 2faf53c60da58241d527599de18f84e306a625c3 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 18:22:04 +0000 Subject: [PATCH 12/13] Drop another outdated TODO --- adapt_common/recovery.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 1e0d713..174a549 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -9,7 +9,6 @@ __all__ = ["recover_gradient_l2", "recover_hessian_clement"] -# TODO: Add test for catching errors @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. From 1dd1a0cfa76844695eadab95fd307a1dfd52446c Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Fri, 20 Nov 2026 15:02:20 +0000 Subject: [PATCH 13/13] Mention continuous Lagrange specifically in error message --- adapt_common/recovery.py | 4 ++-- test/test_recovery_clement.py | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/adapt_common/recovery.py b/adapt_common/recovery.py index 174a549..5bdcbed 100644 --- a/adapt_common/recovery.py +++ b/adapt_common/recovery.py @@ -91,8 +91,8 @@ def recover_gradient_clement(f, target_space=None): :rtype: :class:`firedrake.function.Function` """ val_err = ( - "Clement interpolation can only be used to compute gradients of Lagrange" - " Functions of degree 1." + "Clement interpolation can only be used to compute gradients of continuous" + " Lagrange Functions of degree 1." ) if not isinstance(f, fd.Function): raise ValueError(val_err) diff --git a/test/test_recovery_clement.py b/test/test_recovery_clement.py index e588fd7..aa28c0d 100644 --- a/test/test_recovery_clement.py +++ b/test/test_recovery_clement.py @@ -73,7 +73,7 @@ def test_recover_hessian_clement_linear(mesh): 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" + "Clement interpolation can only be used to compute gradients of continuous" " Lagrange Functions of degree 1." ) with pytest.raises(ValueError, match=val_err): @@ -84,7 +84,7 @@ 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" + "Clement interpolation can only be used to compute gradients of continuous" " Lagrange Functions of degree 1." ) with pytest.raises(ValueError, match=val_err): @@ -95,7 +95,7 @@ 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" + "Clement interpolation can only be used to compute gradients of continuous" " Lagrange Functions of degree 1." ) with pytest.raises(ValueError, match=val_err):