#ifndef __HELPERS__HPP__ #define __HELPERS__HPP__ using namespace pcsvm; namespace py=boost::python; #define SVFloat SparseVector struct RuntimeError //: std::exception { RuntimeError(const std::string & what_ ): what__(what_) {}; const char *what() const throw() { return what__.c_str(); } std::string what__; }; struct TypeError //: std::exception { TypeError(const std::string & what_ ): what__(what_) {}; const char *what() const throw() { return what__.c_str(); } std::string what__; }; void translateRuntimeError(RuntimeError const &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } void translateTypeError(TypeError const &e) { PyErr_SetString(PyExc_TypeError, e.what()); } /* void translateKernelError(ExternalKernel::KernelError const &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } */ /////////////////////////////////////////////////////////////////////////////////// // // utilities, often used functions / procedures // /////////////////////////////////////////////////////////////////////////////////// struct int_pair_to_tuple { static PyObject* convert( std::pair const & int_pair) { return py::incref(py::make_tuple(int_pair.first, int_pair.second).ptr()); } }; template struct list_of_T_to_python_list { static PyObject* convert( std::list const & TList) { py::list retVal; typename std::list::const_iterator it; for (it = TList.begin(); it != TList.end(); ++it) retVal.append(*it); return py::incref(retVal.ptr()); } }; enum PyType { LIST, TUPLE, DICT, INTEGER, FLOAT, LONG, ARRAY, STR, OBJECT }; PyType getType(const py::object &o) { if (py::extract(o).check()) return TUPLE; if (py::extract(o).check()) return LIST; if (py::extract(o).check()) return DICT; if (py::extract(o).check()) return ARRAY; if (py::extract(o).check()) return STR; if (py::extract(o).check()) return LONG; if (py::extract(o).check()) return INTEGER; if (py::extract(o).check()) return FLOAT; return OBJECT; } template bool isType(const py::object &o) { return py::extract(o).check(); } int PyLen(const py::object &o) { return py::extract(o.attr("__len__")()); } inline py::object pass_through(py::object const& o) { return o; } SVFloat imul(const SVFloat &x, float a) { SparseVector tmp = x; tmp *= a; return tmp; } #endif