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

Is it possible to compute the derivative of a scalar or vector field in advance?

0 votes

Hello,

I want to compute the gradient of a scalar or vector field that i computed from FEM data. More precisely, I would like to compute the Matrix that gives me the gradient of an arbitrary scalar or vector field such that i can compute the derivative by Matrix-Vector multiplication. Is this possible in FEniCS?

I tried:

Q = FunctionSpace(mesh, "Lagrange", 1)
phi_i = TestFunction(Q)
phi_j = TrialFunction(Q)

Grad = assemble(inner(phi_j, grad(phi_i)[0]) * dx)
rows, cols, values = as_backend_type(Grad).data()
Grad = sps.csr_matrix((values, cols, rows))

return Grad

But this seems to give me the wrong results.

Best regards,
Sebastian

asked Dec 1, 2015 by SebastianPeitz FEniCS Novice (150 points)

2 Answers

+1 vote
 
Best answer

As Tormod says there is a fast version in fenicstools.

However, I would also like to point out that your above code is actually
correct. But you should be aware that you will obtain the gradient in
the "right-hand side representation". What you probably wanted was the
representation used on the left-hand side. To get to that you would have
to multiply your gradient with the inverse of a mass matrix. That is,
you need to solve as follows.

(u, v are vectors spaces )

m = uvdx
L = inner(grad(f), v)*dx

solve (a == L)

This will often be the case for finite element methods or in general
methods that employ weak formulations. That is, the scaling of vectors
on the left- and right-hand side vectors are different.

answered Dec 1, 2015 by Kent-Andre Mardal FEniCS Expert (14,380 points)
selected Dec 14, 2015 by SebastianPeitz

Hello,

thanks to both of you for your answers, they helped a lot. Since I want to use the matrices within matlab, I solved the Problem by solving the linear system Grad_right = M * Grad_left.

Best regards,
Sebastian

0 votes

Hi,

There is a fast implementation of this in fenicstools

You can also try to use grad(phi_i)[0] as the test function (also on the right hand side). This will produce a symmetric bilinear form. You would anyway have to assemble the right hand side every time.

answered Dec 1, 2015 by Tormod Landet FEniCS User (5,130 points)
...