Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions adapt_common/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from adapt_common.mesh import * # noqa
from adapt_common.norms import * # noqa
from adapt_common.quality import * # noqa
from adapt_common.recovery import * # noqa
from adapt_common.reduction import * # noqa
from adapt_common.transfer import * # noqa
from adapt_common.utility import * # noqa
93 changes: 93 additions & 0 deletions adapt_common/mesh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Module containing mesh volume properties."""

import firedrake as fd
import ufl

__all__ = [
"boundary_facet_area",
"boundary_patch_volume",
"cell_volume",
"patch_volume",
]


# TODO: Upstream as a cached_property of MeshGeometry in Firedrake (#17)
def cell_volume(mesh):
"""Interpolate a mesh's cell volume in :math:`P^0` space.

This is computed by interpolating the UFL :class:`~.CellVolume` for the mesh.

:arg mesh: the mesh to compute cell volumes for
:type mesh: :class:`firedrake.mesh.MeshGeometry`
:return: the cell volume Function
:rtype: :class:`firedrake.function.Function`
"""
volume = fd.Function(fd.FunctionSpace(mesh, "Discontinuous Lagrange", 0))
return volume.interpolate(ufl.CellVolume(mesh))


# TODO: Upstream as a cached_property of MeshGeometry in Firedrake (#17)
def patch_volume(mesh):
"""Sum the volumes of cells neighbouring a vertex in :math:`P^1` space.

:arg mesh: the mesh to compute sums of cell volumes for
:type mesh: :class:`firedrake.mesh.MeshGeometry`
:return: the patch volume Function
:rtype: :class:`firedrake.function.Function`
"""
patch_vol = fd.Function(fd.FunctionSpace(mesh, "Lagrange", 1))
domain = "{[i]: 0 <= i < patch.dofs}"
instructions = "patch[i, 0] = patch[i, 0] + vol[0, 0]"
keys = {"vol": (cell_volume(mesh), fd.READ), "patch": (patch_vol, fd.RW)}
fd.par_loop((domain, instructions), ufl.dx(domain=mesh), keys)
return patch_vol


# TODO: Upstream as a cached_property of MeshGeometry in Firedrake (#17)
def boundary_facet_area(mesh):
"""Interpolate a mesh's boundary facet areas in :math:`P^0` space.

:arg mesh: the mesh to compute boundary facet areas for
:type mesh: :class:`firedrake.mesh.MeshGeometry`
:return: the boundary facet area Function
:rtype: :class:`firedrake.function.Function`
"""
P0 = fd.FunctionSpace(mesh, "Discontinuous Lagrange", 0)
v = fd.TestFunction(P0)
u = fd.TrialFunction(P0)
facet_area = fd.Function(P0)
sp = {"snes_type": "ksponly", "ksp_type": "preonly", "pc_type": "jacobi"}
fd.solve(
v * u * ufl.ds(domain=mesh) == v * ufl.FacetArea(mesh) * ufl.ds(domain=mesh),
facet_area,
solver_parameters=sp,
)
return facet_area


# TODO: Upstream as a cached_property of MeshGeometry in Firedrake (#17)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect this doesn't quite do the right thing for "corner elements", cells with more than one exterior facet - e.g. the 2 corner triangles in a RectangleMesh: a vertex adjacent to such a corner triangle will receive the corner element value weighted by the edge length of both exterior edges of that corner element.

Out of interest, how are you planning to use this? The issue of corner elements (much more common in 3D) also raises the question of whether you actually want the multiple facets to have multiple values - in which case storing it as P0 field, i.e. in the subset of cells near the boundary, rather than in the facets, doesn't seem the right thing.

Could you do this using "submesh"? i.e. generate a submesh for the provided surface id, then if you do have a P0 volume field as source (i.e. single valued in corner elements) you can project/interpolate to a P0 (surface) field on the submesh, and then you should be able to use the non-boundary clement interpolation you already have, which gives you a P1 (surface) field on the submesh - which you could interpolate back to a P1 volume field if you wanted to...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you do this using "submesh"? i.e. generate a submesh for the provided surface id, then if you do have a P0 volume field as source (i.e. single valued in corner elements) you can project/interpolate to a P0 (surface) field on the submesh, and then you should be able to use the non-boundary clement interpolation you already have, which gives you a P1 (surface) field on the submesh - which you could interpolate back to a P1 volume field if you wanted to...

Good suggestion. I've implemented it that way in recent commits.

I suspect this doesn't quite do the right thing for "corner elements", cells with more than one exterior facet - e.g. the 2 corner triangles in a RectangleMesh: a vertex adjacent to such a corner triangle will receive the corner element value weighted by the edge length of both exterior edges of that corner element.

The revised implementation should address this I think, although the tolerances are quite large in the tests.

Out of interest, how are you planning to use this? The issue of corner elements (much more common in 3D) also raises the question of whether you actually want the multiple facets to have multiple values - in which case storing it as P0 field, i.e. in the subset of cells near the boundary, rather than in the facets, doesn't seem the right thing.

The only current use cases is for the Hessian recovery on the boundary (currently in Animate) that is used in some formulations of anisotropic goal-oriented mesh adaptation. I think the approximate method here should be sufficient for that.

def boundary_patch_volume(mesh):
"""Sum the areas of boundary facets neighbouring a vertex in :math:`P^1` space.

