[Beginner] Problem with defining source term

Hi there,
I’m a complete beginner in Fenics. I tried to solve a basic equation :
\Delta v(x,y) + \ell^2 v(x,y) = f(x) on a unit square, with v(0,y)=0 and v(x,0)=0

The f function has been implemented in Python and is quite complex.
This really seems like a dumm question, but how to implement f in Fenics ?

Here is the code I wrote :

mesh = UnitSquareMesh(16,16)
V = FunctionSpace(mesh, 'P', 1)

u_D = Expression('0', degree=0)

def boundary(x, on_boundary):
    return on_boundary and x[0]<0.2 and x[1]<0.2

bc = DirichletBC(V, u_D, boundary)

v = TrialFunction(V)
s = TestFunction(V)
def aux(x):
    return -l2*condY0(x[0])
f = interpolate(aux,V)
a = (-dot(grad(v), grad(s))+l2*v*s)*dx
L = f*s*dx

u = Function(V)
solve(a == L, u, bc)

However this doesn’t seem to work…

Thanks for your help !

As you have not defined

in the script, there is no way telling if V is a suitable function space for your source term.

Oh I see. Here it is :

    N= randint(2,10)
    amplitude = []
    periodes = []

    for k in range(N):
        amplitude.append(randint(1,10)*0.01)
        periodes.append(randint(1,5))

    def hprime(x):
        pos=int(N*x)
        pos_rel=x-pos
        return amplitude[pos]*sin(2*pi*N*periodes[pos]*pos_rel)

    def condY0(x):
        return hprime(x)*u_0

You should use an UserExpression:

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

    def eval(self, values, x):
        values[0] = -l2*condY0(x[0])

f = interpolate(aux(), V)

However, to me it is unclear what you would like your source term to be.