Skip to content
155 changes: 2 additions & 153 deletions animate/interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
85 changes: 7 additions & 78 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 .interpolation import clement_interpolant
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 Expand Up @@ -489,7 +418,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:
Expand Down Expand Up @@ -1061,7 +990,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)

Expand Down Expand Up @@ -1115,7 +1044,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:
Expand Down
Loading