Repository navigation
Add implementation of Hessian recovery using Clement interpolant #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
a0b8ab5
1c4bbc9
1d56a17
13fa774
3e3afd2
0a7f29c
7834dd4
8e543c3
3b0688f
895a80c
c944a8a
2faf53c
1dd1a0c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For degree==2 I'm also not entirely convinced this is safe. If f is CG2 but for some reason your numerical scheme doesn't give you a 2nd order accurate, but a 1st order accurate approximation of some analytical continuous truth, i.e. f could just be in CG1 (as a subset of CG2), then g in DG1 would actually be DG0, and thus H=0 - this may sound arbitrary, but I think it means that any arbitrary 2nd order error in the computation of f would make the Hessian inconsistent.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Restricted in 1d56a17. |
||
| 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 | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would say with DG1 this is still dubious: you only get a good approximation of the gradient if the discontinuities are neglible - which in general is very hard to guarantee
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fair point. To be honest, I'm not sure how this ended up going into Animate (although it was likely my fault!). Restricted to P1 in 1d56a17