Pass Function to C++ expression

For anyone reading this later: You have to includesome header files :slight_smile:
This worked for me. This code simply reads the values from the function/Expression/MeshFunction and adds the values. Hope this helps anyone :slight_smile: :upside_down_face:

#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
namespace py = pybind11;

#include <dolfin/function/Expression.h> // for expressions
#include <dolfin/mesh/MeshFunction.h> //  for MeshFunctions
#include <dolfin/function/Function.h> // for functions



class your_Function_Name : public dolfin::Expression
{
   public:
       your_Function_Name() : dolfin::Expression(3){} // 3 Dimensional vector as output, use Expression() for scalar
       void eval(Eigen::Ref<Eigen::VectorXd> values, Eigen::Ref<const Eigen::VectorXd> x, const ufc::cell& cell) const override
       {

           func1->eval(values, x);
           const double val1 = values[0];
           func1->eval(values, x);
           const double val2 = values[0];
           values[0] = val1 + val2; // do your stuff here

           exp1->eval(values, x);
           const double val3 = values[0];
           exp2->eval(values, x);
           const double val4 = values[0];
           values[1] = val3 + val4; // do your stuff here

           const uint cell_index = cell.index;
           values[2] = (*MshFunc1)[cell_index] + (*MshFunc2)[cell_index]; // do your stuff here

       }

       std::shared_ptr<dolfin::Function> func1;
       std::shared_ptr<dolfin::Function> func2;
       std::shared_ptr<dolfin::Expression> exp1;
       std::shared_ptr<dolfin::Expression> exp2;
       std::shared_ptr<dolfin::MeshFunction<size_t>> MshFunc1;
       std::shared_ptr<dolfin::MeshFunction<size_t>> MshFunc2;
};
PYBIND11_MODULE(SIGNATURE, m)
{
   py::class_<your_Function_Name, std::shared_ptr<your_Function_Name>, dolfin::Expression>(m, "your_Function_Name")
   .def(py::init<>())
   .def_readwrite("func1", &your_Function_Name::func1)
   .def_readwrite("func2", &your_Function_Name::func2)
   .def_readwrite("exp1", &your_Function_Name::exp1)
   .def_readwrite("exp2", &your_Function_Name::exp2)
   .def_readwrite("MshFunc1", &your_Function_Name::MshFunc1)
   .def_readwrite("MshFunc2", &your_Function_Name::MshFunc2);
}
3 Likes