Repository navigation
Differentiate base form operators with ufl.diff - #568
Conversation
…tives directly and add new test for independent variable differentiation
|
From discussions with CLAUDE. Making one operator per component of the variable is a reasonable choice, since argument slots cannot carry free indices. Two further points: 1. External operators reject a tangent linear direction. With this PR, # Run from ufl/test
from utils import LagrangeElement
from ufl import (
Coefficient,
FunctionSpace,
Mesh,
TrialFunction,
action,
derivative,
diff,
dx,
triangle,
variable,
)
from ufl.algorithms import expand_derivatives
from ufl.core.external_operator import ExternalOperator
from ufl.core.interpolate import Interpolate
mesh = Mesh(LagrangeElement(triangle, 1, (2,)))
V = FunctionSpace(mesh, LagrangeElement(triangle, 1))
u = Coefficient(V)
h = Coefficient(V) # tangent linear direction
du = TrialFunction(V)
N = ExternalOperator(u, function_space=V)
def run(name, f):
try:
result = f()
print(f"{name}: ok, {type(result).__name__} of arity {len(result.arguments())}")
except Exception as e:
print(f"{name}: {type(e).__name__}: {e}")
# Gateaux derivative in a Coefficient direction (tangent linear model)
run("derivative(N * dx, u, h)", lambda: expand_derivatives(derivative(N * dx, u, h)))
# The same quantity, through an Argument direction and an action
run("action(derivative(N * dx, u, du), h)", lambda: expand_derivatives(action(derivative(N * dx, u, du), h)))
# Interpolate accepts a Coefficient direction
run(
"derivative(Interpolate(u**2, V) * dx, u, h)",
lambda: expand_derivatives(derivative(Interpolate(u**2, V) * dx, u, h)),
)
# ufl.diff puts directions without Arguments into the slots (needs #568)
x = variable(u)
run("diff(ExternalOperator(x), x) * dx", lambda: expand_derivatives(diff(ExternalOperator(x, function_space=V), x) * dx))On On this branch ( So the restriction applies only to if df == 0:
continue
- if len(extract_arguments(df)) == 0:
- raise NotImplementedError(
- "Frechet derivative of external operators need to be provided!"
- )gives, for @a-latyshev
The patch below adds a test for each of the first two fixes (each fails without its fix), and the suite passes with it. It applies to Patchdiff --git a/test/test_external_operator.py b/test/test_external_operator.py
index b3fba20f..a2ced119 100644
--- a/test/test_external_operator.py
+++ b/test/test_external_operator.py
@@ -40,6 +40,7 @@ from ufl.coefficient import Cofunction
from ufl.core.external_operator import ExternalOperator
from ufl.core.interpolate import Interpolate
from ufl.differentiation import BaseFormDerivative, BaseFormOperatorDerivative, Derivative
+from ufl.domain import extract_unique_domain
from ufl.form import BaseForm, FormSum, ZeroBaseForm
from ufl.pullback import identity_pullback
from ufl.sobolevspace import H1
@@ -144,6 +145,27 @@ def test_dual_slot_must_be_a_base_form(V1):
ExternalOperator(u, function_space=V1, argument_slots=(u,))
+def test_function_space_subclass(V1):
+ """A form compiler's subclass of FunctionSpace, as DOLFINx uses, is accepted."""
+
+ class LibraryFunctionSpace(FunctionSpace):
+ def __eq__(self, other):
+ return type(self) is type(other) and super().__eq__(other)
+
+ __hash__ = FunctionSpace.__hash__
+
+ V = LibraryFunctionSpace(V1.ufl_domain(), V1.ufl_element())
+ N = ExternalOperator(Coefficient(V1), function_space=V)
+ assert N.ufl_function_space().dual() == V.dual()
+ assert "{self" not in repr(N)
+
+
+def test_unique_domain_of_operator_with_several_operands(V1):
+ u, w = Coefficient(V1), Coefficient(V1)
+ N = ExternalOperator(u, w, function_space=V1)
+ assert extract_unique_domain(N) == V1.ufl_domain()
+
+
def test_form(V1, V2):
u = Coefficient(V1)
m = Coefficient(V1)
diff --git a/ufl/core/base_form_operator.py b/ufl/core/base_form_operator.py
index 94e120b9..88c62ab7 100644
--- a/ufl/core/base_form_operator.py
+++ b/ufl/core/base_form_operator.py
@@ -180,7 +180,12 @@ class BaseFormOperator(Operator, BaseForm, Counted):
for a in extract_type(slot, Argument, base_form_op_as_expr=True)
]
contracted, _ = _split_dual_slot_arguments(dual_slot, slot_args)
- if contracted is not None and contracted.ufl_function_space() != function_space:
+ # Compare the dual spaces: function_space may be a subclass (e.g. from a
+ # form compiler's library), while the contracted argument is on a UFL space.
+ if (
+ contracted is not None
+ and contracted.ufl_function_space().dual() != function_space.dual()
+ ):
raise ValueError("The contracted argument in the dual slot must be on function_space.")
# Internal variables for caching coefficient and domain data
@@ -288,7 +293,7 @@ class BaseFormOperator(Operator, BaseForm, Counted):
"""Default repr string construction for base form operators."""
r = f"{type(self).__name__}("
r += ", ".join(repr(op) for op in self.ufl_operands)
- r += "; {self.ufl_function_space()!r}; "
+ r += f"; {self.ufl_function_space()!r}; "
r += ", ".join(repr(arg) for arg in self.argument_slots())
r += f"; derivatives={self.derivatives!r})"
return r
diff --git a/ufl/domain.py b/ufl/domain.py
index df5df106..2c47a959 100644
--- a/ufl/domain.py
+++ b/ufl/domain.py
@@ -460,11 +460,12 @@ def extract_unique_domain(
"""
from ufl.core.base_form_operator import BaseFormOperator
+ from ufl.exprcontainers import ExprList
if isinstance(expr, BaseFormOperator):
# A base form operator has the domains of its argument slots as well,
# but it takes its value on the one its operands are defined over.
- (expr,) = expr.ufl_operands
+ expr = ExprList(*expr.ufl_operands)
domains = extract_domains(expr, expand_mesh_sequence=expand_mesh_sequence)
if len(domains) == 1:
return domains[0] |
|
@jorgensd I applied the patches from the review. |
Summary
For
Interpolate, the input is a primal slot, so the rule reconstructs the interpolation with the differentiated input and the same target. ForExternalOperator, differentiating an operand increments its derivative order and adds a direction to the primal slots.Carry over the regression tests from #567 with their original authorship and add a test for
diffthroughInterpolate.ExternalOperator. The result matches taking the action of the Jacobian on the coefficient.Coargumentworks with DOLFINx-styleFunctionSpacesubclasses.extract_unique_domain.BaseFormOperator.__repr__.Review feedback. Refs #456.
Evidence
ufl.diffhandlers. The external-operator gradient regression passed. All four review regression checks failed before the review fixes.Merge Danger
Door Two-way.
Blast Radius Base form operators.
The new
ufl.diffrule applies to operators with a free output. The review fixes also affect Gâteaux differentiation, operator construction, domain extraction, and representation.