### How to make new expression or function using existing expression?

68
views
0
22 days ago by
Hi everyone,

I encountered a situation implementing theta time scheme. I need to make an expression by an existing expression.

For example. I have f = Expression('sin(x[0]*t)',t=0), and I need to use theta*f(t)+(1-theta)*f(t-dt). How can I make a new expression f_theta(t; theta,dt) from original f.

In pure python I can use lambda expression or functools module.

I know I can circonvent this problem by caching result from last step. But what if I really want to have a wrap on the existing function or expression? For function, it is fairly simple because the implementation should be similar to an array of current values. But for expression, change of parameter seems not so straight forward to me.
Community: FEniCS Project

1
21 days ago by
Hello,

I would do this workaround:

class MyFunctionExpression(Expression):
def __init__(self, dt, t, theta, **kwargs):
self.dt = dt
self.t = t
self.theta = theta

def myFunction(self, x, t):
return sin(x[0]) * self.t

def eval(self, values, x):
values[0] = self.theta * self.myFunction(x, self.t) + (1-self.theta) * self.myFunction(x, self.t-self.dt)​

To initialize such expression class you give the initial parameters:

# MyFunctionExpression(dt, t, theta, element)
f = MyFunctionExpression(0.1, 1.0, 0.0, element=V.ufl_element())
​

where V is the function space...

and to change the parameters you can do this at every iteration:

# increasing the dt
f.dt = 0.2
# changing the theta parameter
f.theta = 0.5

and to assign such expression to a function:

u = Function(V)
u.assign(f)​

I hope it helps..

Regards, Leonardo