Skip to content

Fix dual-slot form argument counting - #527

Merged
jorgensd merged 11 commits into
mainfrom
fix-dual-slot-form-arguments
Nov 2, 2026
Merged

jorgensd merged 11 commits into
mainfrom
fix-dual-slot-form-arguments

Conversation

@pbrubeck

@pbrubeck pbrubeck commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A base form operator N(u; F) with a form F in its dual slot is F(N(u)): the output of N takes the place of one Argument of F. On main, the operator still reports that contracted Argument as free, so it has the wrong rank. For example, Interpolate(u, inner(u, v) * dx) is a number, but main gives it one argument. The outer_form flag existed to work around this miscounting.

This PR makes the contraction part of the dual slot itself:

 BaseFormOperator._analyze_form_arguments
-  dual-slot arguments = all arguments of F whose numbers the primal slots don't use
-                        (includes the contracted Argument; outer_form toggles Coarguments)
+  dual-slot arguments = arguments of F except the contracted one
dual slot
├── Coargument / Cofunction   contracts its primal Argument
└── Form                      an Action, chosen by the primal slots of N
    ├── contain Argument 0    Action(N, F): contracts the lowest-numbered primal Argument of F
    ├── otherwise             Action(F, N): contracts the highest-numbered primal Argument of F
    └── other Arguments       stay free

So Interpolate(u, F) has the same arguments as Action(F, Interpolate(u, V)), and Interpolate(v_0, F) has the same arguments as Action(Interpolate(v_0, V), F). The slot is stored as given, so replace() finds the nodes that arguments() returns.

Behaviour changes:

  • An operator with a form in its dual slot no longer reports the contracted Argument as free.
  • outer_form is removed from Coargument.arguments(), BaseFormOperator.argument_slots() and BaseFormOperatorDerivative.argument_slots().
  • A dual slot that is not a BaseForm raises a ValueError.
  • Interpolate accepts non-contiguous argument numbers. It still rejects shared numbers.
  • A form dual slot contracts its lowest-numbered primal Argument if the primal slots contain Argument 0, and its highest otherwise.
  • The contraction is read from the numbers. Replacing Argument 0 in a primal slot by hand changes it: replace(Interpolate(v_0, F), {v_0: c}) gives F(v_0, I c), not F(I c, v_1). action(c, Interpolate(v_0, F)) gives the latter.
  • BaseFormOperatorDerivative.arguments() raises when the operator and the derivative direction share an argument number. apply_derivatives numbers a derivative direction after the operator's highest argument number. It used to use the argument count, which collides when the numbers have gaps.

Evidence

  • Before (main at 0d23dd32):
    L = inner(u, TestFunction(V2)) * dx
    Interpolate(u, L).arguments()                                       # (V2#0,): the contracted Argument is counted
    ExternalOperator(u, function_space=V2, argument_slots=(L,)).arguments()  # (V2#0,)
    
    F = inner(TrialFunction(V2), TestFunction(V3)) * dx
    Interpolate(u, F).arguments()                     # (V3#0, V2#1): rank 2
    derivative(Interpolate(u, F), u, Argument(V1, 0)) # (V3#0, V2#1, V1#0): duplicate number 0
    Interpolate(u, Argument(V2.dual(), 1))            # ValueError: Non-contiguous argument numbers
    After (84304a8e):
    Interpolate(u, L).arguments()                                       # ()
    ExternalOperator(u, function_space=V2, argument_slots=(L,)).arguments()  # ()
    
    Interpolate(u, F).arguments()                     # (V3#0,), same as Action(F, Interpolate(u, V2))
    derivative(Interpolate(u, F), u, Argument(V1, 0)).arguments()
                                                      # ValueError: Same argument numbers in the operator
                                                      #             and the derivative direction.
    Interpolate(u, Argument(V2.dual(), 1))            # arguments (V2*#1,)
    Interpolate(Argument(V1, 0), F).arguments()       # (V1#0, V2#1), same as main
    Interpolate(Argument(V1, 1), F).arguments()       # (V3#0, V1#1)
  • pytest test: 1044 passed on main, 1062 passed on 84304a8e, including test_form_dual_slot_argument_is_contracted, test_form_dual_slot_contraction_ignores_numbering_gaps and test_form_dual_slot_contracts_lowest_argument_with_test_function for Interpolate and ExternalOperator. ruff check and ruff format --check are clean.

Merge Danger

Door: two-way

Nothing is persisted. Reverting restores the previous argument analysis.

Blast Radius: downstream

🤖 Generated with Claude Code

pbrubeck added a commit that referenced this pull request Oct 8, 2026
…king on #527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pbrubeck
pbrubeck force-pushed the fix-dual-slot-form-arguments branch from 2959a76 to 2510774 Compare October 8, 2026 10:13
@pbrubeck
pbrubeck added this pull request to stack #536 October 8, 2026 10:30
pbrubeck added a commit that referenced this pull request Oct 11, 2026
…king on #527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pbrubeck
pbrubeck force-pushed the fix-dual-slot-form-arguments branch from 397581c to 55a5110 Compare October 11, 2026 21:43
@jorgensd
jorgensd force-pushed the fix-dual-slot-form-arguments branch from 55a5110 to 299e3df Compare October 15, 2026 11:24
Comment thread ufl/core/base_form_operator.py Resolved
Comment thread test/test_external_operator.py Resolved
Comment thread ufl/core/base_form_operator.py Resolved
Comment thread ufl/core/base_form_operator.py Resolved
Comment thread ufl/core/base_form_operator.py Resolved
@jorgensd

Copy link
Copy Markdown
Member

Minor issues from CLAUDE:

The remaining dual-slot arguments aren't renumbered

# A(t, v) = (t, v): v in V2 is number 0, t in V3 is number 1
A = inner(TrialFunction(V3), TestFunction(V2)) * dx
N = ExternalOperator(u, function_space=V2, argument_slots=(A,))
N.arguments()      # (Argument(V3, 1),): a 1-form whose only argument is numbered 1
Interpolate(u, A)  # ValueError: Non-contiguous argument numbers in interpolate.

Contracting v with N(u) should leave the 1-form A(t, N(u)), with t renumbered to 0. ExternalOperator accepts the gap silently, while Interpolate rejects it. On main both returned rank 2, which counted the contracted v, so neither branch is correct. UFL's Action never builds this case; it only comes from direct construction. Firedrake's 2-form pattern Interpolate(TestFunction(V1), A) isn't affected.

Nothing checks that function_space matches the dual slot.

F3 = inner(Coefficient(V3), TestFunction(V3)) * dx  # pairs with a function in V3
M = ExternalOperator(u, function_space=V2, argument_slots=(F3,))
M.ufl_element()  # P2: accepted, although F3 can only pair with a P3 output

With a Coargument slot, the output space can be read back from arguments(). With a contracted slot it can't, so a mismatch goes unnoticed. A check in BaseFormOperator.init would catch it. For a Form or Cofunction slot, that means requiring the lowest-numbered argument of the slot to be on function_space.

@pbrubeck
pbrubeck force-pushed the fix-dual-slot-form-arguments branch 6 times, most recently from f2a10c0 to d88b8b7 Compare October 16, 2026 12:49
pbrubeck added a commit that referenced this pull request Oct 16, 2026
…king on #527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
jorgensd pushed a commit that referenced this pull request Oct 30, 2026
…king on #527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jorgensd
jorgensd force-pushed the fix-dual-slot-form-arguments branch from d88b8b7 to 2e8ba16 Compare October 30, 2026 07:54
Comment thread ufl/core/base_form_operator.py Resolved
@jorgensd

Copy link
Copy Markdown
Member

Issue

Coargument.arguments() caches the result of its first call. After arguments(outer_form=True) the cache is (v*,), without the primal argument. The new dual-slot code reads that cache in three places (_renumber_dual_slot_arguments, the function_space check, and Interpolate.__init__), so a Coargument slot is handled differently depending on how it was first analysed:

v_star = Coargument(V2.dual(), 0)
v_star.arguments(outer_form=True)

ExternalOperator(u, function_space=V2, argument_slots=(v_star,))
# ValueError: The lowest-numbered argument in the dual slot must be on function_space.

Interpolate(u, v_star).arguments()
# (): the free Coargument is lost, and the target space becomes V2*

Suggested fix:

The attached patch reads Coargument and Cofunction slots by type, instead of through arguments():

  • _renumber_dual_slot_arguments returns (dual_arg,) for a Coargument and () for a Cofunction.
  • The function_space check compares dual_slot.ufl_function_space().dual() for these slots. Form slots still use their lowest-numbered argument.
  • Interpolate.__init__ takes its function space from v.ufl_function_space().dual() for these slots.

Side note: nothing in UFL or Firedrake passes outer_form=True to Coargument.arguments(), and its cache ignores the flag after the first call, so the parameter is effectively dead, inconsistent API. Removing it, or caching per outer_form value, would be a good separate cleanup; with the patch, this PR no longer depends on it either way.

ufl-527-coargument-dual-slot.patch

@pbrubeck

pbrubeck commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Coargument.arguments() caches the result of its first call. After arguments(outer_form=True) the cache is (v*,), without the primal argument.

outer_form is a very convoluted API, if we are not using it, we should remove it.

@jorgensd

Copy link
Copy Markdown
Member

Coargument.arguments() caches the result of its first call. After arguments(outer_form=True) the cache is (v*,), without the primal argument.

outer_form is a very convoluted API, if we are not using it, we should remove it.

I could not find any usage in firedrake. So should we just remove it in this PR, and apply the general patch I suggested?

@pbrubeck
pbrubeck force-pushed the fix-dual-slot-form-arguments branch from 5f92b74 to 2e8ba16 Compare October 30, 2026 10:11
@jorgensd

Copy link
Copy Markdown
Member

