PageRenderTime 32ms CodeModel.GetById 5ms RepoModel.GetById 1ms app.codeStats 0ms

/src/interfaces/modular/SGBase.i

https://code.google.com/
Swig | 501 lines | 411 code | 68 blank | 22 comment | 0 complexity | 42f465d5213e98f624314dec0c523814 MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, BSD-3-Clause
  1. /* base includes required by any module */
  2. %include "stdint.i"
  3. %include "exception.i"
  4. %define SERIALIZABLE_DUMMY(SWIGCLASS)
  5. %extend SWIGCLASS {
  6. bool save_serializable(CSerializableFile* file, const char* prefix="") { return false; };
  7. bool load_serializable(CSerializableFile* file, const char* prefix="") { return false; };
  8. }
  9. %enddef
  10. #ifdef SWIGJAVA
  11. %typemap(javainterfaces) SWIGTYPE "java.io.Externalizable"
  12. %typemap(javaincludes) SWIGTYPE
  13. %{
  14. import org.shogun.SerializableFile;
  15. import org.shogun.SerializableAsciiFile;
  16. %}
  17. %typemap(javacode) SWIGTYPE
  18. %{
  19. public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException {
  20. java.util.Random randomGenerator = new java.util.Random();
  21. String tmpFileName = System.getProperty("java.io.tmpdir") + "/" + randomGenerator.nextInt() + "shogun.tmp";
  22. java.io.File file = null;
  23. java.io.FileInputStream in = null;
  24. int ch;
  25. try {
  26. file = new java.io.File(tmpFileName);
  27. file.createNewFile();
  28. SerializableAsciiFile tmpFile = new SerializableAsciiFile(tmpFileName, 'w');
  29. this.save_serializable(tmpFile);
  30. tmpFile.close();
  31. in = new java.io.FileInputStream(file);
  32. // TODO bufferize
  33. while((ch=in.read()) != -1) {
  34. out.write(ch);
  35. }
  36. file.delete();
  37. } catch (java.io.IOException ex) {
  38. } finally {
  39. try {
  40. in.close();
  41. } catch (java.io.IOException ex) {
  42. }
  43. }
  44. }
  45. public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException {
  46. java.util.Random randomGenerator = new java.util.Random();
  47. String tmpFileName = System.getProperty("java.io.tmpdir") + "/" + randomGenerator.nextInt() + "shogun.tmp";
  48. java.io.File file = null;
  49. java.io.FileOutputStream out = null;
  50. int ch;
  51. try {
  52. file = new java.io.File(tmpFileName);
  53. file.createNewFile();
  54. out = new java.io.FileOutputStream(file);
  55. while ((ch=in.read()) != -1) {
  56. out.write(ch);
  57. }
  58. out.close();
  59. SerializableAsciiFile tmpFile = new SerializableAsciiFile(tmpFileName,'r');
  60. this.load_serializable(tmpFile);
  61. tmpFile.close();
  62. file.delete();
  63. } catch (java.io.IOException ex) {
  64. } finally {
  65. try {
  66. out.close();
  67. } catch (java.io.IOException ex) {
  68. }
  69. }
  70. }
  71. %}
  72. #endif
  73. %{
  74. #ifdef SWIGRUBY
  75. extern "C" {
  76. #include <ruby.h>
  77. #include <narray.h>
  78. #include <stdlib.h>
  79. #include <stdio.h>
  80. }
  81. VALUE (*na_to_array_dl)(VALUE);
  82. VALUE (*na_to_narray_dl)(VALUE);
  83. VALUE cNArray;
  84. #include <dlfcn.h>
  85. #endif
  86. #if defined(SWIGPERL) && defined(HAVE_PDL)
  87. #ifdef __cplusplus
  88. extern "C" {
  89. #endif
  90. #include <pdlcore.h>
  91. #include <ppport.h>
  92. #ifdef __cplusplus
  93. }
  94. #endif
  95. #endif
  96. /* required for python */
  97. #define SWIG_FILE_WITH_INIT
  98. #if defined(SWIGJAVA) || defined(SWIGCSHARP)
  99. #include <shogun/base/init.h>
  100. #endif
  101. #include <shogun/lib/common.h>
  102. #include <shogun/io/SGIO.h>
  103. #include <shogun/lib/ShogunException.h>
  104. #include <shogun/lib/DataType.h>
  105. #include <shogun/base/Version.h>
  106. #include <shogun/base/Parallel.h>
  107. #include <shogun/base/SGObject.h>
  108. extern void sg_global_print_message(FILE* target, const char* str);
  109. extern void sg_global_print_warning(FILE* target, const char* str);
  110. extern void sg_global_print_error(FILE* target, const char* str);
  111. #ifndef DISABLE_CANCEL_CALLBACK
  112. extern void sg_global_cancel_computations(bool &delayed, bool &immediately);
  113. #endif
  114. #ifdef SWIGR
  115. #include <Rdefines.h>
  116. #endif
  117. #ifdef SWIGPYTHON
  118. #include <shogun/io/SerializableFile.h>
  119. #include <shogun/io/SerializableAsciiFile.h>
  120. #include <shogun/io/SerializableHdf5File.h>
  121. static int pickle_ascii;
  122. #endif
  123. using namespace shogun;
  124. %}
  125. #if defined (SWIGPERL) && defined(HAVE_PDL)
  126. %header %{
  127. SV* CoreSV;
  128. Core* PDL;
  129. %}
  130. #endif
  131. %init %{
  132. #if defined (SWIGPERL) && defined(HAVE_PDL)
  133. //check Core.xs //Core* PDL_p = pdl__Core_get_Core();
  134. //PDL_COMMENT("Get pointer to structure of core shared C routines")
  135. //PDL_COMMENT("make sure PDL::Core is loaded")
  136. perl_require_pv("PDL::Core");
  137. CoreSV = perl_get_sv("PDL::SHARE",FALSE);
  138. // PDL_COMMENT("SV* value")
  139. if (CoreSV == NULL)
  140. Perl_croak(aTHX_ "Can't load PDL::Core module");
  141. PDL = INT2PTR(Core*, SvIV( CoreSV ));
  142. // PDL_COMMENT("Core* value")
  143. #endif
  144. #ifdef SWIGPYTHON
  145. import_array();
  146. #endif
  147. #if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
  148. #ifndef DISABLE_CANCEL_CALLBACK
  149. shogun::init_shogun(&sg_global_print_message, &sg_global_print_warning,
  150. &sg_global_print_error, &sg_global_cancel_computations);
  151. #else
  152. shogun::init_shogun(&sg_global_print_message, &sg_global_print_warning,
  153. &sg_global_print_error);
  154. #endif
  155. #endif
  156. #ifdef SWIGRUBY
  157. rb_require("narray");
  158. cNArray = rb_const_get(rb_cObject, rb_intern("NArray"));
  159. char* error=NULL;
  160. void* handle = dlopen(NARRAY_LIB, RTLD_LAZY);
  161. if (!handle) {
  162. fprintf(stderr, "%s\n", dlerror());
  163. exit(EXIT_FAILURE);
  164. }
  165. dlerror(); /* Clear any existing error */
  166. *(void **) (&na_to_array_dl) = dlsym(handle, "na_to_array");
  167. if ((error = dlerror()) != NULL) {
  168. fprintf(stderr, "na_to_array %s\n", error);
  169. exit(EXIT_FAILURE);
  170. }
  171. /*if (cNArray==0)
  172. {
  173. void (*Init_narray)();
  174. *(void **) (&Init_narray) = dlsym(handle, "Init_narray");
  175. if ((error = dlerror()) != NULL) {
  176. fprintf(stderr, "Init_narray %s\n", error);
  177. exit(EXIT_FAILURE);
  178. }
  179. fprintf(stderr, "initing narray\n");
  180. (*Init_narray)();
  181. }*/
  182. *(void **) (&na_to_narray_dl) = dlsym(handle, "na_to_narray");
  183. if ((error = dlerror()) != NULL) {
  184. fprintf(stderr, "na_to_narray %s\n", error);
  185. exit(EXIT_FAILURE);
  186. }
  187. /* cNArray = (*(VALUE*)(dlsym(handle, "cNArray")));
  188. if ((error = dlerror()) != NULL) {
  189. fprintf(stderr, "cNArray %s\n", error);
  190. exit(EXIT_FAILURE);
  191. }*/
  192. #endif
  193. %}
  194. #ifdef SWIGPYTHON
  195. %{
  196. static int print_sgobject(PyObject *pyobj, FILE *f, int flags) {
  197. void *argp;
  198. int res;
  199. res = SWIG_ConvertPtr(pyobj, &argp, SWIGTYPE_p_shogun__CSGObject, 0);
  200. if (!SWIG_IsOK(res)) {
  201. SWIG_Error(SWIG_ArgError(res), "in method 'CSGObject::tp_print', argument 1 of type 'CSGObject *'");
  202. return SWIG_ERROR;
  203. }
  204. CSGObject *obj = reinterpret_cast<CSGObject*>(argp);
  205. fprintf(f, "%s", obj->get_name());
  206. return 0;
  207. }
  208. %}
  209. %typemap(out) PyObject* __reduce_ex__(int proto)
  210. {
  211. return PyObject_CallMethod(self, (char*) "__reduce__", (char*) "");
  212. }
  213. %typemap(in) __setstate__(PyObject* state) {
  214. $1 = $input;
  215. }
  216. %typemap(out) PyObject* __getstate__()
  217. {
  218. $result=$1;
  219. }
  220. #elif defined(SWIGPERL)
  221. %{
  222. static int print_sgobject(SV* pobj, FILE *f, int flags) {
  223. void *argp;
  224. int res;
  225. res = SWIG_ConvertPtr(pobj, &argp, SWIGTYPE_p_shogun__CSGObject, 0);
  226. if (!SWIG_IsOK(res)) {
  227. SWIG_Error(SWIG_ArgError(res), "in method 'CSGObject::tp_print', argument 1 of type 'CSGObject *'");
  228. return SWIG_ERROR;
  229. }
  230. CSGObject *obj = reinterpret_cast<CSGObject*>(argp);
  231. fprintf(f, "%s", obj->get_name());
  232. return 0;
  233. }
  234. %}
  235. #endif
  236. %exception
  237. {
  238. try
  239. {
  240. $action
  241. }
  242. #if defined(SWIGPYTHON) && defined(USE_SWIG_DIRECTORS)
  243. catch (Swig::DirectorException &e)
  244. {
  245. SWIG_fail;
  246. }
  247. #endif
  248. catch (std::bad_alloc)
  249. {
  250. SWIG_exception(SWIG_MemoryError, const_cast<char*>("Out of memory error.\n"));
  251. #if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
  252. SWIG_fail;
  253. #endif
  254. }
  255. catch (shogun::ShogunException e)
  256. {
  257. SWIG_exception(SWIG_SystemError, const_cast<char*>(e.get_exception_string()));
  258. #if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
  259. SWIG_fail;
  260. #endif
  261. }
  262. }
  263. %ignore NUM_LOG_LEVELS;
  264. %ignore FBUFSIZE;
  265. /* %ignore init_shogun;
  266. %ignore exit_shogun; */
  267. %ignore sg_print_message;
  268. %ignore sg_print_warning;
  269. %ignore sg_print_error;
  270. %ignore sg_cancel_computations;
  271. %feature("ref") CSGObject "SG_REF($this);"
  272. %feature("unref") CSGObject "SG_UNREF($this);"
  273. %rename(SGObject) CSGObject;
  274. %include <shogun/lib/common.h>
  275. %include "swig_typemaps.i"
  276. #if !defined(SWIGJAVA)
  277. %include "std_vector.i"
  278. namespace std {
  279. %template(IntStdVector) vector<int32_t>;
  280. %template(DoubleStdVector) vector<float64_t>;
  281. }
  282. #endif
  283. #ifndef SWIGR
  284. %include <shogun/base/init.h>
  285. #endif
  286. %include <shogun/io/SGIO.h>
  287. SERIALIZABLE_DUMMY(shogun::SGIO);
  288. %include <shogun/base/SGObject.h>
  289. %include <shogun/base/Version.h>
  290. SERIALIZABLE_DUMMY(shogun::Version);
  291. %include <shogun/base/Parallel.h>
  292. SERIALIZABLE_DUMMY(shogun::Parallel);
  293. #ifdef SWIGPYTHON
  294. namespace shogun
  295. {
  296. %extend CSGObject
  297. {
  298. const char* __str__() const
  299. {
  300. return $self->get_name();
  301. }
  302. const char* __repr__() const
  303. {
  304. return $self->get_name();
  305. }
  306. PyObject* __reduce_ex__(int proto)
  307. {
  308. pickle_ascii= (proto==0) ? 1 : 0;
  309. return NULL;
  310. }
  311. PyObject* __getstate__()
  312. {
  313. char* fname=tmpnam(NULL);
  314. FILE* tmpf=fopen(fname, "w");
  315. CSerializableFile* fstream=NULL;
  316. #ifdef HAVE_HDF5
  317. if (pickle_ascii)
  318. fstream = new CSerializableAsciiFile(fname, 'w');
  319. else
  320. fstream = new CSerializableHdf5File(fname, 'w');
  321. #else
  322. fstream = new CSerializableAsciiFile(fname, 'w');
  323. #endif
  324. $self->save_serializable(fstream);
  325. fstream->close();
  326. delete fstream;
  327. size_t len=0;
  328. char* result=CFile::read_whole_file(fname, len);
  329. unlink(fname);
  330. #ifdef PYTHON3
  331. PyObject* str=PyBytes_FromStringAndSize(result, len);
  332. #else
  333. PyObject* str=PyString_FromStringAndSize(result, len);
  334. #endif
  335. SG_FREE(result);
  336. PyObject* tuple=PyTuple_New(2);
  337. PyTuple_SetItem(tuple, 0, PyBool_FromLong(pickle_ascii));
  338. PyTuple_SetItem(tuple, 1, str);
  339. return tuple;
  340. }
  341. void __setstate__(PyObject* state)
  342. {
  343. PyObject* py_ascii = PyTuple_GetItem(state,0);
  344. pickle_ascii= (py_ascii == Py_True) ? 1 : 0;
  345. PyObject* py_str = PyTuple_GetItem(state,1);
  346. char* str=NULL;
  347. Py_ssize_t len=0;
  348. #ifdef PYTHON3
  349. PyBytes_AsStringAndSize(py_str, &str, &len);
  350. #else
  351. PyString_AsStringAndSize(py_str, &str, &len);
  352. #endif
  353. char* fname=tmpnam(NULL);
  354. FILE* tmpf=fopen(fname, "w");;
  355. size_t total = fwrite(str, (size_t) 1, (size_t) len, tmpf);
  356. fclose(tmpf);
  357. ASSERT(total==len);
  358. CSerializableFile* fstream=NULL;
  359. #ifdef HAVE_HDF5
  360. if (pickle_ascii)
  361. fstream = new CSerializableAsciiFile(fname, 'r');
  362. else
  363. fstream = new CSerializableHdf5File(fname, 'r');
  364. #else
  365. if (!pickle_ascii)
  366. SG_SERROR("File contains an HDF5 stream but " \
  367. "Shogun was not compiled with HDF5" \
  368. " support! - cannot load.");
  369. fstream = new CSerializableAsciiFile(fname, 'r');
  370. #endif
  371. $self->load_serializable(fstream);
  372. fstream->close();
  373. delete fstream;
  374. unlink(fname);
  375. }
  376. /*int getbuffer(PyObject *obj, Py_buffer *view, int flags) { return 0; }*/
  377. }
  378. }
  379. %pythoncode %{
  380. try:
  381. import copy_reg
  382. except ImportError:
  383. import copyreg as copy_reg
  384. def _sg_reconstructor(cls, base, state):
  385. try:
  386. if not isinstance(cls(), SGObject):
  387. return _py_orig_reconstructor(cls, base, state)
  388. except:
  389. return _py_orig_reconstructor(cls, base, state)
  390. if base is object:
  391. obj = cls() #object.__new__(cls)
  392. else:
  393. obj = base.__new__(cls, state)
  394. if base.__init__ != object.__init__:
  395. base.__init__(obj, state)
  396. return obj
  397. def _sg_reduce_ex(self, proto):
  398. try:
  399. if not isinstance(self, SGObject):
  400. return _py_orig_reduce_ex(self, proto)
  401. except:
  402. return _py_orig_reduce_ex(self, proto)
  403. base = object # not really reachable
  404. if base is object:
  405. state = None
  406. else:
  407. if base is self.__class__:
  408. raise TypeError("can't pickle %s objects" % base.__name__)
  409. state = base(self)
  410. args = (self.__class__, base, state)
  411. try:
  412. getstate = self.__getstate__
  413. except AttributeError:
  414. if getattr(self, "__slots__", None):
  415. raise TypeError("a class that defines __slots__ without "
  416. "defining __getstate__ cannot be pickled")
  417. try:
  418. dict = self.__dict__
  419. except AttributeError:
  420. dict = None
  421. else:
  422. dict = getstate()
  423. if dict:
  424. return _sg_reconstructor, args, dict
  425. else:
  426. return _sg_reconstructor, args
  427. _py_orig_reduce_ex=copy_reg._reduce_ex
  428. _py_orig_reconstructor=copy_reg._reconstructor
  429. copy_reg._reduce_ex=_sg_reduce_ex
  430. copy_reg._reconstructor=_sg_reconstructor
  431. %}
  432. #endif /* SWIGPYTHON */