Checking 2 forms are equal

Hi all,

I want to check if two forms are equal.

Can someone explain why this doesn’t work ?

from fenics import *

mesh = UnitIntervalMesh(10)
V = FunctionSpace(mesh, 'P', 1)
u = Function(V)
v = TestFunction(V)

F1 = dot(2*grad(u), grad(v))*dx
F2 = dot(2*grad(u), grad(v))*dx

print(F1)
print(F2)
# Something changes...

assert F1.equals(F2)

Thanks in advance !

The reason is that the object created by the scalar–vector product 2*grad(u) has a free index. Every time an object with a free index is created, the global index counter is incremented, to avoid naming conflicts. The reason the index names start at i_8 and not i_0 is that eight indices are already created by default (i,j,k,l,p,q,r,s). You can technically reset the index counter, e.g.,

F1 = dot(2*grad(u), grad(v))*dx

from ufl.core.multiindex import Index
Index._globalcount = 8

F2 = dot(2*grad(u), grad(v))*dx

to pass the assertion, but this is probably not a good idea. In this particular example, you could alternatively define F1 and F2 by

2*dot(grad(u),grad(v))*dx

which avoids creating the intermediate object 2*grad(u), which has the free index.

1 Like

Ok I see.
Since I just intend to perform unit tests I think it won’t do any harm if i reset the counter.

In really this coefficient is not 2 but more like a function of u so I guess I can’t just put it out of the dot(grad(u), grad(v)) product, right ?

Thanks for your help!

Scalar multiplication by a spatially-varying field can be safely pulled out of the dot product, just not spatial derivatives.

1 Like

Hi @kamensky coming back to this years later in dolfinx, any chance you know the equivalent of

from ufl.core.multiindex import Index
Index._globalcount = 8

in dolfinx?

ping @James_Dark

Resolved in: Compare two forms - #3 by dokken