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

How to set function as class variable in C++ expression used in Python?

+2 votes

Hello

In my application, I need an expression to have a function as a class variable, which is used in the calculations in the eval function. This function will be set from the outside in my python code, which worked fine when I wrote the code for my Expression in Python.

However, I need to increase the speed of the evaluation and has tried to do the same with an expression in C++ code. However, I get error messages of the form:

   error: no match for call to ‘(dolfin::Function) (const dolfin::Array<double>

, when running the simplified version of the code that is found below. What can I do to make it work?

 from dolfin import *

my_expression ='''

class test : public Expression
{
public:

  test() : Expression(1) {}

  void eval(Array<double>& values, const Array<double>& x) 
  {
    values[0] = f(x);
  }

  Function& f;

};

'''
mesh = UnitSquareMesh(8, 8)
V = FunctionSpace(mesh, "Lagrange", 1)
u=interpolate(Constant(1.0),V)
c=Expression(cppcode=my_expression)
c.f=u
asked Jun 16, 2014 by BB FEniCS Novice (710 points)

1 Answer

+4 votes
 
Best answer

Hi, f(x) or f.__call__(x) is python-only method. Try instead

from dolfin import *

my_expression ='''
class test : public Expression
{
public:

  test() : Expression() { }

  void eval(Array<double>& values, const Array<double>& x) const
  {
    f->eval(values, x);
  }

  std::shared_ptr<const Function> f; // DOLFIN 1.4.0
  //boost::shared_ptr<const Function> f; // DOLFIN 1.3.0
};
'''

mesh = RectangleMesh(-1, -1, 1, 1, 40, 40)

V = FunctionSpace(mesh, 'CG', 1)

f = interpolate(Expression('sin(2*pi*(x[0]*x[0] + x[1]*x[1]))'), V)

g = Expression(my_expression)
g.f = f

plot(g, mesh=mesh)
interactive()
answered Jun 16, 2014 by MiroK FEniCS Expert (80,920 points)
selected Jul 3, 2014 by BB

Thanks! It worked!

...