Hi, f=Expression(“g”, g=g, degree=1)
should be thought of as defining f such that f(x)=g(x)
. In ran_mu_expr=Expression(“ran_mu”,ran_mu=ran_mu, degree=4)
you seem to make an assumption that Expression
will do the lookup in ran_mu
array to assign the coefficient value appropriately. That is not the case. Consider instead
from dolfin import *
import numpy as np
class RandomScalar(UserExpression):
def eval(self, value, x):
value[:] = np.random.rand()
def value_shape(self, ):
return ()
def fill_random0(f):
f.assign(interpolate(RandomScalar(degree=1), f.function_space()))
return f
def fill_random1(f):
f.vector().set_local(np.random.rand(f.vector().local_size()))
return f
# To illustrate speed difference
for n in (64, 128, 256):
mesh = UnitSquareMesh(n, n)
V = FunctionSpace(mesh, 'CG', 1)
f = Function(V)
print('n=%d' % n)
for fill in (fill_random0, fill_random1):
t = Timer()
fill(f)
print('\t', t.stop())
# Expression using function
mesh = UnitSquareMesh(n, n)
V = FunctionSpace(mesh, 'CG', 1)
f = Function(V)
# Randomize
f = fill_random1(f)
f_expr = Expression('f', f=f, degree=1)
print(sqrt(abs(assemble(inner(f-f_expr, f-f_expr)*dx))))