@pbrubeck
I re-checked the new head (5e845ee) against TSFC (Firedrake 2026.10) and FFCx (main and #881).

Resolved

The Coargument cache problem is gone now that arguments() always returns (Argument(V, 0), v*).
Storing the renumbered dual slot fixes replace. It also fixes an aliasing bug in the previous head: with a same-space slot such as a mass matrix, the reported free argument compared equal to the contracted one, so replace(IM, {IM.arguments()[0]: w}) put w in the contracted position.
Argument numbering

Keeping the contracted number reserved means a 2-form slot never exposes argument 0. I checked whether the compilers accept that:

TSFC and FFCx both generate the same interpolation kernels for Interpolate(u, v*#1) and Interpolate(Argument(V1, 1), c) as for their 0-numbered versions. FFCx only changes .signature.
Removing the contiguity check makes Firedrake's 2-form-slot rewrite in assemble.py (L873-879) work, since it builds Interpolate(u, Argument(V2.dual(), 1)), which main rejects.
TSFC's compile_form still uses number() as an index, so Argument(V, 1) * dx raises an IndexError. Gapped numbers therefore have to stay on BaseForm-level objects (Interpolate, Action) and never reach a form kernel.
So I'm fine with removing the check. Two things in UFL itself still need attention:

Duplicate argument numbers are created silently:

A = inner(TrialFunction(V3), TestFunction(V2)) * dx
derivative(Interpolate(u, A), u, TrialFunction(V1)).arguments()  # two Arguments numbered 1

This should raise, as Interpolate already does for "Same argument numbers".
The same 1-form now gets different argument numbers depending on how it is written:

(Interpolate(u, A) + Action(adjoint(A), Interpolate(u, V2))).arguments()  # rank 2, not 1

If this is intended, please document it in the docstring ("the remaining arguments are renumbered to the lowest free numbers above the contracted one") and add a test.

Conflict with #515

#515 generalises the contiguity check to numbers == range(n), while this PR removes it. They conflict in ufl/core/interpolate.py, and with #515's check the Firedrake rewrite fails again. Could you agree with @schnellerhase on one direction? FFCx #881 depends on #515.

A dual-valued Interpolate is accepted as an integrand

Interpolate(u, A) * dx with a 2-form A has a DualSpace as its function space but is still accepted as an integrand. The resulting form has no arguments, and FFCx #881 compiles it to exactly the kernel of Interpolate(u, V2) * dx, so A is silently dropped. This isn't new, but this PR makes dual-valued operators BaseForms, so it would be a good place to reject that (e.g. in Measure.rmul) and add a test.

Smaller points

  • Please list the behaviour changes in the PR description:
    • outer_form is removed from Coargument.arguments() and argument_slots() (Firedrake's Coargument._analyze_form_arguments override can drop it too);
    • a non-BaseForm dual slot (e.g. a primal Argument) now raises a ValueError;
    • the contiguity check is removed;
    • form-slot arguments are numbered differently.
  • The renumbering runs three times: in Interpolate.init, in BaseFormOperator.init and in _analyze_form_arguments. Since the stored slot is already renumbered, _analyze_form_arguments could use self._argument_slots[0].arguments()[1:].
  • replace on a primal argument can silently renumber a dual-slot argument. For example, replace(Interpolate(Argument(V1, 1), A), {Argument(V1, 1): Argument(V1, 2)}) moves the V3 argument from 2 to 1. That's probably fine, but worth a sentence in the docstring.

@pbrubeck

pbrubeck commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@schnellerhase the argument numbering contiguity check will be dropped, as an Interpolate is not always the root of the DAG. That check only makes sense at the root.

@pbrubeck

Copy link
Copy Markdown
Contributor Author

I opened #546, I don't think we should be adding changes to Measure.rmul in this PR

Comment thread ufl/differentiation.py Resolved
A form dual slot now contracts its highest-numbered primal argument, as
the left operand of an Action does, so Interpolate(u, F) numbers its
free arguments like Action(F, Interpolate(u, V)), starting at 0.
Coarguments in the slot stay free.

The stored slot is renumbered once, at construction, and argument
analysis reads it back. BaseFormOperatorDerivative rejects duplicate
argument numbers, and apply_derivatives numbers the direction after the
highest operator argument instead of after the argument count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbrubeck

Copy link
Copy Markdown
Contributor Author

Duplicate argument numbers are created silently:

Addressed in 32429b9.

  1. The derivative node now rejects duplicate numbers
  2. apply_derivatives stopped creating duplicates itself

pbrubeck and others added 3 commits October 30, 2026 12:22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Renumbering the slot's own arguments with replace could rename one onto an
argument that an Action inside the slot contracts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread ufl/core/base_form_operator.py Resolved
Renumbering the free arguments in the constructor rewrote the user's form
with replace, which needed _contained_arguments to avoid arguments that inner
Actions contract. That traversal was exponential in the depth of shared
subexpressions.

The free arguments now keep their numbers, and N(u; F) contracts the argument
that an Action would. If the primal slots use number 0, the output of N is
numbered last, so N is the left operand and F's lowest argument is contracted.
Otherwise F is the left operand and its highest argument is contracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jorgensd
jorgensd added this pull request to the merge queue Nov 2, 2026
Merged via the queue into main with commit 6a89eab Nov 2, 2026
21 checks passed
@jorgensd
jorgensd deleted the fix-dual-slot-form-arguments branch November 2, 2026 13:26
pbrubeck added a commit that referenced this pull request Nov 3, 2026
#527 was squash-merged into main, and this branch already contains it. The
resolved tree is the same as this branch's. The conflicts came from code this
branch moved or removed: the Action constructor simplifications, the
apply_derivatives chain rule and Coargument.arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pbrubeck added a commit to firedrakeproject/firedrake that referenced this pull request Nov 3, 2026
…t 0 replaces

A form dual slot does not always contract its highest-numbered primal
argument. Argument 0 of the expression replaces Argument 0 of the form, as
in FEniCS/ufl#527, so the target space of interpolate(v_0, F) is the space
of Argument 0 of F.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pbrubeck added a commit to firedrakeproject/ufl that referenced this pull request Nov 9, 2026
* Fix dual-slot form argument counting

* Compare the stored function space in Interpolate.__eq__

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Fix dual-slot form argument handling

* Only differentiate derivative nodes in the base form operator chain rule

The chain rule dF/du = ∂F/∂u + Σ Action(∂F/∂N, dN/du) computes ∂F/∂N by
mapping the derivative rules over every integrand and FormSum component
of F. Integrands without a derivative node do not depend on `u` through
N, but they were passed through unchanged, so they leaked into ∂F/∂N.
For `derivative(J, u) + F` this gave a spurious Action(F, dN/du), and
for a FormSum with a Cofunction it raised a TypeError.

Map integrands without a derivative node to zero, and drop the empty
Forms that this leaves in a FormSum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate the dual slot of base form operators

A base form operator N(u; v*) is linear in its dual slot v*. When v*
depends on u, the product rule gives

    D[N(u; v*(u))][û] = ∂N/∂u(u; v*)[û] + N(u; Dv*[û]),

but only the first term was computed. For J = j(I u) with I an
interpolation, dJ/du is the adjoint interpolation I*(j'(I u)), whose
dual slot j'(I u) carries all of its dependence on u. The second
derivative of J was therefore ZeroBaseForm instead of I* j''(I u) I.

Add the dual-slot term, as N(u; Dv*) when Dv* is a Form and as
Action(N(u; v̂), Dv*) otherwise. To differentiate the result again:

- A BaseFormOperatorDerivative whose inner derivative is a FormSum or an
  Action is differentiated with `derivative`, by linearity and the
  Leibniz rule.
- `derivative` of a Form with base form operators expands its inner
  derivatives first.
- The Leibniz rule for Action numbers the new argument after the
  arguments of the Action, expands the derivatives of both slots and
  drops vanishing terms. `action` no longer requires a BaseForm on the
  left, since `Action` accepts a Coefficient or an Argument there.
- `Interpolate._ufl_expr_reconstruct_` accepts `argument_slots`.
- Base form operators hash their argument slots and derivatives: the
  `ufl_type` decorator replaced `BaseFormOperator.__hash__`, so N(u; v*)
  and N(u; Dv*) collided. BaseFormOperatorDerivative compares operands
  instead of raising NotImplementedError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expand base form derivatives only in expand_derivatives

`derivative` now only builds derivative nodes. For a Form with base form
operators and nested derivatives, it used to expand the inner derivatives
eagerly, so the type of `derivative(F, u)` depended on the contents of F:
a Form for F = J, but a FormSum or an Action for F = derivative(J, u).
The Action branch also expanded both of its slots. `apply_derivatives`
called back into `derivative`, and `derivative` called `expand_derivatives`.

Move this logic into `apply_derivatives`, so that `expand_derivatives` is
the only place where a derivative can turn a Form into another BaseForm:

- Nested derivatives of a Form with base form operators are expanded from
  the inside out. The inner derivative may be a FormSum or an Action, which
  cannot live inside an integral, so the outer derivative is applied to it
  at the BaseForm level.
- `derivative` of an Action returns a BaseFormDerivative. The Leibniz rule
  is applied when it is expanded.
- `map_integrands` maps through a BaseFormDerivative of a Form, FormSum or
  Action instead of treating it as an integrand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate BaseForms in one ruleset and collapse Action onto any dual slot

The derivatives of FormSums, Actions, Forms and base form operators were
expanded by free functions that dispatched on type. They now live in
BaseFormDerivativeRuleset, a DAGTraverser, and DerivativeRuleDispatcher
has a single BaseFormDerivative handler that expands the inner
derivatives first.

The dual-slot term of D[N(u; v*)] is always Action(N(u; vhat), Dv*).
Action.__new__ collapses Action(N(u; vhat), F) to N(u; F) for every
base form operator, not only Interpolate, when F has one argument.

To make both representations agree:

- A base form operator contracts the first argument of any dual slot
  that is not a Coargument, a Form included, so N(u; F) has the
  arguments of Action(N(u; vhat), F).
- Base form operators keep their target function space, which they use
  to reconstruct, compare and hash, so that rank-0 operators work. A
  rank-0 operator adds as a BaseForm.
- Action sorts its arguments by number, like any other BaseForm.
- The Leibniz rule for Action numbers the argument of the left operand
  after the direction instead of reordering with an adjoint, which was
  ignored when the left operand is not a Form.

Also:

- Nested derivatives of integrands with base form operators are lifted
  to a BaseFormDerivative of a Form.
- map_integrand_dags, not map_integrands, maps through a
  BaseFormDerivative of a BaseForm.
- Form has ufl_operands = (), like every other BaseForm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Allow Interpolate arguments to be numbered non-contiguously

The dual-slot term of D[N(u; v*)] is Action(N(u; vhat), Dv*), with vhat
numbered after the other arguments of N so that the Action contracts it.
For a forward interpolation Interpolate(2 * v_1, v*_0) this builds
Interpolate(2 * v_1, vhat_2), which the contiguity check rejected before
Action could drop the vanishing term. Arguments need not be contiguous in
such intermediate expressions, so only check that the two operands do not
share argument numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add only the arguments of the direction to zero BaseForms

The Gateaux rules for Coargument, Cofunction, Matrix, ZeroBaseForm and a
constant Interpolate returned ZeroBaseForm(o.arguments() + self._v),
which appends the direction even when it is a Coefficient, as in a
tangent linear model. The dual-slot term Action(N(u; vhat), Dv*) then
failed to number the arguments of the Action. Add only the arguments
of the direction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Lower compound algebra when expanding a BaseFormDerivative

map_integrand_dags mapped through a BaseFormDerivative of a BaseForm, so
that apply_algebra_lowering in expand_derivatives would lower the
integrands of its operand. Since a Form has no ufl_operands, the DAG of
the derivative stops at the BaseForm, and the expansion of the
derivative is the place where its operand is processed.

- The BaseFormDerivative handler of DerivativeRuleDispatcher lowers
  compound algebra in its operand before expanding the inner derivatives.
- map_integrand_dags no longer special-cases BaseFormDerivative. Like
  for a CoefficientDerivative, replace raises on a BaseFormDerivative
  whose derivatives have not been applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate base form operators with local rules

The Gateaux derivative of an integrand with a base form operator N(u)
was not an integrand: the chain rule term Action(dF/dN, dN/du) is a
BaseForm. So the rule for N recorded it as a pending operation, and
apply_derivatives recovered dF/dN afterwards by replacing and
re-differentiating every derivative node, lifting nested derivatives out
of integrals, and calling itself from inside the traversers. This mixed
up the chain rules of different derivatives in the same expression.

dN/du[v] is itself a base form operator, which UFL already treats as an
expression, so the rules for base form operators are now local:

- GateauxDerivativeRuleset differentiates Interpolate and
  ExternalOperator like any other operator, returning dN/du[v].
- BaseFormDerivativeRuleset differentiates the expressions of a BaseForm
  with a GateauxDerivativeRuleset, and the dispatcher expands the
  operand of a BaseFormDerivative in postorder, including the integrals
  of a Form operand.
- apply_derivatives ends with extract_base_form_operator_actions, which
  turns each base form operator with uncontracted arguments in an
  integrand or argument slot into an Action, numbering its dual argument
  first, or last as for an adjoint when the direction is numbered 0.
- A vanishing derivative is a ZeroBaseForm with the arguments of the
  derivative.
- Interpolate allows its dual argument to share a number with an
  operand argument, as in an integrand, which contracts it.

The pending operations, BaseFormOperatorDerivativeRuleset,
_lift_nested_derivatives and replace_derivative_nodes are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix the bugs behind the base form operator extraction helpers

- replace reconstructed every ExternalOperator and Interpolate it visited,
  giving untouched operators new counts, and ignored a replacement by Zero,
  which is falsy. It now reuses untouched operators and looks up the
  mapping with a default.
- The Gateaux rule for ExternalOperator ignored its argument slots, so the
  Hessian of N(M(u)) lost the term dN/dM[d2M/du2]. N is linear in its
  slots, so the rule adds the product rule over them.
- The orientation of each Action was decided by renumbering the dual
  argument, then re-read from the numbers by _is_adjoint, _operator_argument
  and _action, which raised for a composition. _contract now chooses the
  orientation once, numbers both contracted arguments, and builds F after
  Nhat is numbered.
- BaseFormOperatorSplitter computed dF/dN by zeroing arguments. dF/dN is now
  the Gateaux derivative with respect to N, and F|_{N=0} uses replace.
- _last_operator documents why the last created operator is not in the
  slots of another one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Restructure base form operator Actions with a DAGTraverser

Replace the isinstance chain of extract_base_form_operator_actions and
the separate recursion of _as_base_form with
BaseFormOperatorActionRestructurer, which registers one rule per BaseForm
type. Form and BaseFormOperator share _contract, which builds dF/dN by
the Gateaux derivative of either and renumbers the dual argument of N by
reconstructing it, so _as_base_form no longer takes the dual argument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate the gradient of a base form operator

The Gateaux rule for Grad treated grad(N) as the gradient of a
coefficient, so when N was not the differentiation variable it returned
zero and dropped the chain rule through N. The derivative of
inner(grad(Interpolate(u, V)), grad(v))*dx with respect to u vanished,
which broke the matfree Newton solve in Firedrake's
test_interp_dual.py::test_solve_interp_u. D[grad(N)] = grad(D[N]).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Check the function spaces of an Action on the derivative of a BaseForm

_check_function_spaces unwrapped every CoefficientDerivative to its
operand, to reach the coefficient of the derivative of an Expr. A
BaseFormDerivative is a CoefficientDerivative too, but its operand lacks
the argument of the direction, so Action(derivative(Action(c, u), c), t)
read the arguments of the 0-form Action(c, u) and raised IndexError. This
broke the TLM of Firedrake's adjoint/test_assemble.py::test_assemble_1_forms_tlm
once derivatives of BaseForms were expanded only in expand_derivatives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Inline the Gateaux derivative rules in _contract

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Return the unrestructured derivative of a base form operator

apply_derivatives no longer restructures a Form with a base form operator N
that has an uncontracted argument, such as dN/du[v], into
F|_{N=0} + Action(dF/dN, N). The local-rule result is already a valid
BaseForm with the same arguments, and UFL's action, adjoint, replace,
derivative and compute_form_data handle it. Composing N with dF/dN is a
choice of how to assemble, so it belongs to the assembler.

Delete BaseFormOperatorActionRestructurer and its helpers. Rewrite the
tests that asserted the Action representation to state the chain rule on
the Form instead, e.g. dF/du[uhat] = dF/dN[dN/du[uhat]], and drop
test_derivative_keeps_argument_class, which tested the restructurer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop replace_derivative_nodes tests and duplicate __eq__ after restacking on FEniCS#527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Keep BaseFormOperatorDerivative.__eq__ at its original site

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Drop the empty-Form filter in map_integrands

The base form operator chain rule that produced empty Forms in a FormSum
is gone; base form operators are now differentiated by local rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Document why the Gateaux derivative direction is not an Argument

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Extract the direction arguments in one call

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop the unreachable int check in apply_derivatives

map_integrands has returned a ZeroBaseForm for an all-zero FormSum since
FEniCS#494, so the derivative of a BaseForm is never a bare 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Restructured differentiation

* Simplify adjoint actions and fix derivative inheritance

* Move BaseForm restructuring out of the constructors

Action and Adjoint keep only their zero and identity simplifications.
The other rules live in a BaseFormRestructurer DAGTraverser, which
assemblers call through restructure_base_form after expanding
derivatives. Contractions are tried first, so that a sum is distributed
only when no contraction applies to it as a whole.

Action now accepts Sum operands, and the Leibniz rule contracts the last
argument of a left operand of any rank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* restore Adjoint(Adjoint)

* Split a rank 2 dual slot off a base form operator

The restructurer now rewrites N(u; A) as Action(N(u; v*), A) when the
dual slot A has rank 2, after restructuring A. v* is reconstructed from
the first argument of A, so it keeps the form compiler's Argument class,
and it is numbered after the arguments of the other slots so the Action
contracts it with the first argument of A. A rank 1 dual slot still
stays in the operator, so the contraction is assembled directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix mypy in Action derivative rule

* Move vanishing derivative handling to stacked change

* Clarify BaseFormOperator chain-rule tests

* Fix dual-slot form argument handling

* Replace only the argument slots when restructuring base form operators

Renumbering or contracting the arguments of a base form operator used
replace on the whole operator, which also changed the arguments that are
bound inside its operands, such as the Coargument of an operand
Interpolate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Split a rank 2 operator off a primal argument slot

The chain rule puts the rank 2 derivative B of an operand into an
argument slot of a base form operator. The operator is linear in that
slot, so the restructurer splits it off as
N(u; v*, B) -> Action(N(u; v*, uhat), B), and each operand can be
assembled on its own. An Action contracts one argument, so an operator
with more than one such slot is not split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Contract a rank 1 operand first in a chain of Actions

Action(x, Action(A, B)) -> Action(Action(x, A), B), so that every Action
in the chain gives another rank 1 operand. The adjoint seed then reaches
the dual slot of a base form operator at the end of the chain, and the
operator is assembled as the action of its adjoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Replace inside a BaseFormDerivative without applying it

replace maps the differentiated base form and the differentiation
variables, and keeps the derivative lazy. It still raises if a
differentiation variable maps to the same expression as another
coefficient of the form, because the replacement does not commute with
the derivative in that case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate an Adjoint that does not depend on the variable

The derivative of Adjoint(A) is a ZeroBaseForm when A does not depend on
the differentiation variable. Otherwise the derivative of the 2-form A is
a 3-form, whose adjoint is not defined, so apply_derivatives raises
NotImplementedError. derivative no longer rejects an Adjoint eagerly,
because the expansion now handles it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Consolidate BaseForm restructuring into cached traversals

Associate rank-one contractions before absorbing arguments into forms and operator slots. Keep sums factored when possible and revisit only changed operators and actions.

Specify assemblability and assembly costs in regression tests, and make Matrix subclass equality reflexive.

* Remove outer_form argument plumbing

* Materialize dual-slot arguments

* Annotate delayed imports

* Contract the highest-numbered argument of a form dual slot

A form dual slot now contracts its highest-numbered primal argument, as
the left operand of an Action does, so Interpolate(u, F) numbers its
free arguments like Action(F, Interpolate(u, V)), starting at 0.
Coarguments in the slot stay free.

The stored slot is renumbered once, at construction, and argument
analysis reads it back. BaseFormOperatorDerivative rejects duplicate
argument numbers, and apply_derivatives numbers the direction after the
highest operator argument instead of after the argument count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Simplify the contracted argument renumbering

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop the dead BaseForm guard in apply_derivatives

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop outer_form leftovers in Coargument and BaseFormOperator

Coargument.arguments() duplicated the inherited BaseForm.arguments().
Check the dual-slot space with an explicit branch, and attach the
Coargument comment to the dual-slot arguments it describes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Inline _restructure_contracted_operator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Read the renumbered dual-slot arguments from the stored slot

The BaseFormOperator constructor stores the dual slot with its free
arguments already renumbered, so renumbering again is a no-op.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that dual-slot contraction ignores numbering gaps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Split a form dual slot when the primal slots use argument 0

Number the contracted argument of the slot first instead of raising.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep arguments contracted inside a dual slot when renumbering

Renumbering the slot's own arguments with replace could rename one onto an
argument that an Action inside the slot contracts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number vhat from the contracted argument of the dual slot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expand derivatives before restructuring BaseForms

Move derivative expansion into the public restructuring entry point and preserve ordinary Forms for the form compiler. Cover unexpanded interpolation derivatives, nested derivatives, and complex preprocessing.

Assisted-by: OpenAI Codex

* Contract a form dual slot as an Action does

Renumbering the free arguments in the constructor rewrote the user's form
with replace, which needed _contained_arguments to avoid arguments that inner
Actions contract. That traversal was exponential in the depth of shared
subexpressions.

The free arguments now keep their numbers, and N(u; F) contracts the argument
that an Action would. If the primal slots use number 0, the output of N is
numbered last, so N is the left operand and F's lowest argument is contracted.
Otherwise F is the left operand and its highest argument is contracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number the bound argument of a one-form dual slot from zero

Contracting the lowest argument of a 2-form leaves a one-form whose only
argument is numbered 1. In a dual slot that argument is bound, so its number is
free, and assembling the form needs it numbered from zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the contracted argument of a form dual slot under differentiation

An Argument 0 in the primal slots contracted the lowest argument of a form
dual slot even when the form had no Argument 0. So differentiating
Interpolate(u, F) in a direction numbered 0 changed which argument was
contracted, and with it the target space. Argument 0 now only replaces an
Argument 0 of the form, and D_w[v] I(w, v*) = I(v, v*) holds as written.

dual_slot_action builds N(u; A) as an Action for both restructure_base_form
and the product rule through the dual slot, which assumed that the contracted
argument of Dv* was its lowest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Compare derivatives of forms that contain base form operators

A Form has no operands, but expr_equals expected every node of a DAG to
declare whether it is terminal. It raised an AttributeError when it
reached a Form inside two equal, distinct BaseFormDerivatives. Declare a
Form as a leaf, so that expr_equals delegates to Form.equals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Differentiate a dual slot in a direction with the same number

The derivative of a dual slot holds the direction and the contracted
argument of the slot. If both had the same number, the derivative could
not be represented. Number the contracted argument after the direction
before differentiating the slot. The argument is bound, so its number is
free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Number the default derivative direction from the free arguments

extract_arguments also counted the contracted argument of a dual slot,
which left a gap in the argument numbers of the derivative. Use
BaseForm.arguments, which only holds the free arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Drop a form sum component with a vanishing derivative

A vanishing component stayed in the FormSum as an empty Form, which has
no arguments and cannot be assembled. Convert it to a ZeroBaseForm with
the arguments of the component before the map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Number the contracted argument of a dual slot in dual_slot_action

dual_slot_action now owns the number of the contracted argument. It
numbers the argument before the slot is differentiated, so that the
derivative rule needs no renumbering of its own. The orientation of the
Action only depends on whether the primal slots use number 0. Thus the
derivative of a dual slot is always Action(A, Nhat) if they do not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Test restructuring the actions of an operator composition

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Treat linear maps in primal slots and their bound Coarguments correctly

extract_type could return a BaseFormOperator found through an operand when
asked for other types, so differentiating N(I(N(I(u)))) raised. Filter the
result by the requested types once, at the end.

Any rank-two BaseForm in a primal slot is a linear map, not only a
BaseFormOperator. Split an Action or a FormSum in that slot into an Action,
as for an operator.

The Coargument of an operator in an operand or a primal slot pairs with the
output of that operator, so it is bound. Replacer substituted it, which gave
Interpolate(2 * Interpolate(w, c), c) for the action of c on
Interpolate(2 * Interpolate(w, V), V). Replace a Coargument only in the dual
slot, for every BaseFormOperator. This makes _replace_argument_slots redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Move restructure and replace tests to their own files

Collect test_restructure_* in test_restructure_base_form.py and test_replace*
in test_replace.py. Group the restructure tests by topic, split the large
test_restructure_base_form test into focused tests, use one family of function
space fixtures, and assign one name per line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Name the replaced coefficients in the BaseFormDerivative replace rule

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Compare a ScalarValue with a Python complex

ComplexValue(1 - 2j) == 1 - 2j was False, since ScalarValue.__eq__ only
accepted int and float. FormSum compares its weights with ==, so weights
conjugated with Conj did not equal the same weights given as Python numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Return N(u; Dv*) from the derivative and split it in restructure_base_form

The derivative of N(u; v*) built Action(N(u; vhat), Dv*). The Action belongs
in restructure_base_form, which already splits a rank-two dual slot, so the
derivative now returns N(u; Dv*). The contracted argument is still numbered
before differentiating, by _number_contracted_argument, since Dv* can bind
other arguments. dual_slot_action is inlined into its only caller.

Number the remaining arguments of Action(x, F) from zero when absorbing x into
the Form F, as the operator branch does. Normalizing the adjoint action of an
interpolation and a mass term changed the free arguments from (0,) to (0, 1):
the Form kept its argument 1, which Firedrake cannot assemble.

Rename ActionContractor to ActionAbsorber: every Action contracts an argument,
while this pass removes the Action by absorbing an operand. Move distribution
over expression Sums to a new ActionDistributor, which runs after absorption so
that a Form or operator can still absorb a sum whole. Document the rules of
each traverser in a table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Report the rank of the components of a FormSum

FormSum took the union of the arguments of its components, so Form(v_0) +
Action(x, Matrix), whose Action keeps the number of the Matrix argument,
reported (0, 1) although it has rank one. Report the arguments of the highest
rank component with the lowest numbers. An empty Form has no arguments, so
rhs(a) + c keeps the rank of c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Merge the Action passes of restructure_base_form into one rule list

The operands of an Action are already restructured when the Action is reached,
so ActionAssociator, ActionAbsorber and ActionDistributor re-walked finished
subtrees and called back into the restructurer whenever an operand changed.
Apply their rules in order in a single handler, with absorption still ahead of
distribution. BaseFormTraversal has one subclass left, so merge it too.

Test distribution over an expression Sum, which had no direct test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Simplify Action(x, Adjoint(A)) and absorb x into a primal slot

Action(Adjoint(A), x) became Action(x, A), but its mirror Action(x, Adjoint(A)),
which is A x, assembled the adjoint as a rank-two matrix. Likewise an operator
whose lowest-numbered argument is in a primal slot, as Adjoint(N) gives, could
not absorb x. Both now contract x without a rank-two assembly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Share the dual slot rule and tidy the BaseForm derivative rules

Find the contracted argument of a split dual slot with
_split_dual_slot_arguments instead of deriving it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Name the restructuring rules after their maths

State the formula beside each Action rule and use one set of symbols in the
docstring tables, which had an undefined R and used a and b for both weights
and operands. Use the names of the docstrings in the code: vstar, uhat_B,
vstar_B, Nhat and contracted. Shorten the test names to labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Take the Adjoint of a row for the column of an Action

Action(x, A) is the row x^H A, so its free argument keeps the number it has in
A. The column is its Adjoint, A^H x = (x^H A)^H, so Action(Adjoint(A), x)
restructures to Adjoint(Action(x, A)), which reports v_0. Adjoint accepts a
row, and a sum of rows becomes a sum of columns before the Adjoint is taken.
FormSum.arguments() is the plain union again.

Differentiating these Actions failed because a contracted argument is a bound
variable, while the direction and the renumbered arguments were chosen from the
free arguments only. So:
- The default direction comes after the lowest argument that an Action contracts
  on its right.
- The Action rule shifts the contracted argument of the left operand and the
  arguments above it, including those contracted in nested Actions.
- Action(L, v) with an Argument v puts v in the contracted slot of L, rather than
  returning L with its old number.
- Absorbing into the last argument of a Form shifts the free arguments down to
  zero, as absorbing into the first one does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Share the column of a sum of rows and keep Action(x, A) sum weights

Absorbing x turns a row into a column, so a sum of rows with an absorbed
component and the Adjoint of a sum of rows both give conj(c) A^H x +
conj(d) B^H x. BaseFormRestructurer.column_sum now does this for both,
replacing the module-level _column helper, and also splits nested sums.

x^H (c A + d B) = c x^H A + d x^H B is linear in the weights, so stop
conjugating them when distributing Action(x, c A + d B).

Drop the rule for Action(Adjoint(c A + d B), x), since A^H x = (x^H A)^H
and column_sum already give that result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate an operator composed with a form with respect to the operator

N(u; F) is F composed with N(u; v*), and F is linear, so its derivative
with respect to N in the direction v is F[v]. The derivative rules only
matched N with a Coargument in its dual slot, so this derivative was zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Hash scalar values by value, as they compare

ScalarValue compares by value, but hashed its repr, as other terminals
do. -2j is complex(-0.0, -2.0), which equals (2j).conjugate() but has a
different repr, so Fx + -2j * Gx compared unequal to an equal form, as
Form.equals compares hashes first. ScalarValue now hashes its type code
and value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Renumber derivative directions when restructuring their operand

derivative() numbers the default direction from the unrestructured
operand, so the Hessian of Action(L(u), Interpolate(u, V)) reported
[1, 2], and [0, 1, 2] once restructured, while Interpolate(u, L(u))
reports [0, 1].

restructure_base_form now restructures before and after expanding
derivatives, with one BaseFormRestructurer so the second pass reuses its
cache. Its BaseFormDerivative handler restructures the operand and moves
a direction numbered at or above the default to stay right after the
free arguments of the restructured operand. derivative() and the handler
share default_direction_number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Inline operators into the Forms that absorb them

A Form absorbs an operator as it absorbs an expression: Action(F, N) is
F(v_0, N) and Action(N, F) is conj(F(N, v_1)), and a Form in the dual slot of
an operator absorbs the operator. The Coargument bound by an inlined operator
takes the lowest number its arguments leave, as for Interpolate(expr, V).

Differentiating a Form with an operator whose primal slots hold Arguments
substitutes the derivative of the operator for Nhat, since an Action would
contract one of those Arguments instead of vhat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number the default direction after every Action's contracted argument

A derivative reaches the right operand of every Action in the form, not
only of the Actions nested as left operands, so default_direction_number
traverses the whole form for Actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test the derivative of an Action of a FormSum of Actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Conjugate an absorbed Form only for a function on the left

_absorb conjugated every Form that absorbed its left operand, as for
Action(w, F) with a function w, where F(w, v_0) leaves the linear slot of F
free. A Form, a dual operator or a rank-two operator on the left keeps the
test argument of F antilinear, so its result is F(left) as it stands.
Interpolate(w, Interpolate(u, a)) gave conj(a(I w, I u)), which conjugates
the coefficients of a, and the derivatives through an operator gave the
conjugate of their plain UFL counterparts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Accept a primal operator whose Coargument is not its lowest argument

Interpolate required the first argument of a BaseForm expression to be
its Coargument. Interpolate(w_0, V1) numbers its Coargument 1, after w_0,
so Interpolate(Interpolate(w_0, V1), V2) was rejected, and restructuring
Interpolate(w, Interpolate(v, F)) into F(I I w) failed. An expression is
primal when it has one Coargument, whatever its number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Say that Interpolate expects a primal expression

The message named the first argument, which reads as the first Argument
of the expression now that the Coargument can have any number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test a FormSum whose first component vanishes under differentiation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Compose Forms only with operators up to max_composed_rank

restructure_base_form takes max_composed_rank, default 1. A Form composes
with an operator, or fills its dual slot, only if the operator has at most
that rank; otherwise the Action is kept. Rename absorb to compose, the term
UFL already uses for N(u; A), and inline _absorb into
BaseFormRestructurer.compose.

Run the affected tests with max_composed_rank 1 and 2, asserting the exact
restructured result for each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep a rank-one Form in the dual slot of a non-composable operator

A Form fills the dual slot of an operator whatever its rank. When splitting
N(u; F) for a rank-one Form F, keep N(u; F) if N(u; vhat) is not composable,
instead of keeping the Action. A Form of higher rank still keeps its Action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
pbrubeck added a commit to firedrakeproject/ufl that referenced this pull request Nov 13, 2026
* replace: only expand CoefficientDerivative

* From end support for ufl.algorithms.expand_coefficient_derivatives

* Fix mypy module not callable

* tests

* fix typing

* add failing test

* Fix CoefficientDerivativeRuleDispatcher choking on Grad(Indexed(...))

CoefficientDerivativeRuleDispatcher registered the abstract Derivative
type to reuse_if_untouched, so that foreign Derivative subtypes (e.g.
irksome.TimeDerivative) are left alone. But since Grad, ReferenceGrad,
etc. are themselves Derivative subtypes with no more specific
registration on this subclass, they were *also* being left untouched
-- including when they appear inside the content of a
CoefficientDerivative that is about to be Gateaux-differentiated. That
content needs the same normalization the full DerivativeRuleDispatcher
gives it (e.g. pushing a spatial Grad down through Indexed to a bare
terminal) before GateauxDerivativeRuleset can process it; skipping
that step left GateauxDerivativeRuleset.Grad staring at
Grad(Indexed(Coefficient, ...)) instead of Grad(Coefficient), which it
does not know how to handle -- this is what test_replace_mixed_element
hit via replace() on a mixed-element coefficient.

Fix: recurse into a CoefficientDerivative's own content with a plain
(cached) DerivativeRuleDispatcher instead of `self`, so nested content
gets full normalization while everything *outside* CoefficientDerivative
nodes keeps the narrow, foreign-Derivative-safe treatment. Also fix the
resulting equality-vs-signature test flakiness in
test_replace_mixed_element (independently built expressions can differ
in dummy index numbering) and two pre-existing, unrelated mypy
var-annotated errors in test_classcoverage.py that blocked `mypy test/`
on this branch.

* Fix dual-slot form argument counting

* Compare the stored function space in Interpolate.__eq__

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Fix dual-slot form argument handling

* Only differentiate derivative nodes in the base form operator chain rule

The chain rule dF/du = ∂F/∂u + Σ Action(∂F/∂N, dN/du) computes ∂F/∂N by
mapping the derivative rules over every integrand and FormSum component
of F. Integrands without a derivative node do not depend on `u` through
N, but they were passed through unchanged, so they leaked into ∂F/∂N.
For `derivative(J, u) + F` this gave a spurious Action(F, dN/du), and
for a FormSum with a Cofunction it raised a TypeError.

Map integrands without a derivative node to zero, and drop the empty
Forms that this leaves in a FormSum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate the dual slot of base form operators

A base form operator N(u; v*) is linear in its dual slot v*. When v*
depends on u, the product rule gives

    D[N(u; v*(u))][û] = ∂N/∂u(u; v*)[û] + N(u; Dv*[û]),

but only the first term was computed. For J = j(I u) with I an
interpolation, dJ/du is the adjoint interpolation I*(j'(I u)), whose
dual slot j'(I u) carries all of its dependence on u. The second
derivative of J was therefore ZeroBaseForm instead of I* j''(I u) I.

Add the dual-slot term, as N(u; Dv*) when Dv* is a Form and as
Action(N(u; v̂), Dv*) otherwise. To differentiate the result again:

- A BaseFormOperatorDerivative whose inner derivative is a FormSum or an
  Action is differentiated with `derivative`, by linearity and the
  Leibniz rule.
- `derivative` of a Form with base form operators expands its inner
  derivatives first.
- The Leibniz rule for Action numbers the new argument after the
  arguments of the Action, expands the derivatives of both slots and
  drops vanishing terms. `action` no longer requires a BaseForm on the
  left, since `Action` accepts a Coefficient or an Argument there.
- `Interpolate._ufl_expr_reconstruct_` accepts `argument_slots`.
- Base form operators hash their argument slots and derivatives: the
  `ufl_type` decorator replaced `BaseFormOperator.__hash__`, so N(u; v*)
  and N(u; Dv*) collided. BaseFormOperatorDerivative compares operands
  instead of raising NotImplementedError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expand base form derivatives only in expand_derivatives

`derivative` now only builds derivative nodes. For a Form with base form
operators and nested derivatives, it used to expand the inner derivatives
eagerly, so the type of `derivative(F, u)` depended on the contents of F:
a Form for F = J, but a FormSum or an Action for F = derivative(J, u).
The Action branch also expanded both of its slots. `apply_derivatives`
called back into `derivative`, and `derivative` called `expand_derivatives`.

Move this logic into `apply_derivatives`, so that `expand_derivatives` is
the only place where a derivative can turn a Form into another BaseForm:

- Nested derivatives of a Form with base form operators are expanded from
  the inside out. The inner derivative may be a FormSum or an Action, which
  cannot live inside an integral, so the outer derivative is applied to it
  at the BaseForm level.
- `derivative` of an Action returns a BaseFormDerivative. The Leibniz rule
  is applied when it is expanded.
- `map_integrands` maps through a BaseFormDerivative of a Form, FormSum or
  Action instead of treating it as an integrand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate BaseForms in one ruleset and collapse Action onto any dual slot

The derivatives of FormSums, Actions, Forms and base form operators were
expanded by free functions that dispatched on type. They now live in
BaseFormDerivativeRuleset, a DAGTraverser, and DerivativeRuleDispatcher
has a single BaseFormDerivative handler that expands the inner
derivatives first.

The dual-slot term of D[N(u; v*)] is always Action(N(u; vhat), Dv*).
Action.__new__ collapses Action(N(u; vhat), F) to N(u; F) for every
base form operator, not only Interpolate, when F has one argument.

To make both representations agree:

- A base form operator contracts the first argument of any dual slot
  that is not a Coargument, a Form included, so N(u; F) has the
  arguments of Action(N(u; vhat), F).
- Base form operators keep their target function space, which they use
  to reconstruct, compare and hash, so that rank-0 operators work. A
  rank-0 operator adds as a BaseForm.
- Action sorts its arguments by number, like any other BaseForm.
- The Leibniz rule for Action numbers the argument of the left operand
  after the direction instead of reordering with an adjoint, which was
  ignored when the left operand is not a Form.

Also:

- Nested derivatives of integrands with base form operators are lifted
  to a BaseFormDerivative of a Form.
- map_integrand_dags, not map_integrands, maps through a
  BaseFormDerivative of a BaseForm.
- Form has ufl_operands = (), like every other BaseForm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Allow Interpolate arguments to be numbered non-contiguously

The dual-slot term of D[N(u; v*)] is Action(N(u; vhat), Dv*), with vhat
numbered after the other arguments of N so that the Action contracts it.
For a forward interpolation Interpolate(2 * v_1, v*_0) this builds
Interpolate(2 * v_1, vhat_2), which the contiguity check rejected before
Action could drop the vanishing term. Arguments need not be contiguous in
such intermediate expressions, so only check that the two operands do not
share argument numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add only the arguments of the direction to zero BaseForms

The Gateaux rules for Coargument, Cofunction, Matrix, ZeroBaseForm and a
constant Interpolate returned ZeroBaseForm(o.arguments() + self._v),
which appends the direction even when it is a Coefficient, as in a
tangent linear model. The dual-slot term Action(N(u; vhat), Dv*) then
failed to number the arguments of the Action. Add only the arguments
of the direction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Lower compound algebra when expanding a BaseFormDerivative

map_integrand_dags mapped through a BaseFormDerivative of a BaseForm, so
that apply_algebra_lowering in expand_derivatives would lower the
integrands of its operand. Since a Form has no ufl_operands, the DAG of
the derivative stops at the BaseForm, and the expansion of the
derivative is the place where its operand is processed.

- The BaseFormDerivative handler of DerivativeRuleDispatcher lowers
  compound algebra in its operand before expanding the inner derivatives.
- map_integrand_dags no longer special-cases BaseFormDerivative. Like
  for a CoefficientDerivative, replace raises on a BaseFormDerivative
  whose derivatives have not been applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate base form operators with local rules

The Gateaux derivative of an integrand with a base form operator N(u)
was not an integrand: the chain rule term Action(dF/dN, dN/du) is a
BaseForm. So the rule for N recorded it as a pending operation, and
apply_derivatives recovered dF/dN afterwards by replacing and
re-differentiating every derivative node, lifting nested derivatives out
of integrals, and calling itself from inside the traversers. This mixed
up the chain rules of different derivatives in the same expression.

dN/du[v] is itself a base form operator, which UFL already treats as an
expression, so the rules for base form operators are now local:

- GateauxDerivativeRuleset differentiates Interpolate and
  ExternalOperator like any other operator, returning dN/du[v].
- BaseFormDerivativeRuleset differentiates the expressions of a BaseForm
  with a GateauxDerivativeRuleset, and the dispatcher expands the
  operand of a BaseFormDerivative in postorder, including the integrals
  of a Form operand.
- apply_derivatives ends with extract_base_form_operator_actions, which
  turns each base form operator with uncontracted arguments in an
  integrand or argument slot into an Action, numbering its dual argument
  first, or last as for an adjoint when the direction is numbered 0.
- A vanishing derivative is a ZeroBaseForm with the arguments of the
  derivative.
- Interpolate allows its dual argument to share a number with an
  operand argument, as in an integrand, which contracts it.

The pending operations, BaseFormOperatorDerivativeRuleset,
_lift_nested_derivatives and replace_derivative_nodes are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix the bugs behind the base form operator extraction helpers

- replace reconstructed every ExternalOperator and Interpolate it visited,
  giving untouched operators new counts, and ignored a replacement by Zero,
  which is falsy. It now reuses untouched operators and looks up the
  mapping with a default.
- The Gateaux rule for ExternalOperator ignored its argument slots, so the
  Hessian of N(M(u)) lost the term dN/dM[d2M/du2]. N is linear in its
  slots, so the rule adds the product rule over them.
- The orientation of each Action was decided by renumbering the dual
  argument, then re-read from the numbers by _is_adjoint, _operator_argument
  and _action, which raised for a composition. _contract now chooses the
  orientation once, numbers both contracted arguments, and builds F after
  Nhat is numbered.
- BaseFormOperatorSplitter computed dF/dN by zeroing arguments. dF/dN is now
  the Gateaux derivative with respect to N, and F|_{N=0} uses replace.
- _last_operator documents why the last created operator is not in the
  slots of another one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Restructure base form operator Actions with a DAGTraverser

Replace the isinstance chain of extract_base_form_operator_actions and
the separate recursion of _as_base_form with
BaseFormOperatorActionRestructurer, which registers one rule per BaseForm
type. Form and BaseFormOperator share _contract, which builds dF/dN by
the Gateaux derivative of either and renumbers the dual argument of N by
reconstructing it, so _as_base_form no longer takes the dual argument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate the gradient of a base form operator

The Gateaux rule for Grad treated grad(N) as the gradient of a
coefficient, so when N was not the differentiation variable it returned
zero and dropped the chain rule through N. The derivative of
inner(grad(Interpolate(u, V)), grad(v))*dx with respect to u vanished,
which broke the matfree Newton solve in Firedrake's
test_interp_dual.py::test_solve_interp_u. D[grad(N)] = grad(D[N]).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Check the function spaces of an Action on the derivative of a BaseForm

_check_function_spaces unwrapped every CoefficientDerivative to its
operand, to reach the coefficient of the derivative of an Expr. A
BaseFormDerivative is a CoefficientDerivative too, but its operand lacks
the argument of the direction, so Action(derivative(Action(c, u), c), t)
read the arguments of the 0-form Action(c, u) and raised IndexError. This
broke the TLM of Firedrake's adjoint/test_assemble.py::test_assemble_1_forms_tlm
once derivatives of BaseForms were expanded only in expand_derivatives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Inline the Gateaux derivative rules in _contract

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Return the unrestructured derivative of a base form operator

apply_derivatives no longer restructures a Form with a base form operator N
that has an uncontracted argument, such as dN/du[v], into
F|_{N=0} + Action(dF/dN, N). The local-rule result is already a valid
BaseForm with the same arguments, and UFL's action, adjoint, replace,
derivative and compute_form_data handle it. Composing N with dF/dN is a
choice of how to assemble, so it belongs to the assembler.

Delete BaseFormOperatorActionRestructurer and its helpers. Rewrite the
tests that asserted the Action representation to state the chain rule on
the Form instead, e.g. dF/du[uhat] = dF/dN[dN/du[uhat]], and drop
test_derivative_keeps_argument_class, which tested the restructurer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop replace_derivative_nodes tests and duplicate __eq__ after restacking on FEniCS#527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Keep BaseFormOperatorDerivative.__eq__ at its original site

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Drop the empty-Form filter in map_integrands

The base form operator chain rule that produced empty Forms in a FormSum
is gone; base form operators are now differentiated by local rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Document why the Gateaux derivative direction is not an Argument

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Extract the direction arguments in one call

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop the unreachable int check in apply_derivatives

map_integrands has returned a ZeroBaseForm for an all-zero FormSum since
FEniCS#494, so the derivative of a BaseForm is never a bare 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Restructured differentiation

* Simplify adjoint actions and fix derivative inheritance

* Move BaseForm restructuring out of the constructors

Action and Adjoint keep only their zero and identity simplifications.
The other rules live in a BaseFormRestructurer DAGTraverser, which
assemblers call through restructure_base_form after expanding
derivatives. Contractions are tried first, so that a sum is distributed
only when no contraction applies to it as a whole.

Action now accepts Sum operands, and the Leibniz rule contracts the last
argument of a left operand of any rank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* restore Adjoint(Adjoint)

* Split a rank 2 dual slot off a base form operator

The restructurer now rewrites N(u; A) as Action(N(u; v*), A) when the
dual slot A has rank 2, after restructuring A. v* is reconstructed from
the first argument of A, so it keeps the form compiler's Argument class,
and it is numbered after the arguments of the other slots so the Action
contracts it with the first argument of A. A rank 1 dual slot still
stays in the operator, so the contraction is assembled directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix mypy in Action derivative rule

* Move vanishing derivative handling to stacked change

* Clarify BaseFormOperator chain-rule tests

* Fix dual-slot form argument handling

* Replace only the argument slots when restructuring base form operators

Renumbering or contracting the arguments of a base form operator used
replace on the whole operator, which also changed the arguments that are
bound inside its operands, such as the Coargument of an operand
Interpolate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Split a rank 2 operator off a primal argument slot

The chain rule puts the rank 2 derivative B of an operand into an
argument slot of a base form operator. The operator is linear in that
slot, so the restructurer splits it off as
N(u; v*, B) -> Action(N(u; v*, uhat), B), and each operand can be
assembled on its own. An Action contracts one argument, so an operator
with more than one such slot is not split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Contract a rank 1 operand first in a chain of Actions

Action(x, Action(A, B)) -> Action(Action(x, A), B), so that every Action
in the chain gives another rank 1 operand. The adjoint seed then reaches
the dual slot of a base form operator at the end of the chain, and the
operator is assembled as the action of its adjoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Replace inside a BaseFormDerivative without applying it

replace maps the differentiated base form and the differentiation
variables, and keeps the derivative lazy. It still raises if a
differentiation variable maps to the same expression as another
coefficient of the form, because the replacement does not commute with
the derivative in that case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate an Adjoint that does not depend on the variable

The derivative of Adjoint(A) is a ZeroBaseForm when A does not depend on
the differentiation variable. Otherwise the derivative of the 2-form A is
a 3-form, whose adjoint is not defined, so apply_derivatives raises
NotImplementedError. derivative no longer rejects an Adjoint eagerly,
because the expansion now handles it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Consolidate BaseForm restructuring into cached traversals

Associate rank-one contractions before absorbing arguments into forms and operator slots. Keep sums factored when possible and revisit only changed operators and actions.

Specify assemblability and assembly costs in regression tests, and make Matrix subclass equality reflexive.

* Remove outer_form argument plumbing

* Materialize dual-slot arguments

* Annotate delayed imports

* Contract the highest-numbered argument of a form dual slot

A form dual slot now contracts its highest-numbered primal argument, as
the left operand of an Action does, so Interpolate(u, F) numbers its
free arguments like Action(F, Interpolate(u, V)), starting at 0.
Coarguments in the slot stay free.

The stored slot is renumbered once, at construction, and argument
analysis reads it back. BaseFormOperatorDerivative rejects duplicate
argument numbers, and apply_derivatives numbers the direction after the
highest operator argument instead of after the argument count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Simplify the contracted argument renumbering

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop the dead BaseForm guard in apply_derivatives

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop outer_form leftovers in Coargument and BaseFormOperator

Coargument.arguments() duplicated the inherited BaseForm.arguments().
Check the dual-slot space with an explicit branch, and attach the
Coargument comment to the dual-slot arguments it describes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Inline _restructure_contracted_operator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Read the renumbered dual-slot arguments from the stored slot

The BaseFormOperator constructor stores the dual slot with its free
arguments already renumbered, so renumbering again is a no-op.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that dual-slot contraction ignores numbering gaps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Split a form dual slot when the primal slots use argument 0

Number the contracted argument of the slot first instead of raising.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep arguments contracted inside a dual slot when renumbering

Renumbering the slot's own arguments with replace could rename one onto an
argument that an Action inside the slot contracts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number vhat from the contracted argument of the dual slot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expand derivatives before restructuring BaseForms

Move derivative expansion into the public restructuring entry point and preserve ordinary Forms for the form compiler. Cover unexpanded interpolation derivatives, nested derivatives, and complex preprocessing.

Assisted-by: OpenAI Codex

* Expand coefficient derivatives without expanding spatial operators

Use shared differentiation rules for selective coefficient and BaseForm expansion in replacement and restructuring. Preserve spatial operators, traverse operator slots, and cover structural replacement, nested derivatives, and shared integrands.

Assisted-by: OpenAI Codex

* Share type preservation across DAG transformations

Let algebra lowering and differentiation preserve selected operator types while transforming their operands inside the memoized traversal. Use this policy for targeted coefficient derivatives, including foreign derivative types.

Assisted-by: OpenAI Codex

* Clarify derivative regression test docstrings

Assisted-by: OpenAI Codex

* Contract a form dual slot as an Action does

Renumbering the free arguments in the constructor rewrote the user's form
with replace, which needed _contained_arguments to avoid arguments that inner
Actions contract. That traversal was exponential in the depth of shared
subexpressions.

The free arguments now keep their numbers, and N(u; F) contracts the argument
that an Action would. If the primal slots use number 0, the output of N is
numbered last, so N is the left operand and F's lowest argument is contracted.
Otherwise F is the left operand and its highest argument is contracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number the bound argument of a one-form dual slot from zero

Contracting the lowest argument of a 2-form leaves a one-form whose only
argument is numbered 1. In a dual slot that argument is bound, so its number is
free, and assembling the form needs it numbered from zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the contracted argument of a form dual slot under differentiation

An Argument 0 in the primal slots contracted the lowest argument of a form
dual slot even when the form had no Argument 0. So differentiating
Interpolate(u, F) in a direction numbered 0 changed which argument was
contracted, and with it the target space. Argument 0 now only replaces an
Argument 0 of the form, and D_w[v] I(w, v*) = I(v, v*) holds as written.

dual_slot_action builds N(u; A) as an Action for both restructure_base_form
and the product rule through the dual slot, which assumed that the contracted
argument of Dv* was its lowest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Compare derivatives of forms that contain base form operators

A Form has no operands, but expr_equals expected every node of a DAG to
declare whether it is terminal. It raised an AttributeError when it
reached a Form inside two equal, distinct BaseFormDerivatives. Declare a
Form as a leaf, so that expr_equals delegates to Form.equals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Differentiate a dual slot in a direction with the same number

The derivative of a dual slot holds the direction and the contracted
argument of the slot. If both had the same number, the derivative could
not be represented. Number the contracted argument after the direction
before differentiating the slot. The argument is bound, so its number is
free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Number the default derivative direction from the free arguments

extract_arguments also counted the contracted argument of a dual slot,
which left a gap in the argument numbers of the derivative. Use
BaseForm.arguments, which only holds the free arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Drop a form sum component with a vanishing derivative

A vanishing component stayed in the FormSum as an empty Form, which has
no arguments and cannot be assembled. Convert it to a ZeroBaseForm with
the arguments of the component before the map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Expand base form derivatives selectively in replace

The replacement acted on the differentiated base form and on the
differentiation variables of a lazy BaseFormDerivative. That gave a zero
if a variable mapped to an expression, and it could not represent a
variable that mapped to another coefficient of the form. Apply the
replacement to the result of expand_coefficient_derivatives, which holds
for any mapping and preserves spatial and foreign derivatives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Number the contracted argument of a dual slot in dual_slot_action

dual_slot_action now owns the number of the contracted argument. It
numbers the argument before the slot is differentiated, so that the
derivative rule needs no renumbering of its own. The orientation of the
Action only depends on whether the primal slots use number 0. Thus the
derivative of a dual slot is always Action(A, Nhat) if they do not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9Ecj4Sc94jPr56cKBz5

* Test restructuring the actions of an operator composition

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the arguments of a form that vanishes under differentiation

An empty Form has no arguments. A form whose coefficient derivatives
vanish therefore lost its rank in expand_coefficient_derivatives, and
replace returned Form([]) for a zero block of a mixed Jacobian. Return a
ZeroBaseForm with the arguments of the form before differentiation from
both apply_derivatives and apply_coefficient_derivatives.

compute_form_data can now see a ZeroBaseForm, so give it integrals() and
constants(), which are empty. FormData reads the rank from the original
form, so a form that vanishes in the pipeline keeps its rank and signature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Treat linear maps in primal slots and their bound Coarguments correctly

extract_type could return a BaseFormOperator found through an operand when
asked for other types, so differentiating N(I(N(I(u)))) raised. Filter the
result by the requested types once, at the end.

Any rank-two BaseForm in a primal slot is a linear map, not only a
BaseFormOperator. Split an Action or a FormSum in that slot into an Action,
as for an operator.

The Coargument of an operator in an operand or a primal slot pairs with the
output of that operator, so it is bound. Replacer substituted it, which gave
Interpolate(2 * Interpolate(w, c), c) for the action of c on
Interpolate(2 * Interpolate(w, V), V). Replace a Coargument only in the dual
slot, for every BaseFormOperator. This makes _replace_argument_slots redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Move restructure and replace tests to their own files

Collect test_restructure_* in test_restructure_base_form.py and test_replace*
in test_replace.py. Group the restructure tests by topic, split the large
test_restructure_base_form test into focused tests, use one family of function
space fixtures, and assign one name per line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Name the replaced coefficients in the BaseFormDerivative replace rule

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Annotate LowerCompoundAlgebra for BaseForm input

The traverser dispatches on BaseForm as well as Expr, so its process
signature accepts and returns both. This fixes the mypy errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Compare a ScalarValue with a Python complex

ComplexValue(1 - 2j) == 1 - 2j was False, since ScalarValue.__eq__ only
accepted int and float. FormSum compares its weights with ==, so weights
conjugated with Conj did not equal the same weights given as Python numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Return N(u; Dv*) from the derivative and split it in restructure_base_form

The derivative of N(u; v*) built Action(N(u; vhat), Dv*). The Action belongs
in restructure_base_form, which already splits a rank-two dual slot, so the
derivative now returns N(u; Dv*). The contracted argument is still numbered
before differentiating, by _number_contracted_argument, since Dv* can bind
other arguments. dual_slot_action is inlined into its only caller.

Number the remaining arguments of Action(x, F) from zero when absorbing x into
the Form F, as the operator branch does. Normalizing the adjoint action of an
interpolation and a mass term changed the free arguments from (0,) to (0, 1):
the Form kept its argument 1, which Firedrake cannot assemble.

Rename ActionContractor to ActionAbsorber: every Action contracts an argument,
while this pass removes the Action by absorbing an operand. Move distribution
over expression Sums to a new ActionDistributor, which runs after absorption so
that a Form or operator can still absorb a sum whole. Document the rules of
each traverser in a table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Report the rank of the components of a FormSum

FormSum took the union of the arguments of its components, so Form(v_0) +
Action(x, Matrix), whose Action keeps the number of the Matrix argument,
reported (0, 1) although it has rank one. Report the arguments of the highest
rank component with the lowest numbers. An empty Form has no arguments, so
rhs(a) + c keeps the rank of c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Merge the Action passes of restructure_base_form into one rule list

The operands of an Action are already restructured when the Action is reached,
so ActionAssociator, ActionAbsorber and ActionDistributor re-walked finished
subtrees and called back into the restructurer whenever an operand changed.
Apply their rules in order in a single handler, with absorption still ahead of
distribution. BaseFormTraversal has one subclass left, so merge it too.

Test distribution over an expression Sum, which had no direct test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Simplify Action(x, Adjoint(A)) and absorb x into a primal slot

Action(Adjoint(A), x) became Action(x, A), but its mirror Action(x, Adjoint(A)),
which is A x, assembled the adjoint as a rank-two matrix. Likewise an operator
whose lowest-numbered argument is in a primal slot, as Adjoint(N) gives, could
not absorb x. Both now contract x without a rank-two assembly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Share the dual slot rule and tidy the BaseForm derivative rules

Find the contracted argument of a split dual slot with
_split_dual_slot_arguments instead of deriving it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Name the restructuring rules after their maths

State the formula beside each Action rule and use one set of symbols in the
docstring tables, which had an undefined R and used a and b for both weights
and operands. Use the names of the docstrings in the code: vstar, uhat_B,
vstar_B, Nhat and contracted. Shorten the test names to labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Restore the union of the FormSum arguments

Reporting only the arguments of the highest rank component dropped arguments:
Matrix(v_0, v_1) + L(v_2) reported rank two, and components in different spaces
reported whichever came first. Take the union again, as Form does, so that
these mismatches stay visible.

An Action keeps the numbers of its operands, so Action(x, Matrix) reports v_1.
Number the arguments of an Action component from zero in the union, so that
Form(v_0) + Action(x, Matrix) keeps rank one. Action itself must keep the
numbers of its operands: the derivative numbers its direction after them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Take the Adjoint of a row for the column of an Action

Action(x, A) is the row x^H A, so its free argument keeps the number it has in
A. The column is its Adjoint, A^H x = (x^H A)^H, so Action(Adjoint(A), x)
restructures to Adjoint(Action(x, A)), which reports v_0. Adjoint accepts a
row, and a sum of rows becomes a sum of columns before the Adjoint is taken.
FormSum.arguments() is the plain union again.

Differentiating these Actions failed because a contracted argument is a bound
variable, while the direction and the renumbered arguments were chosen from the
free arguments only. So:
- The default direction comes after the lowest argument that an Action contracts
  on its right.
- The Action rule shifts the contracted argument of the left operand and the
  arguments above it, including those contracted in nested Actions.
- Action(L, v) with an Argument v puts v in the contracted slot of L, rather than
  returning L with its old number.
- Absorbing into the last argument of a Form shifts the free arguments down to
  zero, as absorbing into the first one does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiE9EdXTj3cqXdNadcRsGs

* Share the column of a sum of rows and keep Action(x, A) sum weights

Absorbing x turns a row into a column, so a sum of rows with an absorbed
component and the Adjoint of a sum of rows both give conj(c) A^H x +
conj(d) B^H x. BaseFormRestructurer.column_sum now does this for both,
replacing the module-level _column helper, and also splits nested sums.

x^H (c A + d B) = c x^H A + d x^H B is linear in the weights, so stop
conjugating them when distributing Action(x, c A + d B).

Drop the rule for Action(Adjoint(c A + d B), x), since A^H x = (x^H A)^H
and column_sum already give that result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Differentiate an operator composed with a form with respect to the operator

N(u; F) is F composed with N(u; v*), and F is linear, so its derivative
with respect to N in the direction v is F[v]. The derivative rules only
matched N with a Coargument in its dual slot, so this derivative was zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Hash scalar values by value, as they compare

ScalarValue compares by value, but hashed its repr, as other terminals
do. -2j is complex(-0.0, -2.0), which equals (2j).conjugate() but has a
different repr, so Fx + -2j * Gx compared unequal to an equal form, as
Form.equals compares hashes first. ScalarValue now hashes its type code
and value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Renumber derivative directions when restructuring their operand

derivative() numbers the default direction from the unrestructured
operand, so the Hessian of Action(L(u), Interpolate(u, V)) reported
[1, 2], and [0, 1, 2] once restructured, while Interpolate(u, L(u))
reports [0, 1].

restructure_base_form now restructures before and after expanding
derivatives, with one BaseFormRestructurer so the second pass reuses its
cache. Its BaseFormDerivative handler restructures the operand and moves
a direction numbered at or above the default to stay right after the
free arguments of the restructured operand. derivative() and the handler
share default_direction_number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Inline operators into the Forms that absorb them

A Form absorbs an operator as it absorbs an expression: Action(F, N) is
F(v_0, N) and Action(N, F) is conj(F(N, v_1)), and a Form in the dual slot of
an operator absorbs the operator. The Coargument bound by an inlined operator
takes the lowest number its arguments leave, as for Interpolate(expr, V).

Differentiating a Form with an operator whose primal slots hold Arguments
substitutes the derivative of the operator for Nhat, since an Action would
contract one of those Arguments instead of vhat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number the default direction after every Action's contracted argument

A derivative reaches the right operand of every Action in the form, not
only of the Actions nested as left operands, so default_direction_number
traverses the whole form for Actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test the derivative of an Action of a FormSum of Actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Number the default direction after every Action's contracted argument

A derivative reaches the right operand of every Action in the form, not
only of the Actions nested as left operands, so default_direction_number
traverses the whole form for Actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test the derivative of an Action of a FormSum of Actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Conjugate an absorbed Form only for a function on the left

_absorb conjugated every Form that absorbed its left operand, as for
Action(w, F) with a function w, where F(w, v_0) leaves the linear slot of F
free. A Form, a dual operator or a rank-two operator on the left keeps the
test argument of F antilinear, so its result is F(left) as it stands.
Interpolate(w, Interpolate(u, a)) gave conj(a(I w, I u)), which conjugates
the coefficients of a, and the derivatives through an operator gave the
conjugate of their plain UFL counterparts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Accept a primal operator whose Coargument is not its lowest argument

Interpolate required the first argument of a BaseForm expression to be
its Coargument. Interpolate(w_0, V1) numbers its Coargument 1, after w_0,
so Interpolate(Interpolate(w_0, V1), V2) was rejected, and restructuring
Interpolate(w, Interpolate(v, F)) into F(I I w) failed. An expression is
primal when it has one Coargument, whatever its number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Say that Interpolate expects a primal expression

The message named the first argument, which reads as the first Argument
of the expression now that the Coargument can have any number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test a FormSum whose first component vanishes under differentiation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Compose Forms only with operators up to max_composed_rank

restructure_base_form takes max_composed_rank, default 1. A Form composes
with an operator, or fills its dual slot, only if the operator has at most
that rank; otherwise the Action is kept. Rename absorb to compose, the term
UFL already uses for N(u; A), and inline _absorb into
BaseFormRestructurer.compose.

Run the affected tests with max_composed_rank 1 and 2, asserting the exact
restructured result for each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep a rank-one Form in the dual slot of a non-composable operator

A Form fills the dual slot of an operator whatever its rank. When splitting
N(u; F) for a rank-one Form F, keep N(u; F) if N(u; vhat) is not composable,
instead of keeping the Action. A Form of higher rank still keeps its Action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Commute coefficient derivatives with foreign derivatives

D_w[v](Dt(f)) = Dt(D_w[v](f)) for a derivative in another variable,
such as Irksome's TimeDerivative, so derivative(F, u) can be expanded
when F contains Dt(u).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expand variable derivatives when expanding coefficient derivatives

replace(derivative(F, u), ...) failed when F contained diff, because
the preserved VariableDerivative reached the Gateaux rules. Expand it
instead; a spatial gradient is independent of the variable, so its
variable derivative is zero even when the gradient is kept on a
compound expression. The Gateaux rule for other derivatives now rejects
any derivative with more than one operand rather than dropping terms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Move replace tests to test_replace.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Commute coefficient derivatives with single-operand derivatives only

The rule for derivatives in another variable now states the linear,
single-operand case it implements instead of special-casing arity.
Test restructure_base_form on a variable derivative.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Expand the operand of a variable derivative fully

When other derivatives are preserved, the operand of diff kept grad, div,
curl, etc. on compound expressions, which the variable rules cannot
differentiate: div failed, and grad of a compound was silently taken as
independent of the variable. Lower and expand the operand fully before
applying the variable rules, as expand_derivatives does, and restore the
check that a grad is applied to a terminal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Commute variable derivatives with spatial derivatives

Expanding the operand of diff fully lost the derivatives preserved
elsewhere. Lower the operand only, so that compound derivatives such as
div are expressed with grads, and let the variable derivative commute
with grad: d/dv grad(f) = grad(df/dv), with the gradient index placed
before those of v. Another derivative of a single operand commutes with
the derivative with respect to a scalar variable. A compound derivative
that reaches the variable rules unlowered raises an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
pbrubeck added a commit that referenced this pull request Nov 25, 2026
* Fix dual-slot form argument counting

* Compare the stored function space in Interpolate.__eq__

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Fix dual-slot form argument handling

* Remove outer_form argument plumbing

* Materialize dual-slot arguments

* Annotate delayed imports

* Contract the highest-numbered argument of a form dual slot

A form dual slot now contracts its highest-numbered primal argument, as
the left operand of an Action does, so Interpolate(u, F) numbers its
free arguments like Action(F, Interpolate(u, V)), starting at 0.
Coarguments in the slot stay free.

The stored slot is renumbered once, at construction, and argument
analysis reads it back. BaseFormOperatorDerivative rejects duplicate
argument numbers, and apply_derivatives numbers the direction after the
highest operator argument instead of after the argument count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Simplify the contracted argument renumbering

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that dual-slot contraction ignores numbering gaps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep arguments contracted inside a dual slot when renumbering

Renumbering the slot's own arguments with replace could rename one onto an
argument that an Action inside the slot contracts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Contract a form dual slot as an Action does

Renumbering the free arguments in the constructor rewrote the user's form
with replace, which needed _contained_arguments to avoid arguments that inner
Actions contract. That traversal was exponential in the depth of shared
subexpressions.

The free arguments now keep their numbers, and N(u; F) contracts the argument
that an Action would. If the primal slots use number 0, the output of N is
numbered last, so N is the left operand and F's lowest argument is contracted.
Otherwise F is the left operand and its highest argument is contracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 6a89eab)
pbrubeck added a commit that referenced this pull request Nov 25, 2026
pbrubeck added a commit that referenced this pull request Nov 25, 2026
It tests the target space chosen for a FormSum dual slot, which #527 fixed
and release does not have. It fails on release with or without #550.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jorgensd pushed a commit that referenced this pull request Nov 25, 2026
…574)

* Negate a contracted Interpolate with free arguments as a form (#550)

* Negate a contracted Interpolate with free arguments as a form

Interpolate(v, cofunction) is a 1-form, but _value_parent_type follows the
target space, which is primal, so negating or scaling it gave an expression.
Subtracting it from a Form then raised a TypeError.

Return BaseForm when the dual slot contracts the value and free arguments
remain. Interpolate(v, V) and the 0-form Interpolate(u, cofunction) stay
expressions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Treat a scaled Coargument dual slot as a free output

2 * Coargument and sums of Coarguments are FormSums, so checking the type of
the dual slot treated their output as contracted, and negation gave a
FormSum. Check for a Coargument among the arguments of the dual slot instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 1b8d1e2)

* Keep release interpolation target selection in the backport

* Fix dual-slot form argument counting (#527)

* Fix dual-slot form argument counting

* Compare the stored function space in Interpolate.__eq__

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Fix dual-slot form argument handling

* Remove outer_form argument plumbing

* Materialize dual-slot arguments

* Annotate delayed imports

* Contract the highest-numbered argument of a form dual slot

A form dual slot now contracts its highest-numbered primal argument, as
the left operand of an Action does, so Interpolate(u, F) numbers its
free arguments like Action(F, Interpolate(u, V)), starting at 0.
Coarguments in the slot stay free.

The stored slot is renumbered once, at construction, and argument
analysis reads it back. BaseFormOperatorDerivative rejects duplicate
argument numbers, and apply_derivatives numbers the direction after the
highest operator argument instead of after the argument count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Simplify the contracted argument renumbering

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that dual-slot contraction ignores numbering gaps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep arguments contracted inside a dual slot when renumbering

Renumbering the slot's own arguments with replace could rename one onto an
argument that an Action inside the slot contracts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Contract a form dual slot as an Action does

Renumbering the free arguments in the constructor rewrote the user's form
with replace, which needed _contained_arguments to avoid arguments that inner
Actions contract. That traversal was exponential in the depth of shared
subexpressions.

The free arguments now keep their numbers, and N(u; F) contracts the argument
that an Action would. If the primal slots use number 0, the output of N is
numbered last, so N is the left operand and F's lowest argument is contracted.
Otherwise F is the left operand and its highest argument is contracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 6a89eab)

* Revert "Fix dual-slot form argument counting (#527)"

This reverts commit ca2a2a7.

* Drop the scaled-Coargument regression from the backport

It tests the target space chosen for a FormSum dual slot, which #527 fixed
and release does not have. It fails on release with or without #550.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Alias datetime as dt in the docs configuration

Ruff 0.17 flags a plain datetime import. main made the same change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

4 participants