:arg mesh: the mesh to compute sums of boundary facet areas for
:type mesh: :class:`firedrake.mesh.MeshGeometry`
:return: the boundary patch volume Function
:rtype: :class:`firedrake.function.Function`
"""
P1 = fd.FunctionSpace(mesh, "Lagrange", 1)

# Indicate which vertices lie on the domain boundary
indicator = fd.Function(P1)
fd.DirichletBC(P1, 1, "on_boundary").apply(indicator)

# Sum the facet areas of boundary facets neighbouring each vertex
patch_vol = fd.Function(P1)
domain = "{[i]: 0 <= i < patch.dofs}"
instructions = "patch[i, 0] = patch[i, 0] + indicator[i, 0] * area[0, 0]"
keys = {
"indicator": (indicator, fd.READ),
"area": (boundary_facet_area(mesh), fd.READ),
"patch": (patch_vol, fd.RW),
}
fd.par_loop((domain, instructions), ufl.ds(domain=mesh), keys)
return patch_vol
99 changes: 99 additions & 0 deletions adapt_common/quality.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Class for computing mesh quality measures."""

import firedrake as fd
import ufl
from firedrake.petsc import PETSc

__all__ = ["QualityMeasure"]


class QualityMeasure:
"""
Class for computing quality measures associated with a given mesh.

Choices of quality measure:
* ``area``: the area of each cell in a 2D triangular mesh
* ``volume``: the volume of each cell in a 3D tetrahedral mesh
* ``facet_area``: the area of each *facet*.
* ``aspect_ratio``: the aspect ratio of each cell
* ``scaled_jacobian``: the scaled Jacobian of each cell
"""

_measures = (
"area",
"volume",
"facet_area",
"aspect_ratio",
"scaled_jacobian",
)

@PETSc.Log.EventDecorator()
def __init__(self, mesh):
"""
:arg mesh: the input mesh to do computations on
:type mesh: :class:`firedrake.mesh.MeshGeometry`
"""
self.mesh = mesh
self.dim = mesh.topological_dimension
self.coords = mesh.coordinates
self.P0 = fd.FunctionSpace(mesh, "DG", 0)

@PETSc.Log.EventDecorator()
def __call__(self, name):
"""
:arg name: the quality measure name
:type name: :class:`str`
:returns: the quality measure applied to the provided mesh
:rtype: :class:`firedrake.function.Function`
"""
if name not in QualityMeasure._measures:
raise ValueError(f"Quality measure '{name}' not recognised.")

if name in ("area", "volume"):
return fd.Function(self.P0).interpolate(ufl.CellVolume(self.mesh))

elif name == "facet_area":
HDivTrace = fd.FunctionSpace(self.mesh, "HDiv Trace", 0)
v = fd.TestFunction(HDivTrace)
u = fd.TrialFunction(HDivTrace)
facet_area = fd.Function(HDivTrace, name="Facet areas")
mass_term = v("+") * u("+") * ufl.dS + v * u * ufl.ds
rhs = (
v("+") * ufl.FacetArea(self.mesh) * ufl.dS
+ v * ufl.FacetArea(self.mesh) * ufl.ds
)
sp = {
"snes_type": "ksponly",
"ksp_type": "preonly",
"pc_type": "jacobi",
}
fd.solve(mass_term == rhs, facet_area, solver_parameters=sp)
return facet_area

