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

How do you compute the gradient of a refined function?

+7 votes

For some reason, the following code

from dolfin import *
r = Rectangle(-1, -1, 1, 1) 
mesh = Mesh(r, 10)
positions = mesh.coordinates()
V = FunctionSpace(mesh, "CG", 1)
f = Expression('sin(3.14159*x[0]) + cos(3.14159*x[1])')
u = interpolate(f,V)

cell_markers = CellFunction("bool", mesh)
cell_markers.set_all(True)

mesh_refined = refine(mesh, cell_markers)
u_refined = adapt(u, mesh_refined)
u_refined.set_parent(u)

plot(grad(u_refined))    
interactive()

Fails with the following error code:

ufl.log.UFLException: Invalid type conversion: class
'dolfin.cpp.function.Function' can not be converted to any UFL type.
The representation of the object is: dolfin.cpp.function.Function;
proxy of Swig Object of type 'boost::shared_ptr dolfin::Function
*' at 0x108a0e5d0

What am I missing here?

asked Dec 6, 2013 by asherp FEniCS Novice (340 points)

Just out of curiosity: why would one call Function.set_parent/child?

1 Answer

+5 votes
 
Best answer

Hi,

This is probably a bit confusing, but a Python Function is not exactly the same as a C++ Function since a Python Function is a class that inherits from both ufl.Coefficient and cpp.Function, see lib/python2.7/site-packages/dolfin/functions/function.py. The C++ function adapt returns a cpp.Function. There should probably be a Python wrapper of the adapt function that returns a Python Function, instead. Meanwhile you can wrap adapt yourselves with for example

u_refined = Function(adapt(u, mesh_refined))

The rest of your code will then work as expected.

answered Dec 7, 2013 by mikael-mortensen FEniCS Expert (29,340 points)
selected Dec 7, 2013 by asherp

Thanks alot, that did the trick!

...