Expression in equation

Good day! I have the next question: Is it any difference between putting in the equation expression and expression, interpolated on function space (i.e. function)? Example bellow. Thank you!

from dolfin import *

mesh = UnitSquareMesh(30, 30)
V = FunctionSpace(mesh, "CG", 1)

def boundary(x, on_boundary):
    return on_boundary

u_D = Expression('1 + x[0] * x[0] + 2 * x[1] * x[1]', degree=2)
bc = DirichletBC(V, u_D, boundary)

u = TrialFunction(V)
v = TestFunction(V)

f = Expression('-6.0', degree=1)
# f = interpolate(Expression('-6.0', degree=1), V) Is it matter?

a = dot(grad(u), grad(v)) * dx
L = f * v * dx

u = Function(V)
solve(a == L, u, bc)

There is no need to interpolate the expression in your case.
The function interpolate performs the interpolation of a given function upon a given finite element space.

PS. For the constant expression, the degree is 0 .

Ok, I provided not the best example. But in general case, is it any difference between putting in the equation expression and expression, interpolated on function space (i.e. function)?

These two approaches should produce the same result.
There is a little difference in performance.

Expression() approach will interpolate the c++ string locally for each cell during assembly, so it doesn’t need to store the whole function in memory. There are layers of function calls around, so this approach could be slightly less performant as the latter.

On the other hand, interpolation beforehand stores the intermediate result as a function, so needs more memory for storage, but computation time will be spent outside assembly. I would prefer this approach, memory requirements for additional function is almost never the problem.

Even better approach is to put the expression written in symbolic UFL language terms into finite element form directly. This means -6.0 * v * dx for your simple case. But UFL provides plenty of function, so c++ string expression could be almost always avoided.

2 Likes

Thank you very much for the detailed response!