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

Difference between direct assemble and assemble + matrix multiplication

+6 votes

Consider this code:

V = FunctionSpace(mesh, 'CG', 1)
Vv = VectorFunctionSpace(mesh, 'CG', 1)
v = TestFunction(V)
g = Function(V)
f = Function(Vv)
initialize_g(g) 
initialize_f(f) 
F1 = assemble(f[0] * g * dx)
F_op = assemble(f[0] * v * dx)
F2 = (F_op * g.vector()).sum()

As expected, F1 == F2. However, with a more complicated expression

F1 = assemble(cross(f, grad(g))[0] * dx)
F_op = assemble(cross(f, grad(v))[0] * dx)
F2 = (F_op * g.vector()).sum()

..I'm actually getting different results for F1 and F2 (e.g. -9.266e-04 vs -8.763e-04).

Why is that?

asked Feb 4, 2014 by Nikolaus Rath FEniCS User (2,100 points)

Please, supply a complete, executable code so that we can try.

1 Answer

+6 votes
 
Best answer

There shouldn't be any difference between these two. The result should be exactly the same whenever g is a finite element function. Try the following code:

from dolfin import *

mesh = UnitCubeMesh(8, 8, 8)

V = FunctionSpace(mesh, 'CG', 1)
Vv = VectorFunctionSpace(mesh, 'CG', 1)

v = TestFunction(V)

f = project(Expression(("x[1]", "sin(x[0])*cos(x[1]*x[2])", "x[0]")), Vv)
g = project(Expression("sin(x[0])*sin(x[1])*sin(x[2])"), V)

F1 =  assemble(f[1]*g*dx)
F2 = (assemble(f[1]*v*dx) * g.vector()).sum()

print F1, F2

F1 =  assemble(cross(f, grad(g))[0]*dx)
F2 = (assemble(cross(f, grad(v))[0]*dx) * g.vector()).sum()

print F1, F2

I think the difference in your case is either round-off error, as a result of choosing functions for which the combination of cross and grad returns something which is near zero.

If you find an interesting case which does not return the exact results, try to isolate the problem for as simple expressions as possible, in particular making all components of the vector function zero except one, and then rewrite the forms without using cross and grad (use instead g.dx(0) or similar), and then post your example code.

answered Feb 5, 2014 by logg FEniCS Expert (11,790 points)
selected Feb 5, 2014 by Jan Blechta

Seems you are right, in my case the expression evaluates to almost zero. For other cases the results are as expected. Thanks!

...