How to define piecewise source terms?

How can I define a piecewise expression for the source/sink term f?
Thanks.

Something like this on your mind:

from dolfin import *

mesh = UnitSquareMesh(10,10)

p1 = Expression("x[0]", degree=1, domain=mesh)
p2 = Expression("1-x[0]*x[1]", degree=1, domain=mesh)

g = Expression('x[0] < 0.25 + DOLFIN_EPS ? p1 : (x[0] < 0.5 + DOLFIN_EPS ? p2 : 0)',
               p1=p1, p2=p2, degree=2)

V = FunctionSpace(mesh, "DG", 0)
g_int = interpolate(g, V)
out = XDMFFile("dg.xdmf")
out.write_checkpoint(g_int, "g", 0.0, append=False)

You can of course switch the functionspace to a CG space if that is more suitable.
This answer was inspired by:
https://fenicsproject.org/qa/7684/how-to-define-piecewise-function-on-more-pieces-of-the-domain/

1 Like

Piecewise expressions can be defined using the UFL conditionals operators. Please, see page 23 of the UFL documentation: https://readthedocs.org/projects/fenics-ufl/downloads/pdf/latest/

1 Like