-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
SGBase.i
527 lines (454 loc) · 14.3 KB
/
SGBase.i
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/* base includes required by any module */
%include "stdint.i"
%include "std_string.i"
%include "exception.i"
%feature("ref") shogun::CSGObject "SG_REF($this);"
%feature("unref") shogun::CSGObject "SG_UNREF($this);"
#ifdef SWIGJAVA
%typemap(javainterfaces) shogun::CSGObject "java.io.Externalizable"
%typemap(javaimports) shogun::CSGObject
%{
import org.shogun.SerializableFile;
import org.shogun.SerializableAsciiFile;
%}
%typemap(javacode) shogun::CSGObject
%{
public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException {
java.util.Random randomGenerator = new java.util.Random();
String tmpFileName = System.getProperty("java.io.tmpdir") + "/" + randomGenerator.nextInt() + "shogun.tmp";
java.io.File file = null;
java.io.FileInputStream in = null;
int ch;
try {
file = new java.io.File(tmpFileName);
file.createNewFile();
SerializableAsciiFile tmpFile = new SerializableAsciiFile(tmpFileName, 'w');
this.save_serializable(tmpFile);
tmpFile.close();
in = new java.io.FileInputStream(file);
// TODO bufferize
while((ch=in.read()) != -1) {
out.write(ch);
}
file.delete();
} catch (java.io.IOException ex) {
} finally {
try {
in.close();
} catch (java.io.IOException ex) {
}
}
}
public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException {
java.util.Random randomGenerator = new java.util.Random();
String tmpFileName = System.getProperty("java.io.tmpdir") + "/" + randomGenerator.nextInt() + "shogun.tmp";
java.io.File file = null;
java.io.FileOutputStream out = null;
int ch;
try {
file = new java.io.File(tmpFileName);
file.createNewFile();
out = new java.io.FileOutputStream(file);
while ((ch=in.read()) != -1) {
out.write(ch);
}
out.close();
SerializableAsciiFile tmpFile = new SerializableAsciiFile(tmpFileName,'r');
this.load_serializable(tmpFile);
tmpFile.close();
file.delete();
} catch (java.io.IOException ex) {
} finally {
try {
out.close();
} catch (java.io.IOException ex) {
}
}
}
%}
#endif
%{
#ifdef SWIGRUBY
extern "C" {
#include <ruby.h>
#include <narray.h>
#include <stdlib.h>
#include <stdio.h>
}
VALUE (*na_to_array_dl)(VALUE);
VALUE (*na_to_narray_dl)(VALUE);
VALUE cNArray;
#include <dlfcn.h>
#endif
#if defined(SWIGPERL) && defined(HAVE_PDL)
#ifdef __cplusplus
extern "C" {
#endif
#include <pdlcore.h>
#include <ppport.h>
#ifdef __cplusplus
}
#endif
#endif
/* required for python */
#define SWIG_FILE_WITH_INIT
#include <shogun/base/init.h>
#include <shogun/lib/common.h>
#include <shogun/io/SGIO.h>
#include <shogun/lib/ShogunException.h>
#include <shogun/lib/DataType.h>
#include <shogun/base/Version.h>
#include <shogun/base/Parallel.h>
#include <shogun/base/SGObject.h>
extern void sg_global_print_message(FILE* target, const char* str);
extern void sg_global_print_warning(FILE* target, const char* str);
extern void sg_global_print_error(FILE* target, const char* str);
#ifdef SWIGR
#include <Rdefines.h>
#endif
#ifdef SWIGPYTHON
#include <shogun/io/SerializableFile.h>
#include <shogun/io/SerializableAsciiFile.h>
#include <shogun/io/SerializableHdf5File.h>
static int pickle_ascii;
#endif
using namespace shogun;
%}
#if defined (SWIGPERL) && defined(HAVE_PDL)
%header %{
SV* CoreSV;
Core* PDL;
%}
#endif
%init %{
#if defined (SWIGPERL) && defined(HAVE_PDL)
//check Core.xs //Core* PDL_p = pdl__Core_get_Core();
//PDL_COMMENT("Get pointer to structure of core shared C routines")
//PDL_COMMENT("make sure PDL::Core is loaded")
perl_require_pv("PDL::Core");
CoreSV = perl_get_sv("PDL::SHARE",FALSE);
// PDL_COMMENT("SV* value")
if (CoreSV == NULL)
Perl_croak(aTHX_ "Can't load PDL::Core module");
PDL = INT2PTR(Core*, SvIV( CoreSV ));
// PDL_COMMENT("Core* value")
#endif
#ifdef SWIGPYTHON
import_array();
#endif
#if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
#ifndef DISABLE_CANCEL_CALLBACK
shogun::init_shogun(&sg_global_print_message, &sg_global_print_warning,
&sg_global_print_error);
#else
shogun::init_shogun(&sg_global_print_message, &sg_global_print_warning,
&sg_global_print_error);
#endif
#endif
#ifdef SWIGRUBY
rb_require("narray");
cNArray = rb_const_get(rb_cObject, rb_intern("NArray"));
char* error=NULL;
void* handle = dlopen(NARRAY_LIB, RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
*(void **) (&na_to_array_dl) = dlsym(handle, "na_to_array");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "na_to_array %s\n", error);
exit(EXIT_FAILURE);
}
/*if (cNArray==0)
{
void (*Init_narray)();
*(void **) (&Init_narray) = dlsym(handle, "Init_narray");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "Init_narray %s\n", error);
exit(EXIT_FAILURE);
}
fprintf(stderr, "initing narray\n");
(*Init_narray)();
}*/
*(void **) (&na_to_narray_dl) = dlsym(handle, "na_to_narray");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "na_to_narray %s\n", error);
exit(EXIT_FAILURE);
}
/* cNArray = (*(VALUE*)(dlsym(handle, "cNArray")));
if ((error = dlerror()) != NULL) {
fprintf(stderr, "cNArray %s\n", error);
exit(EXIT_FAILURE);
}*/
#endif
%}
#ifdef SWIGPYTHON
%{
static int print_sgobject(PyObject *pyobj, FILE *f, int flags) {
void *argp;
int res;
res = SWIG_ConvertPtr(pyobj, &argp, SWIGTYPE_p_shogun__CSGObject, 0);
if (!SWIG_IsOK(res)) {
SWIG_Error(SWIG_ArgError(res), "in method 'CSGObject::tp_print', argument 1 of type 'CSGObject *'");
return SWIG_ERROR;
}
CSGObject *obj = reinterpret_cast<CSGObject*>(argp);
fprintf(f, "%s", obj->get_name());
return 0;
}
%}
%typemap(out) PyObject* __reduce_ex__(int proto)
{
return PyObject_CallMethod(self, (char*) "__reduce__", (char*) "");
}
%typemap(in) __setstate__(PyObject* state) {
$1 = $input;
}
%typemap(out) PyObject* __getstate__()
{
$result=$1;
}
#elif defined(SWIGPERL)
%{
static int print_sgobject(SV* pobj, FILE *f, int flags) {
void *argp;
int res;
res = SWIG_ConvertPtr(pobj, &argp, SWIGTYPE_p_shogun__CSGObject, 0);
if (!SWIG_IsOK(res)) {
SWIG_Error(SWIG_ArgError(res), "in method 'CSGObject::tp_print', argument 1 of type 'CSGObject *'");
return SWIG_ERROR;
}
CSGObject *obj = reinterpret_cast<CSGObject*>(argp);
fprintf(f, "%s", obj->get_name());
return 0;
}
%}
#endif
%exception
{
try
{
$action
}
#if defined(SWIGPYTHON) && defined(USE_SWIG_DIRECTORS)
catch (Swig::DirectorException &e)
{
SWIG_fail;
}
#endif
catch (std::bad_alloc)
{
SWIG_exception(SWIG_MemoryError, const_cast<char*>("Out of memory error.\n"));
#if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
SWIG_fail;
#endif
}
catch (shogun::ShogunException e)
{
SWIG_exception(SWIG_SystemError, const_cast<char*>(e.get_exception_string()));
#if !defined(SWIGJAVA) && !defined(SWIGCSHARP)
SWIG_fail;
#endif
}
}
%ignore NUM_LOG_LEVELS;
%ignore FBUFSIZE;
/* %ignore init_shogun;
%ignore exit_shogun; */
%ignore sg_print_message;
%ignore sg_print_warning;
%ignore sg_print_error;
%ignore sg_cancel_computations;
%rename(SGObject) CSGObject;
%include <shogun/lib/common.h>
%include "swig_typemaps.i"
#if !defined(SWIGJAVA)
%include "std_vector.i"
namespace std {
%template(IntStdVector) vector<int32_t>;
%template(DoubleStdVector) vector<float64_t>;
}
#endif
#ifndef SWIGR
%include <shogun/base/init.h>
#endif
%include <shogun/base/SGObject.h>
%include <shogun/io/SGIO.h>
%include <shogun/base/Version.h>
%include <shogun/base/Parallel.h>
#ifdef SWIGPYTHON
namespace shogun
{
%extend CSGObject
{
const char* __str__() const
{
return $self->get_name();
}
const char* __repr__() const
{
return $self->get_name();
}
PyObject* __reduce_ex__(int proto)
{
pickle_ascii = (proto==0) ? 1 : 0;
Py_RETURN_NONE;
}
PyObject* __getstate__()
{
char* fname=tmpnam(NULL);
FILE* tmpf=fopen(fname, "w");
CSerializableFile* fstream=NULL;
#ifdef HAVE_HDF5
if (pickle_ascii)
fstream = new CSerializableAsciiFile(fname, 'w');
else
fstream = new CSerializableHdf5File(fname, 'w');
#else
fstream = new CSerializableAsciiFile(fname, 'w');
#endif
$self->save_serializable(fstream);
fstream->close();
delete fstream;
size_t len=0;
char* result=CFile::read_whole_file(fname, len);
unlink(fname);
#ifdef PYTHON3
PyObject* str=PyBytes_FromStringAndSize(result, len);
#else
PyObject* str=PyString_FromStringAndSize(result, len);
#endif
SG_FREE(result);
PyObject* tuple=PyTuple_New(2);
PyTuple_SetItem(tuple, 0, PyBool_FromLong(pickle_ascii));
PyTuple_SetItem(tuple, 1, str);
return tuple;
}
void __setstate__(PyObject* state)
{
PyObject* py_ascii = PyTuple_GetItem(state,0);
pickle_ascii= (py_ascii == Py_True) ? 1 : 0;
PyObject* py_str = PyTuple_GetItem(state,1);
char* str=NULL;
Py_ssize_t len=0;
#ifdef PYTHON3
PyBytes_AsStringAndSize(py_str, &str, &len);
#else
PyString_AsStringAndSize(py_str, &str, &len);
#endif
char* fname=tmpnam(NULL);
FILE* tmpf=fopen(fname, "w");;
size_t total = fwrite(str, (size_t) 1, (size_t) len, tmpf);
fclose(tmpf);
ASSERT(total==len);
CSerializableFile* fstream=NULL;
#ifdef HAVE_HDF5
if (pickle_ascii)
fstream = new CSerializableAsciiFile(fname, 'r');
else
{
try
{
fstream = new CSerializableHdf5File(fname, 'r');
}
catch (ShogunException& e)
{
fstream = new CSerializableAsciiFile(fname, 'r');
}
}
#else
try
{
fstream = new CSerializableAsciiFile(fname, 'r');
}
catch (ShogunException& e)
{
SG_SERROR("File contains an HDF5 stream but " \
"Shogun was not compiled with HDF5" \
" support! - cannot load file %s." \
" (exception was %s)", e.get_exception_string());
}
#endif
$self->load_serializable(fstream);
fstream->close();
delete fstream;
unlink(fname);
}
/*int getbuffer(PyObject *obj, Py_buffer *view, int flags) { return 0; }*/
}
}
%pythoncode %{
try:
import copy_reg
except ImportError:
import copyreg as copy_reg
def _sg_reconstructor(cls, base, state):
try:
if isinstance(cls, str) and cls.startswith('shogun.'):
if base is object:
import shogun
return eval(cls+'()')
else:
base.__new__(cls, state)
if base.__init__ != object.__init__:
base.__init__(obj, state)
return obj
if isinstance(cls(), SGObject):
if base is object:
obj = cls()
else:
obj = base.__new__(cls, state)
if base.__init__ != object.__init__:
base.__init__(obj, state)
return obj
return _py_orig_reconstructor(cls, base, state)
except:
return _py_orig_reconstructor(cls, base, state)
def _sg_reduce_ex(self, proto):
try:
if not isinstance(self, SGObject):
return _py_orig_reduce_ex(self, proto)
except:
return _py_orig_reduce_ex(self, proto)
base = object
state = None
args = ('shogun.' + self.get_name(), base, state)
try:
getstate = self.__getstate__
except AttributeError:
if getattr(self, "__slots__", None):
raise TypeError("a class that defines __slots__ without "
"defining __getstate__ cannot be pickled")
try:
dict = self.__dict__
except AttributeError:
dict = None
else:
dict = getstate()
if dict:
return _sg_reconstructor, args, dict
else:
return _sg_reconstructor, args
_py_orig_reduce_ex=copy_reg._reduce_ex
_py_orig_reconstructor=copy_reg._reconstructor
copy_reg._reduce_ex=_sg_reduce_ex
copy_reg._reconstructor=_sg_reconstructor
%}
#endif /* SWIGPYTHON */
%include <shogun/lib/basetag.h>
%include <shogun/lib/tag.h>
%include <shogun/lib/ShogunException.h>
%include <shogun/base/SGObject.h>
%define SUPPORT_TAG(camel_type, short_type, type)
%template(Tag ## camel_type) shogun::Tag<type>;
%template(put) shogun::CSGObject::put<type>;
%template(put) shogun::CSGObject::put<type, void>;
%template(put) shogun::CSGObject::put<type>;
%template(get_ ## short_type) shogun::CSGObject::get<type, void>;
%template(has) shogun::CSGObject::has<type>;
%template(has_ ## short_type) shogun::CSGObject::has<type, void>;
%enddef
SUPPORT_TAG(String, string, std::string)
SUPPORT_TAG(Float64, float, float64_t)
SUPPORT_TAG(Int64, int, int64_t)