Skip to content

Differentiate base form operators with ufl.diff - #568

Merged
jorgensd merged 6 commits into
mainfrom
pbrubeck/fix/external-operator-variable-derivatives
Nov 23, 2026
Merged

jorgensd merged 6 commits into
mainfrom
pbrubeck/fix/external-operator-variable-derivatives

Conversation

@pbrubeck

@pbrubeck pbrubeck commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

expand_derivatives(diff(N, v))
  differentiate the primal slots
  differentiate the operands when N has a derivative multi-index
  assemble the componentwise derivatives with shape N.ufl_shape + v.ufl_shape

For Interpolate, the input is a primal slot, so the rule reconstructs the interpolation with the differentiated input and the same target. For ExternalOperator, 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 diff through Interpolate.

  • Accept coefficient directions in the Gâteaux derivative of an ExternalOperator. The result matches taking the action of the Jacobian on the coefficient.
  • Compare dual spaces when validating the contracted argument so the default Coargument works with DOLFINx-style FunctionSpace subclasses.
  • Collect domains from every operator operand, including form operands, in extract_unique_domain.
  • Show the function space in BaseFormOperator.__repr__.

Review feedback. Refs #456.

Evidence

  • Before — Four external-operator cases and the interpolation regression failed on missing ufl.diff handlers. The external-operator gradient regression passed. All four review regression checks failed before the review fixes.
  • After — The full suite passes with 1,463 tests. Ruff and mypy checks pass.

Merge Danger

Door Two-way.

Blast Radius Base form operators.

The new ufl.diff rule applies to operators with a free output. The review fixes also affect Gâteaux differentiation, operator construction, domain extraction, and representation.

@pbrubeck pbrubeck changed the title Differentiate external operators with ufl.diff Differentiate base form operators with ufl.diff Nov 20, 2026
@jorgensd

Copy link
Copy Markdown
Member

From discussions with CLAUDE.
The diff rule looks correct.

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, diff puts directions without Arguments into the argument slots. The Gateaux rule for ExternalOperator, however, still refuses a direction that contains no Argument, such as the Coefficient direction of a tangent linear model:

# 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 main (f4183ef2):

derivative(N * dx, u, h): NotImplementedError: Frechet derivative of external operators need to be provided!
action(derivative(N * dx, u, du), h): ok, Form of arity 0
derivative(Interpolate(u**2, V) * dx, u, h): ok, Form of arity 0
diff(ExternalOperator(x), x) * dx: ValueError: Missing differentiation handler for type ExternalOperator. Have you added a new type?

On this branch (58b92b6b):

derivative(N * dx, u, h): NotImplementedError: Frechet derivative of external operators need to be provided!
action(derivative(N * dx, u, du), h): ok, Form of arity 0
derivative(Interpolate(u**2, V) * dx, u, h): ok, Form of arity 0
diff(ExternalOperator(x), x) * dx: ok, Form of arity 0

So the restriction applies only to derivative of an ExternalOperator. Taking the action of the Jacobian gives the same quantity, and neither Interpolate nor the new diff rule have such a check. Removing the check on this branch:

             if df == 0:
                 continue
-            if len(extract_arguments(df)) == 0:
-                raise NotImplementedError(
-                    "Frechet derivative of external operators need to be provided!"
-                )

gives, for N = ExternalOperator(u**2, function_space=V), exactly the form of the action route, ∂e(w_0 ** 2; w_0 * 2 * w_1, v_0)/∂o1, with the same signature. The suite still passes (1460). Could the check go, either in this PR or separately?

@a-latyshev
2. Unrelated: two bugs on main that stop DOLFINx from constructing base form operators. I found these while trying this PR with DOLFINx spaces; neither is caused by this PR.

  • The contracted-space check in BaseFormOperator.__init__ (from Fix dual-slot form argument counting #527/Differentiate the dual slot of base form operators #544) compares contracted.ufl_function_space() != function_space. UFL's __eq__ requires type(self) is type(other). With the default Coargument the contracted argument is on a plain UFL FunctionSpace, so every DOLFINx space fails with The contracted argument in the dual slot must be on function_space. Comparing the dual spaces fixes it.
  • extract_unique_domain unpacks (expr,) = expr.ufl_operands for a base form operator (from Fix Interpolate holes #497), so split(N) fails for an operator with two operands.
  • The patch also adds the missing f in BaseFormOperator.__repr__, which printed {self.ufl_function_space()!r} literally.

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 main and to this branch. I'm happy to open it as a separate PR if you prefer.

Patch
diff --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]

@pbrubeck

Copy link
Copy Markdown
Contributor Author

@jorgensd I applied the patches from the review.

@jorgensd
jorgensd added this pull request to the merge queue Nov 23, 2026
Merged via the queue into main with commit cff4151 Nov 23, 2026
21 checks passed
@jorgensd
jorgensd deleted the pbrubeck/fix/external-operator-variable-derivatives branch November 23, 2026 12:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants