Skip to content
2 changes: 1 addition & 1 deletion adapt_common
77 changes: 3 additions & 74 deletions animate/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
except ImportError:
from petsctools import OptionsManager

from adapt_common.recovery import recover_gradient_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

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"]

Expand Down Expand Up @@ -336,10 +336,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 = (
Expand All @@ -349,25 +345,7 @@ 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")
)
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]
)
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):
Expand All @@ -383,55 +361,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()
Expand Down
52 changes: 2 additions & 50 deletions animate/recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
137 changes: 9 additions & 128 deletions test/test_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@
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 firedrake.functionspace import TensorFunctionSpace
from parameterized import parameterized
from sensors import bowl, mesh_for_sensors

Expand All @@ -21,144 +18,28 @@
# ---------------------------


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_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 > 0."
)
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 > 0."
)
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 > 0."
)
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:
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 TestRecoveryBowl(unittest.TestCase):
"""
Unit tests for 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], [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
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
Expand All @@ -170,7 +51,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
Expand Down