Derivative of Function

I don’t think I understand what derivative does in fenics and am hoping to clear this up with the following simple problem.

I have a form J in terms of a regular (as in not a trial or test function) function alpha that I am trying to take the derivative of, but for some reason this derivative is incorrect.

from fenics import *

mesh = UnitSquareMesh(16,16)
K = FunctionSpace(mesh,"DG",0)
alpha = Function(K)
alpha.interpolate(Constant(1))
J = inner(alpha,alpha)*dx
dJ = Function(K,assemble(derivative(J, alpha)))
dJtrue = 2*alpha

print(assemble(inner(dJ,dJ)*dx))
print(assemble(inner(dJtrue,dJtrue)*dx))

When running the above test code I would expect to get twice 4, as the derivative of J is 2*alpha, however I get 1.5e-5 instead for the first output.

edit: the exact output is:

1.52587890625e-05
4.0

When you use derivative(J, alpha) what dolfin does, is that it computes:

da = TestFunction(K)
dJdalpha = inner(alpha, da) * dx + inner(da, alpha) * dx

What you in turn do is that you assemble this form into a function, and compute the squared L2 norm of it:

dJ2 = Function(K, assemble(dJdalpha))
print(assemble(inner(dJ2, dJ2)*dx))

So how would I get dJ to be a function in K equivalent to dJtrue then ?

from dolfin import *
import ufl 

mesh = UnitSquareMesh(10, 10)
V = FunctionSpace(mesh, "DG", 0)
alpha = Function(V)
alpha.interpolate(Constant(1))
a = inner(alpha, alpha)
da = ufl.diff(a, alpha)
print(assemble(inner(da, da)*dx))

I’m confused now ; your first post describes the behaviour of dolfin.derivative and the second that of ufl.diff. It would make sense for them to be the same, but the nuance is crucial when making the passage to dolfinx I think.

Besides, I can’t help but see from your post that you omitted the dx in the form prior to differentiation. In my case I don’t do that, and still seem to obtain reasonable results. It feels wrong to me to have a form with no dx. Would you care to comment on that ?

I would suggest reading:
https://fenics.readthedocs.io/projects/ufl/en/latest/manual/form_language.html#variable-derivatives
And
https://fenics.readthedocs.io/projects/ufl/en/latest/manual/form_language.html#automatic-functional-differentiation

2 Likes

Thank you for these pointers. All provided examples differentiate a form with dx, but I guess it matters little for symbolic differentiation.

I guess my dismay comes from the fact I understood your first post wrong. For a moment there, I thought dolfin.derivative introduces an additional dx and thus requires a form with no dx.

I was wrong, thank you for your time.