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

Expression subclass overloading __init__ requires a UFL element

+1 vote

Hello,

I have noticed with dolfin 1.4.0 that my Expression subclass with overloaded init method requires that a ufl_element be passed as value 'element', else the error

*** Warning: Evaluating an Expression without knowing the right geometric dimension, assuming 2 is correct.

occurs when calling the Expression. I have fixed this by noting in the init method the element should be defined as

self._ufl_element = element

Is there is a more elegant way to do this without going through the source code?

Here is a minimal example:

class MyExpression0(Expression):
  def __init__(self, t, element):
    self.t = t
    self._ufl_element = element
  def eval(self, value, x):
    dx = x[0] - 0.5
    dy = x[1] - 0.5
    value[0] = 500.0*exp(-(dx*dx + dy*dy)/0.02)
    value[1] = 250.0*exp(-(dx*dx + dy*dy)/0.01)
  def value_shape(self):
    return (2,)

mesh = UnitSquareMesh(4,4)
V = FunctionSpace(mesh, "BDM", 1)
f1 = MyExpression0(5, element = V.ufl_element())
f1(0,0)  # no error with the element defined

can anyone help?

asked Jun 10, 2014 by pf4d FEniCS User (2,970 points)

1 Answer

+4 votes
 
Best answer

I had no problems running your code with or without explicit setting self._ufl_element. The element is however expected to be passed as a kwarg. You do that in the running code so that might explain why it worked. If I remove self._ufl_element from the __init__ method, and instantiate the Expression using

MyExpression0(5, V.ufl_element())

I get the error. I suggest you to use the below code which should work.

class MyExpression0(Expression):
  def __init__(self, t, element=None):
    self.t = t
  def eval(self, value, x):
    dx = x[0] - 0.5
    dy = x[1] - 0.5
    value[0] = 500.0*exp(-(dx*dx + dy*dy)/0.02)
    value[1] = 250.0*exp(-(dx*dx + dy*dy)/0.01)
  def value_shape(self):
    return (2,)

mesh = UnitSquareMesh(4,4)
V = FunctionSpace(mesh, "BDM", 1)
f1 = MyExpression0(5, element = V.ufl_element())
f1(0,0)  # no error with the element defined

or use a compiled Expression:

f2 = Expression(["500.0*exp(-((x[0] - 0.5)*(x[0] - 0.5) + (x[1] - 0.5)*(x[1] - 0.5))/0.02)",
                 "250.0*exp(-((x[0] - 0.5)*(x[0] - 0.5) + (x[1] - 0.5)*(x[1] - 0.5))/0.01)"],  
                 element=V.ufl_element())
answered Jun 11, 2014 by johanhake FEniCS Expert (22,480 points)
selected Jun 12, 2014 by pf4d

Looks good, thanks!

...