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

How to define a piecewise function on more pieces of the domain?

0 votes

How can I define a piecewise function f with Expression on 3 pieces of a
unit square [0, 1] x [0,1]?

Something like:

f = p1,  x[0] <= 1/4
f = p2,  x[0] >= 1/4 and x[0] <= 1/2
f = 0,    x[0] >= 1/2

( I tried to pass the Expressions folowing the post http://fenicsproject.org/qa/3397/define-a-piecewise-constant-source?show=3397#q3397 of piecewise constant function withou success
too. )

related to an answer for: piecewise defintion of function
asked Jul 26, 2015 by Andre Machado FEniCS User (1,040 points)

1 Answer

+3 votes
 
Best answer

Hi, could explain the problem in more detail? The constructs below work, but perhaps they are not what you are looking for

from dolfin import *

class Foo(Expression):
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

    def eval(self, values, x):
        if x[0] < 0.25 + DOLFIN_EPS:
            values[0] = self.p1(x)
        elif x[0] < 0.5 + DOLFIN_EPS:
            values[0] = self.p2(x)
        else:
            values[0] = 0

mesh = UnitSquareMesh(20, 20)

p1 = Expression('x[0]', degree=1, domain=mesh)
p2 = Expression('1-x[0]', degree=1, domain=mesh)
f = Foo(p1, p2)

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

V = FunctionSpace(mesh, 'CG', 1)
f = interpolate(f, V)
g = interpolate(g, V)

plot(f, title='f')
plot(g, title='g')
interactive()
answered Jul 27, 2015 by MiroK FEniCS Expert (80,920 points)
selected Aug 9, 2015 by Andre Machado

It s perfect! Thank you very much MiroK!

...