# Error evaluating a 2D exact solution using User-defined expressions by subclassing

Dear Colleagues

I have a problem when evaluating the L2 error norm or when interpolating it by using an Expression by sub-classing, I share whit you the essential of the code that shows the error, thanks by advance for your help!

from fenics import *
from mshr import *
import matplotlib.pyplot as plt
from math import *
import numpy as np

L = Constant(48)
D = Constant(12)
P = Constant(1E3)
I = Constant(pow(D,3)/12.0)
E = Constant(3E7)
nu = Constant(0.3)

domain = Rectangle(Point(0, -D/2.0), Point(L, D/2.0))
mesh = generate_mesh(domain, 50)
V = VectorFunctionSpace(mesh,‘P’, 1)

class Exact_disp(Expression):
def init(self, P, E, nu , I, D, L, **kwargs):
self._P, self._E, self._nu, self._I, self._D, self._L = P, E, nu, I, D, L

``````def eval(self, value, x):
self._P, self._E, self._nu, self._I, self._D, self._L = P, E, nu, I, D, L, x

value[0] = ((-P*x[1])/(6.0*E*I))*((x[0]*((6*L) - (3*x[0]))) + ((2 + nu)*((pow(x[1],2)) - (0.25*pow(D,2)))))

value[1] = ((P*x[1])/(6.0*E*I))*(((3*nu*pow(x[1],2))*(L - x[0])) - ((0.25*pow(D,2)*x[0])*(4 + (5*nu))) + (pow(x[0],2)*((3*L) - x[0])))

def value_shape(self):
return(2,)
``````

u_exact = Exact_disp(P=P, E=E, nu=nu , I=I, D=D, L=L, element=V.ufl_element())

u_ex = interpolate(u_exact, V)

The error:
Traceback (most recent call last):
File “exact_sol.py”, line 37, in
u_ex = interpolate(u_exact, V)
File “/usr/lib/python3/dist-packages/dolfin/fem/interpolation.py”, line 70, in interpolate
if hasattr(v, “_cpp_object”):
File “/usr/lib/python3/dist-packages/dolfin/function/expression.py”, line 432, in getattr
return self._parameters[name]
File “/usr/lib/python3/dist-packages/dolfin/function/expression.py”, line 432, in getattr
return self._parameters[name]
File “/usr/lib/python3/dist-packages/dolfin/function/expression.py”, line 432, in getattr
return self._parameters[name]
[Previous line repeated 329 more times]
RecursionError: maximum recursion depth exceeded

Fenics last release ubuntu 18.04 installed from source

Thanks!

There is a corrected code for `Exact_disp` , in Fenics 2018 and higher versions Expression changes to UserExpression.
You don’t need to set the parameters E,P, … in the `eval` since it is done in the `__init__`.

``````class Exact_disp(UserExpression):
def __init__(self, P, E, nu , I, D, L, **kwargs):
super().__init__(**kwargs)
self._P = P
self._E = E
self._nu = nu
self._I = I
self._D = D
self._L = L

def eval(self, value, x):
value[0] = ((-self._P*x[1])/(6.0*self._E*self._I))*((x[0]*((6*self._L) - (3*x[0]))) + ((2 + self._nu)*((pow(x[1],2)) - (0.25*pow(self._D,2)))))
value[1] = ((self._P*x[1])/(6.0*self._E*self._I))*(((3*self._nu*pow(x[1],2))*(self._L - x[0])) - ((0.25*pow(self._D,2)*x[0])*(4 + (5*self._nu))) + (pow(x[0],2)*((3*self._L) - x[0])))

def value_shape(self):
return(2,)
``````
1 Like

Thank you so much that’s running perfectly!!!