aboutsummaryrefslogtreecommitdiffstats
path: root/interface/pyfunc_obj.hpp
blob: 3e75d341fde7558ded0bc1ae69d63cd6458a55ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
   \file pyfunc_obj.hpp
   \brief function object wrappers for python functions
   \author Junhua Gu
 */


#ifndef PYFUNC_OBJ_HPP
#define PYFUNC_OBJ_HPP
#include <boost/python.hpp>
#include <core/optimizer.hpp>
#include <core/opt_traits.hpp>


namespace opt_utilities
{

  template <typename Ty,typename Tx>
  class pyfunc_obj
    :public func_obj<Ty,Tx>
  {
  private:
    boost::python::object pyfunc;
  public:
    pyfunc_obj()
    {
      if(!Py_IsInitialized())
	{
	  Py_Initialize();
	}
    }

    pyfunc_obj(const pyfunc_obj& rhs)
      :pyfunc(rhs.pyfunc)
    {}

    pyfunc_obj& operator=(const pyfunc_obj& rhs)
    {
      pyfunc=rhs.pyfunc;
    }

    ~pyfunc_obj()
    {}

  public:
    void attach(const std::string module_name,
		const std::string func_name)
    {
      boost::python::object mod(boost::python::import(module_name.c_str()));
      pyfunc=mod.attr(func_name.c_str());
      
    }
  private:
    func_obj<Ty,Tx>* do_clone()const
    {
      return new pyfunc_obj(*this);
    }
    
    void do_destroy()
    {
      delete this;
    }
    
    Ty do_eval(const Tx& x)
    {
      boost::python::list args;
      for(size_t i=0;i<get_size(x);++i)
	{
	  args.append(get_element(x,i));
	}
      return boost::python::extract<Ty>(pyfunc(args));
    }
  };
}


#endif
//EOF