This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

Check if two forms are equal for testing.

+2 votes

I am currently trying to generalize some code to make it more reusable. I want to make sure that the form generated by my "general" version is the same as those generated by the scripts I have for specific problems. If I have two forms, F1 and F2, the syntax F1 == F2 returns an equation object. Is there a way to check the equality of these two objects instead of creating an equation object?

asked Aug 29, 2016 by miguelr FEniCS Novice (420 points)

1 Answer

+2 votes

Hi, consider

from dolfin import *

mesh = UnitSquareMesh(10, 10)
V = FunctionSpace(mesh, 'CG', 1)
v = TestFunction(V)
f0 = Function(V)
f1 = Function(V)

L0 = inner(f0, v)*dx
L1 = inner(f1, v)*dx

print L0.equals(L1)
L0 = replace(L0, {f0: f1})
print L0.equals(L1) 
answered Aug 31, 2016 by MiroK FEniCS Expert (80,920 points)

Thank you for the response. I tried this:

import dolfin as dlf

#
mesh0 = dlf.UnitSquareMesh(10, 10)
V0 = dlf.FunctionSpace(mesh0, 'CG', 1)

u0 = dlf.Function(V0)
v0 = dlf.TestFunction(V0)
f0 = dlf.Constant(1.0)

F0 = dlf.inner(u0, v0)*dlf.dx - f0*v0*dlf.dx

#
mesh1 = dlf.UnitSquareMesh(10, 10)
V1 = dlf.FunctionSpace(mesh1, 'CG', 1)

u1 = dlf.Function(V1)
v1 = dlf.TestFunction(V1)
f1 = dlf.Constant(1.0)

F1 = dlf.inner(u1, v1)*dlf.dx - f1*v1*dlf.dx

##
print 'Before replace (F1 == F0): ', F0.equals(F1)
F0 = dlf.replace(F0, {u0: u1, v0: v1, f0: f1})
print 'After replace (F1 == F0): ', F0.equals(F1)

and the output was

Before replace (F1 == F0):  False
After replace (F1 == F0):  False

This leads me to believe that they will only be evaluated as equal if all functions (including test and trial functions) come from the same instance of FunctionSpace. Is this correct?

The reason I ask is because I would like to compare the forms generated in different scripts. One script formulating a specific problem, and another formulating the same problem via generalized code.

You could always assemble a matrix with each approach for non trivial meshes, coefficients, etc., and check if a norm of the difference is zero. This does of course not test for equality in a strong sense, but it may work as a heuristic approach as long as you find no better way ;-).

Hi, they will only be evaluated as equal if all functions (including test and trial functions) come from the same instance of FunctionSpace is correct. An alternative to Christian's approach is perhaps to tinker with the hash of the objects that make up the form.

...