# Other quality measures depend on element Jacobian
P0_ten = fd.TensorFunctionSpace(self.mesh, "DG", 0)
J = fd.Function(P0_ten).interpolate(ufl.Jacobian(self.mesh))
edge1 = ufl.as_vector([J[0, 0], J[1, 0]])
edge2 = ufl.as_vector([J[0, 1], J[1, 1]])
edge3 = edge1 - edge2
a = ufl.sqrt(ufl.dot(edge1, edge1))
b = ufl.sqrt(ufl.dot(edge2, edge2))
c = ufl.sqrt(ufl.dot(edge3, edge3))

if name == "aspect_ratio" and self.dim == 2:
ar = fd.Function(self.P0)
ar.interpolate(a * b * c / ((a + b - c) * (b + c - a) * (c + a - b)))
return ar

elif name == "scaled_jacobian" and self.dim == 2:
detJ = ufl.JacobianDeterminant(self.mesh)
jacobian_sign = ufl.sign(detJ)
max_product = ufl.max_value(
ufl.max_value(ufl.max_value(a * b, a * c), ufl.max_value(b * c, b * a)),
ufl.max_value(c * a, c * b),
)
return fd.Function(self.P0).interpolate(detJ / max_product * jacobian_sign)

raise NotImplementedError(
f"Quality measure '{name}' not implemented in the {self.dim}D case."
)
177 changes: 177 additions & 0 deletions adapt_common/transfer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
"""Module containing functions for transferring fields between function spaces."""

import firedrake as fd
import numpy as np
import ufl
from firedrake.petsc import PETSc

from adapt_common.mesh import (
boundary_facet_area,
boundary_patch_volume,
cell_volume,
patch_volume,
)
from adapt_common.utility import (
cofunction2function,
function2cofunction,
get_function_space,
)

__all__ = ["clement_interpolant"]


def _process_source(source):
"""Process and validate the source function.

:arg source: the source function or cofunction
:type source: :class:`firedrake.function.Function` or
:class:`firedrake.cofunction.Cofunction`
:return: the source function space
:rtype: :class:`firedrake.functionspace.FunctionSpace`
"""
if isinstance(source, fd.Cofunction):
Vs = source.function_space().dual()
elif isinstance(source, fd.Function):
Vs = source.function_space()
else:
type_err = f"Expected Cofunction or Function, got '{type(source)}'."
raise TypeError(type_err)

element = Vs.ufl_element()
if not (element.family() == "Discontinuous Lagrange" and element.degree() == 0):
val_err = "Source function provided must be from a P0 space."
raise ValueError(val_err)
return Vs


def _process_target(source_space, target):
"""Process and validate the target function or function space.

When `target` is None, the target's shape is inferred from the source space.

:arg source_space: the function space used for the source function
:type source_space: :class:`firedrake.functionspaceimpl.FunctionSpace`
:arg target: the target function, function space, cofunction, dual space, or None
:type target: :class:`firedrake.function.Function`,
:class:`firedrake.functionspaceimpl.FunctionSpace`,
:class:`firedrake.cofunction.Counction`,
:class:`firedrake.functionspaceimpl.FiredrakeDualSpace`, or None
:return: the target function and whether the user requested a cofunction target
:rtype: tuple[:class:`firedrake.function.Function`, bool]
"""
is_cofunction = False
rank = len(source_space.value_shape)
mesh = source_space.mesh()

if isinstance(target, fd.Function):
Vt = target.function_space()
elif isinstance(target, fd.Cofunction):
target = cofunction2function(target)
Vt = target.function_space()
is_cofunction = True
elif isinstance(target, fd.functionspaceimpl.FiredrakeDualSpace):
target = fd.Function(target.dual())
Vt = target.function_space()
is_cofunction = True
elif isinstance(target, fd.functionspaceimpl.WithGeometry):
target = fd.Function(target)
Vt = target.function_space()
elif target is None:
Vt = get_function_space(mesh, "CG", 1, source_space.value_shape)
target = fd.Function(Vt)
else:
type_err = f"Unexpected target type '{type(target)}'."
raise TypeError(type_err)

