How to define source term function

Custom Python definitions of expressions should be subclasses of UserExpression, not Expression in the current version of FEniCS (2019.1). See, e.g., the following example:

from dolfin import *

# Minimal example reproducing error from post:

#class e(Expression):
#    def __init__(self, eps):
#        self.eps = eps
#eInstance = e(1.0)

# In version 2019.1, you want to subclass UserExpression:
class e(UserExpression):
    def __init__(self,eps,**kwargs):
        # Call superclass constructor with keyword arguments to properly
        # set up the instance:
        super().__init__(**kwargs)
        # Perform custom setup tasks for the subclass after that:
        self.eps = eps
        
    def eval(self, values, x):
        eps = self.eps
        values[0] = eps/pi/(x[0]**2 + x[1]**2 + eps**2)

    def value_shape(self):
        return ()

# Test:

# NOTE: UserExpressions are always interpolated in finite element spaces during
# assembly of forms.  You can control which space by passing a degree
# keyword argument.  The default value, if nothing is passed, is degree=2.
# For the given regularized delta function, it will always be an approximation,
# since the formula is non-polynomial.  (An alternative would be to define
# it directly in UFL, using `x = SpatialCoordinate(mesh)`.)
eInstance = e(1.0,degree=4)

mesh = UnitSquareMesh(1,1)
print(assemble(eInstance*dx(domain=mesh)))
1 Like