I wanted to do the same thing. Here's how it is working for me:
The jpcGrad.ufl file:
element = FiniteElement("Lagrange", triangle, 2)
velement = VectorElement("Lagrange", triangle, 2)
solution = Coefficient(element)
v = TestFunction(velement) # Test Function
u = TrialFunction(velement) # Trial Function
a = inner(u, v)*dx
L = inner(grad(solution),v)*dx
Now, in the .cpp file:
#include "jpcGrad.h"
...
class GradClass : public Expression
{
public:
GradClass(Function &cref)
{
c = &cref;
}
void eval(Array<double>& values, const Array<double>& x) const
{
calledGradEval();
Array<double> myval(1);
c->eval(myval, x);
values[0] = myval[0];
}
private:
Function *c;
};
...
jpcGrad::FunctionSpace G(mesh, PBC);
jpcGrad::LinearForm L(G);
jpcGrad::BilinearForm a(G,G);
auto gradf = GradClass(c);
L.solution = gradf;
Function u(G);
...//now in the time loop:
//this is the solver that gives the solution c
Solver.solve();
//now solve for grad c:
solve(a == L, u);
Thus, I had to subclass Expression so that the solution (a reference to which is saved in the private data of the subclass) can be evaluated in the gradient variational form assembly.