Custom expressions defined in Python are no longer subclasses of Expression
, but, instead, of a separate class, UserExpression
. However, I will note that what it looks like you’re trying to do can be accomplished with the standard Expression
constructor, by passing a tuple of C++ snippets:
w_init = Expression(2*('1.0*random() + 0.25',),
element = W.ufl_element())
I will also add that I’m not sure the C++ random()
function is doing what you think it is; this will return very large numerical values. To get random floating point numbers between, say, 0 and 1, you would want something like
random()/((double)RAND_MAX)
because random()
on its own returns an integer between 0
and RAND_MAX
(which is about 2 billion).
EDIT: Alternatively, if you are trying to use the NumPy random()
function (based on the import
statements at the top) you could do something like
from numpy.random import random
class IC(UserExpression):
def eval(self,values,x):
values[0] = 1.0*random() + 0.25
values[1] = 1.0*random() + 0.25
def value_shape(self):
return(2,)
w_init = IC(element = W.ufl_element())