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

How to subclass expression with changeable parameters?

+3 votes

Hi there,

I read about the Expression part in the reference, but it doesn't mention how to overload the expression with changeable parameters. In the reference, one example is given as:

class MyExpression0(Expression):
def eval(self, value, x):
    dx = x[0] - 0.5
    dy = x[1] - 0.5
    value[0] = 500.0*exp(-(dx*dx + dy*dy)/0.02)
    value[1] = 250.0*exp(-(dx*dx + dy*dy)/0.01)
def value_shape(self):
    return (2,)

f0 = MyExpression0()

Here 500.0 and 250.0 are fixed values. Can I set them as changeable variables instead? Then we can change the variables in a way similar to:

f = Expression('A*sin(x[0]) + B*cos(x[1])', A=2.0, B=4.0)
f.A = 1.0

If so, how could I define this class with parameters?

asked Aug 27, 2014 by Chao Zhang FEniCS User (1,180 points)
edited Aug 27, 2014 by Chao Zhang

1 Answer

+5 votes
 
Best answer

Try:

class MyExpression0(Expression):
def __init__(self, a, b):
    self.a = a
    self.b = b
def eval(self, value, x):
    dx = x[0] - 0.5
    dy = x[1] - 0.5
    value[0] = self.a*exp(-(dx*dx + dy*dy)/0.02)
    value[1] = self.b*exp(-(dx*dx + dy*dy)/0.01)
def value_shape(self):
    return (2,)

f0 = MyExpression0(500.,250.)
answered Aug 27, 2014 by johanhake FEniCS Expert (22,480 points)
selected Sep 1, 2014 by Chao Zhang
...