From b6c9e2fe81c3a6d3d19b9c8a2912314ec394e666 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Fri, 6 Nov 2026 16:54:46 +0000 Subject: [PATCH 01/10] Use Clement from adapt_common --- adapt_common | 2 +- animate/interpolation.py | 155 +------------------------------------ animate/metric.py | 8 +- animate/recovery.py | 14 ++-- test/test_interpolation.py | 27 +------ test/test_recovery.py | 1 - 6 files changed, 17 insertions(+), 190 deletions(-) diff --git a/adapt_common b/adapt_common index 07cd3ca..c9d97a9 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit 07cd3ca428a030c932fe7a8144393d58d17f4421 +Subproject commit c9d97a9fb41a59ecdcf5677b50d59835969c8ae0 diff --git a/animate/interpolation.py b/animate/interpolation.py index 10cd9ce..cb5f5d1 100644 --- a/animate/interpolation.py +++ b/animate/interpolation.py @@ -3,17 +3,13 @@ """ import firedrake -import numpy as np -import pyop3 as op3 -import ufl -from adapt_common.quality import QualityMeasure from adapt_common.utility import assemble_mass_matrix, cofunction2function -from firedrake.functionspaceimpl import FiredrakeDualSpace, WithGeometry +from firedrake.functionspaceimpl import WithGeometry from firedrake.petsc import PETSc from firedrake.supermeshing import assemble_mixed_mass_matrix from petsc4py import PETSc as petsc4py -__all__ = ["transfer", "interpolate", "project", "clement_interpolant"] +__all__ = ["transfer", "interpolate", "project"] @PETSc.Log.EventDecorator() @@ -174,150 +170,3 @@ def project(source, target, bounded=False, **kwargs): ksp.solveTranspose(vs, residual) mixed_mass.mult(residual, vt) # NOTE: already transposed above t.dat.data_with_halos[:] = tf.dat.data_with_halos - - -@PETSc.Log.EventDecorator() -def clement_interpolant(source, target_space=None, boundary=False): - r""" - Compute the Clement interpolant of a :math:`\mathbb P0` source field, i.e. take the - volume average over neighbouring cells at each vertex. See :cite:`Clement:1975`. - - :arg source: the :math:`\mathbb P0` source field - :type source: :class:`firedrake.function.Function` - :kwarg target_space: the :math:`\mathbb P1` space to interpolate into - :type target_space: :class:`firedrake.functionspaceimpl.FunctionSpace` - :kwarg boundary: interpolate over boundary facets or cells? - :type boundary: :class:`bool` - """ - if not isinstance(source, (firedrake.Cofunction, firedrake.Function)): - raise TypeError(f"Expected Cofunction or Function, got '{type(source)}'.") - - # Map Cofunctions to Functions for the interpolation - is_cofunction = isinstance(source, firedrake.Cofunction) - if is_cofunction: - data = source.dat.data_with_halos - source = firedrake.Function(source.function_space().dual()) - source.dat.data_with_halos[:] = data - - # Process source space - Vs = source.function_space() - Vs_e = Vs.ufl_element() - if not (Vs_e.family() == "Discontinuous Lagrange" and Vs_e.degree() == 0): - raise ValueError("Source function provided must be from a P0 space.") - rank = len(Vs.value_shape) - if rank not in (0, 1, 2): - raise ValueError(f"Rank-{rank + 1} tensors are not supported.") - mesh = Vs.mesh() - dim = mesh.topological_dimension - - # Process target space - Vt = target_space - if Vt is None: - Vt = { - 0: firedrake.FunctionSpace, - 1: firedrake.VectorFunctionSpace, - 2: firedrake.TensorFunctionSpace, - }[rank](mesh, "CG", 1) - elif isinstance(Vt, FiredrakeDualSpace): - Vt = Vt.dual() - else: - is_cofunction = False - Vt_e = Vt.ufl_element() - if not (Vt_e.family() == "Lagrange" and Vt_e.degree() == 1): - raise ValueError("Target space provided must be P1.") - target = firedrake.Function(Vt) - - # Scalar P0 and P1 spaces to hold volumes, etc. - P0 = firedrake.FunctionSpace(mesh, "DG", 0) - P1 = firedrake.FunctionSpace(mesh, "CG", 1) - - # Determine target domain - tdomain = { - 0: "{[i]: 0 <= i < t.dofs}", - 1: f"{{[i, j]: 0 <= i < t.dofs and 0 <= j < {dim}}}", - 2: f"{{[i, j, k]: 0 <= i < t.dofs and 0 <= j < {dim} and 0 <= k < {dim}}}", - }[rank] - - # Compute the patch volume at each vertex - if not boundary: - dX = ufl.dx(domain=mesh) - volume = QualityMeasure(mesh)("volume") - - # Compute patch volume - patch_volume = firedrake.Function(P1) - domain = "{[i]: 0 <= i < patch.dofs}" - instructions = "patch[i, 0] = patch[i, 0] + vol[0, 0]" - keys = {"vol": (volume, op3.READ), "patch": (patch_volume, op3.RW)} - firedrake.par_loop((domain, instructions), dX, keys) - - # Take weighted average - instructions = { - 0: "t[i, 0] = t[i, 0] + v[0, 0] * s[0, 0]", - 1: "t[i, j] = t[i, j] + v[0, 0] * s[0, j]", - 2: ( - f"t[i, {dim} * j + k] =" - f" t[i, {dim} * j + k] + v[0, 0] * s[0, {dim} * j + k]" - ), - }[rank] - keys = { - "s": (source, op3.READ), - "v": (volume, op3.READ), - "t": (target, op3.RW), - } - firedrake.par_loop((tdomain, instructions), dX, keys) - else: - dX = ufl.ds(domain=mesh) - - # Indicate appropriate boundary - bnd_indicator = firedrake.Function(P1) - firedrake.DirichletBC(P1, 1, "on_boundary").apply(bnd_indicator) - - # Determine facet area for boundary edges - v = firedrake.TestFunction(P0) - u = firedrake.TrialFunction(P0) - bnd_volume = firedrake.Function(P0) - mass_term = v * u * dX - rhs = v * ufl.FacetArea(mesh) * dX - sp = {"snes_type": "ksponly", "ksp_type": "preonly", "pc_type": "jacobi"} - firedrake.solve(mass_term == rhs, bnd_volume, solver_parameters=sp) - - # Compute patch volume - patch_volume = firedrake.Function(P1) - domain = "{[i]: 0 <= i < patch.dofs}" - instructions = "patch[i, 0] = patch[i, 0] + indicator[i, 0] * bnd_vol[0, 0]" - keys = { - "bnd_vol": (bnd_volume, op3.READ), - "indicator": (bnd_indicator, op3.READ), - "patch": (patch_volume, op3.RW), - } - firedrake.par_loop((domain, instructions), dX, keys) - - # Take weighted average - instructions = { - 0: "t[i, 0] = t[i, 0] + v[0, 0] * b[i, 0] * s[0, 0]", - 1: "t[i, j] = t[i, j] + v[0, 0] * b[i, 0] * s[0, j]", - 2: ( - f"t[i, {dim} * j + k] = " - f"t[i, {dim} * j + k] + v[0, 0] * b[i, 0] * s[0, {dim} * j + k]" - ), - }[rank] - keys = { - "s": (source, op3.READ), - "v": (bnd_volume, op3.READ), - "b": (bnd_indicator, op3.READ), - "t": (target, op3.RW), - } - firedrake.par_loop((tdomain, instructions), dX, keys) - - # Divide by patch volume and ensure finite - target.interpolate(target / patch_volume) - target.dat.data_with_halos[:] = np.nan_to_num( - target.dat.data_with_halos, posinf=0, neginf=0 - ) - - # Map back to Cofunction, if one was passed originally - if is_cofunction: - data = target.dat.data_with_halos - target = firedrake.Cofunction(target.function_space().dual()) - target.dat.data_with_halos[:] = data - return target diff --git a/animate/metric.py b/animate/metric.py index 32cd69d..9a118ee 100644 --- a/animate/metric.py +++ b/animate/metric.py @@ -18,9 +18,9 @@ from adapt_common.recovery import recover_gradient_l2 from adapt_common.reduction import function_data_min, function_data_sum +from adapt_common.transfer import clement_interpolant from ._kernel import get_metric_kernel -from .interpolation import clement_interpolant from .recovery import recover_boundary_hessian, recover_hessian_clement __all__ = ["RiemannianMetric", "determine_metric_complexity", "intersect_on_boundary"] @@ -489,7 +489,7 @@ def interp(f): * `ValueError` indicates the :class:`Function` is not :math:`\mathbb{P}0`. """ try: - return clement_interpolant(f, target_space=P1) + return clement_interpolant(f, target=P1) except TypeError: return ffunc.Function(P1).assign(f) except ValueError: @@ -1061,7 +1061,7 @@ def compute_anisotropic_dwr_metric( fs = self.function_space() metric = RiemannianMetric(fs) if interpolant == "Clement": - metric.assign(clement_interpolant(P0_metric, target_space=fs)) + metric.assign(clement_interpolant(P0_metric, target=fs)) else: metric.project(P0_metric) @@ -1115,7 +1115,7 @@ def compute_weighted_hessian_metric( f"Expected Hessian to be a RiemannianMetric, not {type(hessian)}." ) if interpolant == "Clement": - error_indicator = clement_interpolant(error_indicator, target_space=P1) + error_indicator = clement_interpolant(error_indicator, target=P1) elif interpolant == "L2": error_indicator = firedrake.project(error_indicator, P1) else: diff --git a/animate/recovery.py b/animate/recovery.py index c9459aa..1e4d093 100644 --- a/animate/recovery.py +++ b/animate/recovery.py @@ -7,9 +7,9 @@ from adapt_common.quality import QualityMeasure from adapt_common.recovery import recover_gradient_l2 from adapt_common.reduction import function_data_max +from adapt_common.transfer import clement_interpolant, clement_interpolant_boundary from firedrake.petsc import PETSc -from .interpolation import clement_interpolant from .math import construct_basis __all__ = ["recover_hessian_clement", "recover_boundary_hessian"] @@ -97,6 +97,7 @@ def recover_boundary_hessian(f, method="Clement", target_space=None, **kwargs): v = firedrake.TestFunction(P1) l2_proj = [[firedrake.Function(P1) for i in range(d - 1)] for j in range(d - 1)] P0 = firedrake.FunctionSpace(mesh, "DG", 0) + p1test = firedrake.TestFunction(P1) h = firedrake.Function(P0).interpolate(ufl.CellDiameter(mesh)) h = firedrake.Constant(1 / function_data_max(h) ** 2) sp = { @@ -133,23 +134,20 @@ def recover_boundary_hessian(f, method="Clement", target_space=None, **kwargs): elif method == "Clement": P0_vec = firedrake.VectorFunctionSpace(mesh, "DG", 0) + p0test = firedrake.TestFunction(P0_vec) P0_ten = firedrake.TensorFunctionSpace(mesh, "DG", 0) P1_vec = firedrake.VectorFunctionSpace(mesh, "CG", 1) - H = firedrake.Function(P1_ten) - p0test = firedrake.TestFunction(P0_vec) - p1test = firedrake.TestFunction(P1) fa = QualityMeasure(mesh)("facet_area") source = firedrake.assemble(ufl.inner(p0test, ufl.grad(f)) / fa * ufl.ds) # Recover gradient - c = clement_interpolant(source, boundary=True, target_space=P1_vec) + c = clement_interpolant_boundary(source, target=P1_vec) # Recover Hessian - H += clement_interpolant( + H = clement_interpolant_boundary( firedrake.Function(P0_ten).interpolate(ufl.grad(c)), - boundary=True, - target_space=P1_ten, + target=P1_ten, ) # Compute tangential components diff --git a/test/test_interpolation.py b/test/test_interpolation.py index 8393dec..404daff 100644 --- a/test/test_interpolation.py +++ b/test/test_interpolation.py @@ -7,6 +7,7 @@ import numpy as np import pytest import ufl +from adapt_common.transfer import clement_interpolant from adapt_common.utility import cofunction2function, function2cofunction from firedrake.assemble import assemble from firedrake.cofunction import Cofunction @@ -23,7 +24,6 @@ from animate.interpolation import ( _supermesh_project, - clement_interpolant, project, transfer, ) @@ -84,12 +84,6 @@ def test_source_type_error(self): ) self.assertEqual(str(cm.exception), msg) - def test_rank_error(self): - with self.assertRaises(ValueError) as cm: - clement_interpolant(Function(self.get_space(3, "DG", 0))) - msg = "Rank-4 tensors are not supported." - self.assertEqual(str(cm.exception), msg) - def test_source_space_error(self): with self.assertRaises(ValueError) as cm: clement_interpolant(Function(self.get_space(0, "CG", 1))) @@ -98,7 +92,7 @@ def test_source_space_error(self): def test_target_space_error(self): with self.assertRaises(ValueError) as cm: - clement_interpolant(Function(self.P0), target_space=self.P0) + clement_interpolant(Function(self.P0), target=self.P0) msg = "Target space provided must be P1." self.assertEqual(str(cm.exception), msg) @@ -107,7 +101,7 @@ def test_cofunction_dual_target_space(self): P1 = self.get_space(0, "CG", 1) source = Cofunction(P0.dual()) source.dat.data_with_halos[:] = 1.0 - target = clement_interpolant(source, target_space=P1.dual()) + target = clement_interpolant(source, target=P1.dual()) self.assertTrue(isinstance(target, Cofunction)) self.assertTrue(np.allclose(target.dat.data_with_halos, 1.0)) @@ -116,7 +110,7 @@ def test_cofunction_primal_target_space(self): P1 = self.get_space(0, "CG", 1) source = Cofunction(P0.dual()) source.dat.data_with_halos[:] = 1.0 - target = clement_interpolant(source, target_space=P1) + target = clement_interpolant(source, target=P1) self.assertTrue(isinstance(target, Function)) self.assertTrue(np.allclose(target.dat.data_with_halos, 1.0)) @@ -131,19 +125,6 @@ def test_volume_average_2d(self, rank): err = assemble(self.interior * (target - expected) ** 2 * ufl.dx) self.assertAlmostEqual(err, 0) - @parameterized.expand([[0], [1], [2]]) - def test_facet_average_2d(self, rank): - exact = self.analytic(rank) - P0 = self.get_space(rank, "DG", 0) - source = Function(P0).project(exact) - target = clement_interpolant(source, boundary=True) - expected = source - integrand = (1 - self.corner) * (target - expected) ** 2 - - # Check approximate recovery - for tag in [1, 2, 3, 4]: - self.assertLess(assemble(integrand * ufl.ds(tag)), 5e-3) - class TestTransfer(unittest.TestCase): """ diff --git a/test/test_recovery.py b/test/test_recovery.py index c3fefc8..999195e 100644 --- a/test/test_recovery.py +++ b/test/test_recovery.py @@ -168,7 +168,6 @@ def test_boundary_mixed_L2(self, dim): @parameterized.expand([[2]]) def test_boundary_Clement(self, dim): - # FIXME: 3D case for test_boundary_Clement mesh = mesh_for_sensors(dim, 20) f = bowl(*mesh.coordinates) metric = self.metric(mesh) From 270c2ad7eadc8ddf9b81a171eb6a952359a57fe2 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Mon, 16 Nov 2026 12:50:20 +0000 Subject: [PATCH 02/10] Update adapt_common --- adapt_common | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adapt_common b/adapt_common index c9d97a9..f9c1bc8 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit c9d97a9fb41a59ecdcf5677b50d59835969c8ae0 +Subproject commit f9c1bc8822498bc4cd616973d8db91aa2b0a4b2d From 636745208f7a965c7d361f3ceb25a4b9ecfd1c0a Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Wed, 18 Nov 2026 18:16:00 +0000 Subject: [PATCH 03/10] Use recover_hessian_clement from adapt_common --- adapt_common | 2 +- animate/metric.py | 4 ++-- animate/recovery.py | 52 ++------------------------------------------- 3 files changed, 5 insertions(+), 53 deletions(-) diff --git a/adapt_common b/adapt_common index f9c1bc8..1d56a17 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit f9c1bc8822498bc4cd616973d8db91aa2b0a4b2d +Subproject commit 1d56a17de6c0041659d12dd104d37a53a7f1921d diff --git a/animate/metric.py b/animate/metric.py index 9a118ee..2829ba1 100644 --- a/animate/metric.py +++ b/animate/metric.py @@ -16,12 +16,12 @@ except ImportError: from petsctools import OptionsManager -from adapt_common.recovery import recover_gradient_l2 +from adapt_common.recovery import recover_gradient_l2, recover_hessian_clement from adapt_common.reduction import function_data_min, function_data_sum from adapt_common.transfer import clement_interpolant from ._kernel import get_metric_kernel -from .recovery import recover_boundary_hessian, recover_hessian_clement +from .recovery import recover_boundary_hessian __all__ = ["RiemannianMetric", "determine_metric_complexity", "intersect_on_boundary"] diff --git a/animate/recovery.py b/animate/recovery.py index 1e4d093..155736a 100644 --- a/animate/recovery.py +++ b/animate/recovery.py @@ -5,61 +5,13 @@ import firedrake import ufl from adapt_common.quality import QualityMeasure -from adapt_common.recovery import recover_gradient_l2 from adapt_common.reduction import function_data_max -from adapt_common.transfer import clement_interpolant, clement_interpolant_boundary +from adapt_common.transfer import clement_interpolant_boundary from firedrake.petsc import PETSc from .math import construct_basis -__all__ = ["recover_hessian_clement", "recover_boundary_hessian"] - - -@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 Hessian - :rtype: :class:`firedrake.function.Function` - """ - if not isinstance(f, firedrake.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 = firedrake.VectorFunctionSpace(mesh, "DG", 0) - g = clement_interpolant(firedrake.project(ufl.grad(f), V)) - else: - V = firedrake.VectorFunctionSpace(mesh, "DG", degree - 1) - g = recover_gradient_l2(f, target_space=V) - - # Recover Hessian - if degree <= 2: - W = firedrake.TensorFunctionSpace(mesh, "DG", 0) - H = clement_interpolant(firedrake.project(ufl.grad(g), W)) - else: - W = firedrake.TensorFunctionSpace(mesh, "DG", degree - 2) - H = recover_gradient_l2(g, target_space=W) - return g, H +__all__ = ["recover_boundary_hessian"] @PETSc.Log.EventDecorator() From 403e1bb8c8b77644d0600a78ea91306d209755b8 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Wed, 18 Nov 2026 18:44:15 +0000 Subject: [PATCH 04/10] Use recover_hessian_l2 from adapt_common --- adapt_common | 2 +- animate/metric.py | 74 +++++++---------------------------------------- 2 files changed, 12 insertions(+), 64 deletions(-) diff --git a/adapt_common b/adapt_common index 1d56a17..1cf143a 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit 1d56a17de6c0041659d12dd104d37a53a7f1921d +Subproject commit 1cf143aa7858e09affae099340db9ae38d5c738e diff --git a/animate/metric.py b/animate/metric.py index 2829ba1..9bb1c59 100644 --- a/animate/metric.py +++ b/animate/metric.py @@ -16,7 +16,10 @@ except ImportError: from petsctools import OptionsManager -from adapt_common.recovery import recover_gradient_l2, recover_hessian_clement +from adapt_common.recovery import ( + recover_hessian_clement, + recover_hessian_l2, +) from adapt_common.reduction import function_data_min, function_data_sum from adapt_common.transfer import clement_interpolant @@ -336,10 +339,6 @@ def compute_hessian(self, field, method="mixed_L2", **kwargs): :rtype: :class:`~.RiemannianMetric` All other keyword arguments are passed to the chosen recovery routine. - - In the case of the `'L2'` method, the `target_space` keyword argument is used - for the gradient recovery. The target space for the Hessian recovery is - inherited from the metric itself. """ if len(field.ufl_shape) > 0: value_error = ( @@ -349,16 +348,14 @@ def compute_hessian(self, field, method="mixed_L2", **kwargs): "RiemannianMetric.combine." ) raise ValueError(value_error) - if method == "L2": - gradient = recover_gradient_l2( - field, target_space=kwargs.get("target_space") - ) + if method in ("L2", "mixed_L2"): return self.assign( - recover_gradient_l2(gradient, target_space=self.function_space()) - ) - elif method == "mixed_L2": - return self.interpolate( - self._compute_gradient_and_hessian(field, **kwargs)[1] + recover_hessian_l2( + field, + mixed=(method == "mixed_L2"), + target_space=self.function_space(), + **kwargs, + )[1] ) elif method == "Clement": return self.assign(recover_hessian_clement(field, **kwargs)[1]) @@ -383,55 +380,6 @@ def compute_boundary_hessian(self, field, method="mixed_L2", **kwargs): """ return self.assign(recover_boundary_hessian(field, method=method, **kwargs)) - def _compute_gradient_and_hessian(self, field, solver_parameters=None): - mesh = self.function_space().mesh() - V = ffs.VectorFunctionSpace(mesh, "CG", 1) - W = V * self.function_space() - g, H = firedrake.TrialFunctions(W) - phi, tau = firedrake.TestFunctions(W) - sol = ffunc.Function(W) - n = ufl.FacetNormal(mesh) - - a = ( - ufl.inner(tau, H) * ufl.dx - + ufl.inner(ufl.div(tau), g) * ufl.dx - - ufl.dot(g, ufl.dot(tau, n)) * ufl.ds - - ufl.dot(ufl.avg(g), ufl.jump(tau, n)) * ufl.dS - + ufl.inner(phi, g) * ufl.dx - ) - L = ( - field * ufl.dot(phi, n) * ufl.ds - + ufl.avg(field) * ufl.jump(phi, n) * ufl.dS - - field * ufl.div(phi) * ufl.dx - ) - if solver_parameters is None: - solver_parameters = { - "mat_type": "aij", - "ksp_type": "gmres", - "ksp_max_it": 20, - "pc_type": "fieldsplit", - "pc_fieldsplit_type": "schur", - "pc_fieldsplit_0_fields": "1", - "pc_fieldsplit_1_fields": "0", - "pc_fieldsplit_schur_precondition": "selfp", - "fieldsplit_0_ksp_type": "preonly", - "fieldsplit_1_ksp_type": "preonly", - "fieldsplit_1_pc_type": "gamg", - "fieldsplit_1_mg_levels_ksp_max_it": 5, - } - if firedrake.COMM_WORLD.size == 1: - solver_parameters["fieldsplit_0_pc_type"] = "ilu" - solver_parameters["fieldsplit_1_mg_levels_pc_type"] = "ilu" - else: - solver_parameters["fieldsplit_0_pc_type"] = "bjacobi" - solver_parameters["fieldsplit_0_sub_ksp_type"] = "preonly" - solver_parameters["fieldsplit_0_sub_pc_type"] = "ilu" - solver_parameters["fieldsplit_1_mg_levels_pc_type"] = "bjacobi" - solver_parameters["fieldsplit_1_mg_levels_sub_ksp_type"] = "preonly" - solver_parameters["fieldsplit_1_mg_levels_sub_pc_type"] = "ilu" - firedrake.solve(a == L, sol, solver_parameters=solver_parameters) - return sol.subfunctions - # --- Methods for processing metrics @PETSc.Log.EventDecorator() From 7b80ac40aa7f3ad259f4ce75dc782aab059bb0b7 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Wed, 18 Nov 2026 18:44:40 +0000 Subject: [PATCH 05/10] Update expected Clement error message in tests --- test/test_recovery.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_recovery.py b/test/test_recovery.py index 999195e..ae2ecf7 100644 --- a/test/test_recovery.py +++ b/test/test_recovery.py @@ -42,7 +42,7 @@ def test_clement_function_error(self): self.metric.compute_hessian(f, method="Clement") msg = ( "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree > 0." + " Lagrange Functions of degree 1." ) self.assertEqual(str(cm.exception), msg) @@ -52,7 +52,7 @@ def test_clement_space_error(self): self.metric.compute_hessian(f, method="Clement") msg = ( "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree > 0." + " Lagrange Functions of degree 1." ) self.assertEqual(str(cm.exception), msg) @@ -62,7 +62,7 @@ def test_clement_degree_error(self): self.metric.compute_hessian(f, method="Clement") msg = ( "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree > 0." + " Lagrange Functions of degree 1." ) self.assertEqual(str(cm.exception), msg) From 38dea6ea2bd6a2d591657825a6fd1551c36d6ae8 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Wed, 18 Nov 2026 18:46:00 +0000 Subject: [PATCH 06/10] Drop erroneous test --- test/test_recovery.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/test/test_recovery.py b/test/test_recovery.py index ae2ecf7..f4c4382 100644 --- a/test/test_recovery.py +++ b/test/test_recovery.py @@ -145,14 +145,6 @@ def test_interior_Clement_linear(self, dim): metric.compute_hessian(f, method="Clement") self.assertLess(self.relative_error(metric, ignore_boundary=True), 1.0e-05) - @parameterized.expand([[2], [3]]) - def test_interior_Clement_quadratic(self, dim): - mesh = mesh_for_sensors(dim, 20) - f = Function(FunctionSpace(mesh, "CG", 1)).interpolate(bowl(*mesh.coordinates)) - metric = self.metric(mesh) - metric.compute_hessian(f, method="Clement") - self.assertLess(self.relative_error(metric, ignore_boundary=True), 1.0e-08) - @parameterized.expand([[2]]) def test_boundary_mixed_L2(self, dim): # FIXME: 3D case for test_boundary_mixed_L2 From f20ed6d1a577cfa7ca56e9a1a4b8b6f4f3a70890 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 07:02:14 +0000 Subject: [PATCH 07/10] Drop duplicate tests --- test/test_recovery.py | 32 ++------------------------------ 1 file changed, 2 insertions(+), 30 deletions(-) diff --git a/test/test_recovery.py b/test/test_recovery.py index f4c4382..9c50e4a 100644 --- a/test/test_recovery.py +++ b/test/test_recovery.py @@ -20,6 +20,8 @@ # standard tests for pytest # --------------------------- +# TODO: Port tests + class TestRecoverySetup(unittest.TestCase): """ @@ -36,36 +38,6 @@ def get_func_ones(self, family, degree): V = FunctionSpace(self.mesh, family, degree) return Function(V).assign(1.0) - def test_clement_function_error(self): - f = bowl(*ufl.SpatialCoordinate(self.mesh)) - with self.assertRaises(ValueError) as cm: - self.metric.compute_hessian(f, method="Clement") - msg = ( - "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree 1." - ) - self.assertEqual(str(cm.exception), msg) - - def test_clement_space_error(self): - f = self.get_func_ones("DG", 0) - with self.assertRaises(ValueError) as cm: - self.metric.compute_hessian(f, method="Clement") - msg = ( - "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree 1." - ) - self.assertEqual(str(cm.exception), msg) - - def test_clement_degree_error(self): - f = self.get_func_ones("DG", 0) - with self.assertRaises(ValueError) as cm: - self.metric.compute_hessian(f, method="Clement") - msg = ( - "Clement interpolation can only be used to compute gradients of" - " Lagrange Functions of degree 1." - ) - self.assertEqual(str(cm.exception), msg) - def test_zz_notimplemented_error(self): f = self.get_func_ones("CG", 1) with self.assertRaises(NotImplementedError) as cm: From 80476ef089889ad5c7005c7061a551f3b845bad0 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 07:48:07 +0000 Subject: [PATCH 08/10] Fully port Hessian on domain interior recovery to adapt_common --- adapt_common | 2 +- animate/metric.py | 23 ++-------------- test/test_recovery.py | 62 +++---------------------------------------- 3 files changed, 7 insertions(+), 80 deletions(-) diff --git a/adapt_common b/adapt_common index 1cf143a..53e8742 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit 1cf143aa7858e09affae099340db9ae38d5c738e +Subproject commit 53e874200bb382bd98d7b62ce4576b33e6dfb7f8 diff --git a/animate/metric.py b/animate/metric.py index 9bb1c59..ab29b97 100644 --- a/animate/metric.py +++ b/animate/metric.py @@ -16,10 +16,7 @@ except ImportError: from petsctools import OptionsManager -from adapt_common.recovery import ( - recover_hessian_clement, - recover_hessian_l2, -) +from adapt_common.recovery import recover_hessian from adapt_common.reduction import function_data_min, function_data_sum from adapt_common.transfer import clement_interpolant @@ -348,23 +345,7 @@ def compute_hessian(self, field, method="mixed_L2", **kwargs): "RiemannianMetric.combine." ) raise ValueError(value_error) - if method in ("L2", "mixed_L2"): - return self.assign( - recover_hessian_l2( - field, - mixed=(method == "mixed_L2"), - target_space=self.function_space(), - **kwargs, - )[1] - ) - elif method == "Clement": - return self.assign(recover_hessian_clement(field, **kwargs)[1]) - elif method == "ZZ": - raise NotImplementedError( - "Zienkiewicz-Zhu recovery not yet implemented." - ) # TODO (#130) - else: - raise ValueError(f"Recovery method '{method}' not recognised.") + return self.assign(recover_hessian(field, method=method, **kwargs)[1]) @PETSc.Log.EventDecorator() def compute_boundary_hessian(self, field, method="mixed_L2", **kwargs): diff --git a/test/test_recovery.py b/test/test_recovery.py index 9c50e4a..b5467c6 100644 --- a/test/test_recovery.py +++ b/test/test_recovery.py @@ -5,9 +5,7 @@ import unittest import ufl -from adapt_common.norms import errornorm, norm from firedrake.assemble import assemble -from firedrake.constant import Constant from firedrake.function import Function from firedrake.functionspace import FunctionSpace, TensorFunctionSpace from parameterized import parameterized @@ -20,8 +18,6 @@ # standard tests for pytest # --------------------------- -# TODO: Port tests - class TestRecoverySetup(unittest.TestCase): """ @@ -62,67 +58,17 @@ def test_unrecognised_boundary_method_error(self): self.assertEqual(str(cm.exception), msg) -class TestRecoveryBowl(unittest.TestCase): +class TestRecoveryBoundary(unittest.TestCase): """ - Unit tests for recovery applied to a quadratic 'bowl' sensor. + Unit tests for boundary recovery applied to a quadratic 'bowl' sensor. """ - @staticmethod - def metric(mesh): - P1_ten = TensorFunctionSpace(mesh, "CG", 1) - return RiemannianMetric(P1_ten) - - @staticmethod - def relative_error(approx, ignore_boundary=False): - mesh = approx.function_space().mesh() - dim = mesh.topological_dimension - P1_ten = TensorFunctionSpace(mesh, "CG", 1) - identity = Function(P1_ten).interpolate(ufl.Identity(dim)) - - # Check that they agree - cond = Constant(1.0) - if ignore_boundary: - x = ufl.SpatialCoordinate(mesh) - cond = ufl.And(x[0] > -0.8, x[0] < 0.8) - for i in range(1, dim): - cond = ufl.And(cond, ufl.And(x[i] > -0.8, x[i] < 0.8)) - cond = ufl.conditional(cond, 1, 0) - err = errornorm(approx, identity, norm_type="L2", condition=cond) - err /= norm(identity, norm_type="L2", condition=cond) - return err - - @parameterized.expand( - [ - (2, "L2"), - (2, "mixed_L2"), - (3, "L2"), - (3, "mixed_L2"), - ] - ) - def test_interior_L2_quadratic(self, dim, method): - # TODO: parallel version (#33) - mesh = mesh_for_sensors(dim, 4) - f = bowl(*mesh.coordinates) - if method == "L2": - f = Function(FunctionSpace(mesh, "CG", 2)).interpolate(f) - metric = self.metric(mesh) - metric.compute_hessian(f, method=method) - self.assertLess(self.relative_error(metric), 1.0e-07) - - @parameterized.expand([[2], [3]]) - def test_interior_Clement_linear(self, dim): - mesh = mesh_for_sensors(dim, 20) - f = Function(FunctionSpace(mesh, "CG", 1)).interpolate(bowl(*mesh.coordinates)) - metric = self.metric(mesh) - metric.compute_hessian(f, method="Clement") - self.assertLess(self.relative_error(metric, ignore_boundary=True), 1.0e-05) - @parameterized.expand([[2]]) def test_boundary_mixed_L2(self, dim): # FIXME: 3D case for test_boundary_mixed_L2 mesh = mesh_for_sensors(dim, 4) f = bowl(*mesh.coordinates) - metric = self.metric(mesh) + metric = RiemannianMetric(TensorFunctionSpace(mesh, "CG", 1)) metric.compute_boundary_hessian(f, method="mixed_L2") # Check its directional derivatives in boundaries are zero @@ -134,7 +80,7 @@ def test_boundary_mixed_L2(self, dim): def test_boundary_Clement(self, dim): mesh = mesh_for_sensors(dim, 20) f = bowl(*mesh.coordinates) - metric = self.metric(mesh) + metric = RiemannianMetric(TensorFunctionSpace(mesh, "CG", 1)) metric.compute_boundary_hessian(f, method="Clement") # Check its directional derivatives in boundaries are zero From 2b9141366fde73184376c882c1267bbebfbc8dab Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Thu, 19 Nov 2026 18:33:59 +0000 Subject: [PATCH 09/10] Update adapt_common commit --- adapt_common | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adapt_common b/adapt_common index 53e8742..207ab5a 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit 53e874200bb382bd98d7b62ce4576b33e6dfb7f8 +Subproject commit 207ab5a94f5a00804691755ece42e06beaae0c02 From 9350e437dbf999071c16e87c70edc89e67f204b4 Mon Sep 17 00:00:00 2001 From: Joe Wallwork Date: Fri, 20 Nov 2026 09:16:06 +0000 Subject: [PATCH 10/10] Drop tests duplicated in adapt_common --- adapt_common | 2 +- test/test_recovery.py | 43 +++++++------------------------------------ 2 files changed, 8 insertions(+), 37 deletions(-) diff --git a/adapt_common b/adapt_common index 207ab5a..fb77950 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit 207ab5a94f5a00804691755ece42e06beaae0c02 +Subproject commit fb77950c56b47e5f35d80940c6921a8ad75eee3a diff --git a/test/test_recovery.py b/test/test_recovery.py index b5467c6..dfa1488 100644 --- a/test/test_recovery.py +++ b/test/test_recovery.py @@ -6,8 +6,7 @@ import ufl from firedrake.assemble import assemble -from firedrake.function import Function -from firedrake.functionspace import FunctionSpace, TensorFunctionSpace +from firedrake.functionspace import TensorFunctionSpace from parameterized import parameterized from sensors import bowl, mesh_for_sensors @@ -19,50 +18,22 @@ # --------------------------- -class TestRecoverySetup(unittest.TestCase): +class TestRecoveryBoundary(unittest.TestCase): """ - Unit tests for derivative recovery. + Unit tests for boundary recovery applied to a quadratic 'bowl' sensor. """ - def setUp(self): - self.mesh = mesh_for_sensors(2, 4) - P1_ten = TensorFunctionSpace(self.mesh, "CG", 1) - self.metric = RiemannianMetric(P1_ten) - self.expr = bowl(*self.mesh.coordinates) - - def get_func_ones(self, family, degree): - V = FunctionSpace(self.mesh, family, degree) - return Function(V).assign(1.0) - - def test_zz_notimplemented_error(self): - f = self.get_func_ones("CG", 1) - with self.assertRaises(NotImplementedError) as cm: - self.metric.compute_hessian(f, method="ZZ") - msg = "Zienkiewicz-Zhu recovery not yet implemented." - self.assertEqual(str(cm.exception), msg) - - def test_unrecognised_interior_method_error(self): - f = self.get_func_ones("CG", 1) - with self.assertRaises(ValueError) as cm: - self.metric.compute_hessian(f, method="some_method") - msg = "Recovery method 'some_method' not recognised." - self.assertEqual(str(cm.exception), msg) - def test_unrecognised_boundary_method_error(self): - f = self.get_func_ones("CG", 1) + mesh = mesh_for_sensors(2, 4) + f = bowl(*mesh.coordinates) + metric = RiemannianMetric(TensorFunctionSpace(mesh, "CG", 1)) with self.assertRaises(ValueError) as cm: - self.metric.compute_boundary_hessian(f, method="some_method") + metric.compute_boundary_hessian(f, method="some_method") msg = ( "Recovery method 'some_method' not supported for Hessians on the boundary." ) self.assertEqual(str(cm.exception), msg) - -class TestRecoveryBoundary(unittest.TestCase): - """ - Unit tests for boundary recovery applied to a quadratic 'bowl' sensor. - """ - @parameterized.expand([[2]]) def test_boundary_mixed_L2(self, dim): # FIXME: 3D case for test_boundary_mixed_L2