void defineUtil() { // NOTE: This file has a ton of macros and templates, so it's going to take a while to compile ... init_numpy(); boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); register_exception_translator<AssertException>(&translateAssertException); ADD_MODULE(util); // NOTE: When overloading functions always make sure to put the array/matrix function before the vector one MAT_CONV( MatrixX ); MAT_CONV( RMatrixX ); MAT_CONV( VectorX ); MAT_CONV( ArrayXX ); MAT_CONV( RArrayXX ); MAT_CONV( ArrayX ); // Define some std::vectors MAT_VEC( RMatrixX ); MAT_VEC( VectorX ); // Datastructures class_< std::vector<int> >("VecInt").def( vector_indexing_suite< std::vector<int> >() ).def( VectorInitSuite< std::vector<int> >() ); class_< std::vector<float> >("VecFloat").def( vector_indexing_suite< std::vector<float> >() ).def( VectorInitSuite< std::vector<float> >() ); }
/* * Convert a numpy ndarray to a jep.NDArray. * * @param env the JNI environment * @param pyobj the numpy ndarray to convert * * @return a new jep.NDArray or NULL if errors are encountered */ jobject convert_pyndarray_jndarray(JNIEnv *env, PyObject *pyobj) { npy_intp *dims = NULL; jint *jdims = NULL; jobject jdimObj = NULL; jobject primitive = NULL; jobject result = NULL; PyArrayObject *pyarray = (PyArrayObject*) pyobj; int ndims = 0; int i; init_numpy(); if (ndarrayInit == 0) { ndarrayInit = (*env)->GetMethodID(env, JEP_NDARRAY_TYPE, "<init>", "(Ljava/lang/Object;[I)V"); if (process_java_exception(env) || !ndarrayInit) { return NULL; } } // setup the int[] constructor arg ndims = PyArray_NDIM(pyarray); dims = PyArray_DIMS(pyarray); jdims = malloc(((int) ndims) * sizeof(jint)); for (i = 0; i < ndims; i++) { jdims[i] = (jint) dims[i]; } jdimObj = (*env)->NewIntArray(env, ndims); if (process_java_exception(env) || !jdimObj) { free(jdims); return NULL; } (*env)->SetIntArrayRegion(env, jdimObj, 0, ndims, jdims); free(jdims); if (process_java_exception(env)) { return NULL; } // setup the primitive array arg primitive = convert_pyndarray_jprimitivearray(env, pyobj, NULL); if (!primitive) { return NULL; } result = (*env)->NewObject(env, JEP_NDARRAY_TYPE, ndarrayInit, primitive, jdimObj); if (process_java_exception(env) || !result) { return NULL; } return result; }
PyObject * wrap_double_array(double* d, int len) { init_numpy(); PyArray_Descr *type = PyArray_DescrFromType(NPY_DOUBLE); npy_intp dim[1] = {len}; npy_intp strides[1] = {sizeof(double)}; PyObject* arr = PyArray_NewFromDescr( &PyArray_Type, type, 1, dim, strides, d, NPY_CONTIGUOUS | NPY_WRITEABLE, NULL /*PyObject *obj*/ ); PyArray_BASE(arr) = make_deallocator_for(d, 0); return arr; }
PyObject * wrapDMat(DMat d) { init_numpy(); PyArray_Descr *type = PyArray_DescrFromType(NPY_DOUBLE); npy_intp dim[2] = {d->rows, d->cols}; npy_intp strides[2] = {d->cols*sizeof(double), sizeof(double)}; PyObject* arr = PyArray_NewFromDescr( &PyArray_Type, type, 2, dim, strides, d->value[0], NPY_CONTIGUOUS | NPY_WRITEABLE, NULL /*PyObject *obj*/ ); PyArray_BASE(arr) = make_deallocator_for(d->value, 1); return arr; }
DoomGamePython::DoomGamePython() { init_numpy(); }
static void* initialize2(bool register_scalar_converters) { init_numpy(); import_ufunc(); if (register_scalar_converters) dtype::register_scalar_converters(); }
bool InteractionClassifier::initialize(const std::string& model, const std::vector<std::string>& interactions) { // Update list of interactions // TODO: Load from model this->interactions = interactions; // Step 1 topviewkinect::util::log_println("Initializing Python..."); Py_Initialize(); init_numpy(); PyRun_SimpleString("import sys"); std::ostringstream path_ss; path_ss << "sys.path.append(\"" << topviewkinect::EAGLESENSE_DIRECTORY << "\")"; PyRun_SimpleString(path_ss.str().c_str()); // Step 2 topviewkinect::util::log_println("Initializing classifier..."); PyObject* p_module = PyImport_ImportModule("classifier"); if (p_module == NULL) { PyErr_Print(); topviewkinect::util::log_println("Failed to load the classifier module."); return false; } PyObject* p_classifier_class = PyObject_GetAttrString(p_module, "TopviewInteractionClassifier"); if (p_classifier_class == NULL) { PyErr_Print(); topviewkinect::util::log_println("Failed to load the classifier class."); return false; } Py_DECREF(p_module); this->p_classifier = PyObject_CallObject(p_classifier_class, NULL); if (this->p_classifier == NULL) { PyErr_Print(); topviewkinect::util::log_println("Failed to create a classifier object."); return false; } Py_DECREF(p_classifier_class); // Step 3 topviewkinect::util::log_println("Loading model..."); std::string path_to_model = topviewkinect::get_model_filepath(model); PyObject* p_load_args = Py_BuildValue("(s)", path_to_model.c_str()); PyObject* p_load = PyObject_GetAttrString(this->p_classifier, "load"); PyObject* p_result = PyObject_CallObject(p_load, p_load_args); if (p_result == NULL) { PyErr_Print(); topviewkinect::util::log_println("Failed to call the classifier `load` function."); return false; } Py_DECREF(p_load_args); Py_DECREF(p_load); Py_DECREF(p_result); // Step 4 topviewkinect::util::log_println("Loading 'predict' function..."); this->p_predict_func = PyObject_GetAttrString(this->p_classifier, "predict"); if (!PyCallable_Check(this->p_predict_func)) { PyErr_Print(); topviewkinect::util::log_println("Failed to load the classifier `predict` function."); return false; } return true; }
int npy_array_check(PyObject *obj) { init_numpy(); return PyArray_Check(obj); }
/* * Converts a jep.NDArray to a numpy ndarray. * * @param env the JNI environment * @param obj the jep.NDArray to convert * * @return a numpy ndarray, or NULL if there were errors */ PyObject* convert_jndarray_pyndarray(JNIEnv *env, jobject obj) { npy_intp *dims = NULL; jobject jdimObj = NULL; jint *jdims = NULL; jobject data = NULL; PyObject *result = NULL; jsize ndims = 0; int i; init_numpy(); if (ndarrayGetDims == 0) { ndarrayGetDims = (*env)->GetMethodID(env, JEP_NDARRAY_TYPE, "getDimensions", "()[I"); if (process_java_exception(env) || !ndarrayGetDims) { return NULL; } } if (ndarrayGetData == 0) { ndarrayGetData = (*env)->GetMethodID(env, JEP_NDARRAY_TYPE, "getData", "()Ljava/lang/Object;"); if (process_java_exception(env) || !ndarrayGetData) { return NULL; } } // set up the dimensions for conversion jdimObj = (*env)->CallObjectMethod(env, obj, ndarrayGetDims); if (process_java_exception(env) || !jdimObj) { return NULL; } ndims = (*env)->GetArrayLength(env, jdimObj); if (ndims < 1) { PyErr_Format(PyExc_ValueError, "ndarrays must have at least one dimension"); return NULL; } jdims = (*env)->GetIntArrayElements(env, jdimObj, 0); if (process_java_exception(env) || !jdimObj) { return NULL; } dims = malloc(((int) ndims) * sizeof(npy_intp)); for (i = 0; i < ndims; i++) { dims[i] = jdims[i]; } (*env)->ReleaseIntArrayElements(env, jdimObj, jdims, JNI_ABORT); (*env)->DeleteLocalRef(env, jdimObj); // get the primitive array and convert it data = (*env)->CallObjectMethod(env, obj, ndarrayGetData); if (process_java_exception(env) || !data) { return NULL; } result = convert_jprimitivearray_pyndarray(env, data, ndims, dims); if (!result) { process_java_exception(env); } // primitive arrays can be large, encourage garbage collection (*env)->DeleteLocalRef(env, data); free(dims); return result; }
int c_function(int *n, float **mat) { PyObject *pModule = NULL; PyObject *pFunc = NULL; PyObject *pArg = NULL; PyObject *pRet = NULL; PyObject *pName = NULL; size_t size = *n; npy_intp *dim; int i, j; dim = (npy_intp *) malloc(sizeof(npy_intp)*(size)); for (i=0; i < size; i++) dim[i] = size; Py_Initialize(); if (!Py_IsInitialized()) { fprintf(stderr, "nao foi possivel inicializar o python!\n"); return -1; } init_numpy(); PyObject* pMat = PyArray_NewFromDescr( &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL); Py_INCREF(pMat); pName = PyString_FromString("function"); pModule = PyImport_Import(pName); pFunc = PyObject_GetAttrString(pModule, "py_function"); if(!PyCallable_Check(pFunc)) { printf("func not callable!\n"); return -1; } pArg = PyTuple_New (2); PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size)); PyTuple_SetItem(pArg, 1, pMat); pRet = PyObject_CallObject(pFunc, pArg); printf("py ret: %s\n", PyString_AsString(pRet)); Py_DECREF (pMat); Py_DECREF (pName); Py_DECREF (pModule); Py_DECREF (pFunc); Py_DECREF (pArg); Py_DECREF (pRet); Py_Finalize(); return 0; }
void defineUtil() { // NOTE: This file has a ton of macros and templates, so it's going to take a while to compile ... init_numpy(); boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); register_exception_translator<AssertException>(&translateAssertException); ADD_MODULE(util); class_<Edge>("Edge") .def(init<int,int>()) .def_readonly( "a", &Edge::a ) .def_readonly( "b", &Edge::b ) .def_pickle(Edge_pickle()); class_< Edges >("Edges") .def(init<Edges>()) .def(vector_indexing_suite<Edges>()); def("qp",static_cast<VectorXf(*)(const RMatrixXf &, const VectorXf &, const RMatrixXf &, const VectorXf &)>(&qp)); def("qp",static_cast<VectorXd(*)(const RMatrixXd &, const VectorXd &, const RMatrixXd &, const VectorXd &)>(&qp)); // NOTE: When overloading functions always make sure to put the array/matrix function before the vector one MAT_CONV( MatrixX ); MAT_CONV( RMatrixX ); MAT_CONV( VectorX ); MAT_CONV( ArrayXX ); MAT_CONV( RArrayXX ); MAT_CONV( ArrayX ); // Defien some std::vectors MAT_VEC( RMatrixX ); MAT_VEC( VectorX ); class_< std::vector< std::vector<RMatrixXb> > >("VecVecRMatrixXb") .def( vector_indexing_suite< std::vector< std::vector<RMatrixXb> >, true >() ) .def( VectorInitSuite< std::vector< std::vector<RMatrixXb> > >() ); // Datastructures class_< std::vector<int> >("VecInt").def( vector_indexing_suite< std::vector<int> >() ).def( VectorInitSuite< std::vector<int> >() ); class_< std::vector<float> >("VecFloat").def( vector_indexing_suite< std::vector<float> >() ).def( VectorInitSuite< std::vector<float> >() ); class_< std::vector<std::string> >("VecStr").def( vector_indexing_suite< std::vector<std::string> >() ).def( VectorInitSuite< std::vector<std::string> >() ); // class_<Polygons>("Polygons").def( vector_indexing_suite<Polygons,true >() ); class_< std::vector<Polygons> >("VecPolygons").def( vector_indexing_suite< std::vector<Polygons> >() ) .def_pickle(VecPolygons_pickle_suite()); // Rasterize def("rasterize",static_cast<RMatrixXf(*)(const Polygon &,int)>(&rasterize),rasterize1()); def("rasterize",static_cast<RMatrixXf(*)(const Polygons &,int)>(&rasterize),rasterize2()); // Facility location class_<Floc>("Floc") .def("energy",Floc::energy) .staticmethod("energy") .def("greedy",Floc::greedy) .staticmethod("greedy") .def("jms",Floc::jms) .staticmethod("jms") .def("myz",Floc::myz) .staticmethod("myz") .def("local",Floc::local) .staticmethod("local") .def("scaledLocal",Floc::scaledLocal) .staticmethod("scaledLocal") .def("tabu",Floc::tabu) .staticmethod("tabu"); // Geodesic distance class_<GeodesicDistance>("GeodesicDistance",init<Edges,VectorXf>()) .def("compute",static_cast<VectorXf (GeodesicDistance::*)(int)const>( &GeodesicDistance::compute )) .def("compute",static_cast<VectorXf (GeodesicDistance::*)(const VectorXf &)const>( &GeodesicDistance::compute )) .add_property("N",&GeodesicDistance::N); }