diff --git a/adapt_common b/adapt_common index 07cd3ca..1f9d503 160000 --- a/adapt_common +++ b/adapt_common @@ -1 +1 @@ -Subproject commit 07cd3ca428a030c932fe7a8144393d58d17f4421 +Subproject commit 1f9d50368d52e9bec3a4d3f395fb8813b705c493 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)