Compute grad of UserExpression

Hi all,

I’m trying to get the gradient of a UserExpression using the eval_cell method.

from fenics import *


class CustomExpression(UserExpression):
    def __init__(self, **kwargs):
        super().__init__(kwargs)

    def eval_cell(self, value, x, ufc_cell):
        value[0] = 1

    def value_shape(self):
        return ()


mesh = UnitSquareMesh(16, 16)
V = FunctionSpace(mesh, 'CG', 1)
u = Function(V)
n = FacetNormal(mesh)
my_expression = CustomExpression()
print(assemble(dot(grad(my_expression), n)*ds))

However I’m getting the following error:

fenics@4e87fe631d9d:~/shared$ python3 test.py
Cannot determine geometric dimension from expression.
Traceback (most recent call last):
  File "test.py", line 21, in <module>
    print(assemble(dot(grad(my_expression), n)*ds))
  File "/usr/local/lib/python3.6/dist-packages/ufl/operators.py", line 381, in grad
    return Grad(f)
  File "/usr/local/lib/python3.6/dist-packages/ufl/differentiation.py", line 159, in __init__
    self._dim = find_geometric_dimension(f)
  File "/usr/local/lib/python3.6/dist-packages/ufl/domain.py", line 384, in find_geometric_dimension
    error("Cannot determine geometric dimension from expression.")
  File "/usr/local/lib/python3.6/dist-packages/ufl/log.py", line 172, in error
    raise self._exception_type(self._format_raw(*message))
ufl.log.UFLException: Cannot determine geometric dimension from expression.

Thanks for the help!

Rémi

In order to use grad() you have to first project your expression on a suitable function space.

try out this:

from fenics import *

class CustomExpression(UserExpression):
    def __init__(self, **kwargs):
        super().__init__(kwargs)

    def eval_cell(self, value, x, ufc_cell):
        value[0] = 1

    def value_shape(self):
        return ()

mesh = UnitSquareMesh(16, 16)
V = FunctionSpace(mesh, 'CG', 1)
n = FacetNormal(mesh)
my_expression = CustomExpression()
u = project(my_expression, V)

print(assemble(dot(grad(u), n)*ds))