# Validate that Vt is a P1 Lagrange space
element = Vt.ufl_element()
if not (element.family() == "Lagrange" and element.degree() == 1):
val_err = "Target space provided must be P1."
raise ValueError(val_err)

# Validate rank consistency
value_shape = getattr(Vt, "value_shape", ())
if rank != len(value_shape):
val_err = f"Rank-{rank} input inconsistent with target space."
raise ValueError(val_err)

# Ensure meshes match
if Vt.mesh() != mesh:
val_err = "Target function mesh inconsistent with source function mesh."
raise ValueError(val_err)

return target, is_cofunction


@PETSc.Log.EventDecorator()
def clement_interpolant(source, target=None, boundary=False):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this really need to be an option argument? Why not just have a clement_interpolant() and a boundary_clement_interpolant()? There's a bit of overlap, but not that much, and I can't really see a situation where you wanted the calling code to easily switch between the two: for the boundary version you end up with a function that you know only has values on the specified boundary, so presumably you're going to do something else with it than in the case of the non-boundary clement_interpolant

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Addressed in latest merge/commits.

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`.

When `target` is None, the target's shape is inferred from the source space. If the
user requested a dual/cofunction target, a Cofunction will be returned; otherwise a
Function is returned.

:arg source: the :math:`\mathbb P0` source field or dual equivalent
:type source: :class:`firedrake.function.Function` or
:class:`firedrake.cofunction.Cofunction`
:arg target: the target function, function space, cofunction, dual space, or None
:type target: :class:`firedrake.function.Function`,
:class:`firedrake.functionspaceimpl.FunctionSpace`,
:class:`firedrake.cofunction.Counction`,
:class:`firedrake.functionspaceimpl.FiredrakeDualSpace`, or None
:kwarg boundary: if ``True``, take the average over neighbouring boundary facets
rather than cells
:type boundary: :class:`bool`
:return: the interpolated :math:`\mathbb P1` field
:rtype: :class:`firedrake.function.Function` or
:class:`firedrake.cofunction.Cofunction`
"""
if isinstance(source, fd.Cofunction):
source = cofunction2function(source)
Vs = _process_source(source)
mesh = Vs.mesh()
target, is_cofunction = _process_target(Vs, target)

# Take the weighted average of the source function over the neighbouring cells or
# boundary facets
block_size = getattr(Vs, "block_size", 1)
domain = f"{{[i, j]: 0 <= i < out.dofs and 0 <= j < {block_size}}}"
dX = ufl.ds(domain=mesh) if boundary else ufl.dx(domain=mesh)
if boundary:
P1 = fd.FunctionSpace(mesh, "Lagrange", 1)
indicator = fd.Function(P1)
fd.DirichletBC(P1, 1, "on_boundary").apply(indicator)
vol = boundary_facet_area(mesh)
instructions = "out[i, j] = out[i, j] + vol[0, 0] * ind[i, 0] * f[0, j]"
keys = {
"f": (source, fd.READ),
"vol": (vol, fd.READ),
"ind": (indicator, fd.READ),
"out": (target, fd.RW),
}
patch = boundary_patch_volume(mesh)
else:
vol = cell_volume(mesh)
instructions = "out[i, j] = out[i, j] + vol[0, 0] * f[0, j]"
keys = {
"f": (source, fd.READ),
"vol": (vol, fd.READ),
"out": (target, fd.RW),
}
patch = patch_volume(mesh)
fd.par_loop((domain, instructions), dX, keys)

# Divide by the volume of the patch of neighbouring cells or boundary facets, and
# ensure the result is finite
target.interpolate(target / patch)
target.dat.data_with_halos[:] = np.nan_to_num(
target.dat.data_with_halos, posinf=0.0, neginf=0.0
)

# Map back to Cofunction, if one is requested or was passed originally
if is_cofunction:
return function2cofunction(target)
return target
Loading
Loading