Debian Codegraph @

src/swig/jiplib.i

raw ◀ ▶
1 Debian patch touch this file
1 /**********************************************************************
2 Interface file for SWIG
3 Author(s): [email protected], [email protected]
4 Copyright (C) 2016-2020 European Union (Joint Research Centre)
5
6 This file is part of jiplib.
7
8 jiplib is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 jiplib is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with jiplib. If not, see <https://www.gnu.org/licenses/>.
20 ***********************************************************************/
21 %include <std_string.i>
22 %include <std_vector.i>
23 %include <std_map.i>
24 %include <std_list.i>
25 %include <std_iostream.i>
26 %include <std_shared_ptr.i>
27 %shared_ptr(Jim)
28 /* %shared_ptr(jiplib::Jim) */
29 %shared_ptr(VectorOgr)
30
31 /* http://www.swig.org/Doc1.3/Arguments.html */
32 %include "typemaps.i"
33
34 //catch all exceptions thrown in C++
35 %include "exception.i"
36 %exception {
37 try {
38 $action
39 }
40 catch (const std::string errorString) {
41 PyErr_SetString(PyExc_SystemError,errorString.c_str());
42 SWIG_fail;
43 }
44 }
45
46
47 %define DOCJIPLIB
48 "HELP.MODULE"
49 %enddef
50
51 %module(docstring=DOCJIPLIB) jiplib
52 #pragma SWIG nowarn=303,362,401,467,503,509,
53
54 /* %define DOCJIPLIB */
55 /* "Joint image processing library (jiplib) */
56 /* developed in the framework of the JEODPP of the EO&SS@BD pilot project." */
57 /* %enddef */
58
59
60 /* %feature("autodoc", "2"); */
61
62 //uncomment if documentation is needed (make sure to execute make doc before make!!!)
63 /* %pythoncode %{ */
64 /* %import "jiplib_doc.i" */
65 /* %} */
66
67 /* %module(docstring=DOCJIPLIB) jiplib */
68
69 /* %template(Float64Vector) std::vector<double>; */
70
71 /* %apply int &INOUT{ int &nbin }; */
72 /* %apply double &INOUT{ double &min }; */
73 /* %apply double &INOUT{ double &max }; */
74 /* %apply Float64Vector &INOUT{ std::vector<double>& }; */
75
76 /* to resolve naming conflicts with miallib library: rename(to) from*/
77 %rename(filter2d_erode) filter2d::erode;
78 %rename(filter2d_dilate) filter2d::dilate;
79 %rename(filter2d_shift) filter2d::shift;
80
81 %rename(Jim_createImg) Jim::createImg;
82 %rename(VectorOgr_createVector) VectorOgr::createVector;
83
84 %typemap(in) app::AppFactory& (app::AppFactory tempFactory){
85 if(PyDict_Check($input)){
86 PyObject *pKey, *pValue;
87 Py_ssize_t ppos=0;
88 /* $1=new app::AppFactory(); */
89 $1=&tempFactory;
90 while (PyDict_Next($input, &ppos, &pKey, &pValue)) {
91 std::string theKey;
92 std::string theValue;
•93 if(PyBytes_Check(pKey)){
94 theKey=PyBytes_AsString(pKey);
95 }
96 else if(PyUnicode_Check(pKey)){
•97 theKey=PyBytes_AsString(PyUnicode_AsUTF8String(pKey));
98 }
99 else{
100 PyErr_SetString(PyExc_TypeError,"Expected a string.");
101 std::string errorString="Error: Expected a string.";
102 throw(errorString);
103 return NULL;
104 }
105 if(PyList_Check(pValue)){
106 for(Py_ssize_t i=0;i<PyList_Size(pValue);++i){
107 PyObject *rValue;
108 rValue=PyList_GetItem(pValue,i);
•109 if (PyBytes_Check(rValue))
110 theValue=PyBytes_AsString(rValue);
111 else if (PyUnicode_Check(rValue))
•112 theValue = PyBytes_AsString(PyUnicode_AsUTF8String(rValue));
113 else if(rValue != Py_None){
114 PyObject *tmp_obj = PyObject_Repr(rValue);
•115 if (PyBytes_Check(tmp_obj))
116 theValue=PyBytes_AsString(tmp_obj);
117 else if (PyUnicode_Check(tmp_obj))
•118 theValue=PyBytes_AsString(PyUnicode_AsUTF8String(tmp_obj));
119 }
120 else{
121 PyErr_SetString(PyExc_TypeError,"Expected a string.");
122 return NULL;
123 }
124 $1->pushLongOption(theKey,theValue);
125 }
126 continue;
127 }
•128 else if(PyBytes_Check(pValue)){
129 theValue=PyBytes_AsString(pValue);
130 $1->pushLongOption(theKey,theValue);
131 }
132 else if (PyUnicode_Check(pValue)){
•133 theValue = PyBytes_AsString(PyUnicode_AsUTF8String(pValue));
134 $1->pushLongOption(theKey,theValue);
135 }
136 else if(PyBool_Check(pValue)){
137 if(pValue==Py_True){
138 if(theKey=="help")
139 $1->pushLongOption("dict");
140 else
141 $1->pushLongOption(theKey);
142 }
143 }
144 else if(pValue != Py_None){
145 PyObject *tmp_obj = PyObject_Repr(pValue);
•146 if (PyBytes_Check(tmp_obj))
147 theValue=PyBytes_AsString(tmp_obj);
148 else if (PyUnicode_Check(tmp_obj))
•149 theValue=PyBytes_AsString(PyUnicode_AsUTF8String(tmp_obj));
150 $1->pushLongOption(theKey,theValue);
151 }
152 }
153 }
154 else{
155 PyObject* kwargs;
156 char *theString;
157 char *theOptInt;
158 strcpy(theString, "theString");
159 strcpy(theOptInt, "theOptInt");
160 static char *kwlist[] = {
161 theString,
162 theOptInt,
163 NULL
164 };
165 PyArg_ParseTupleAndKeywords($input,kwargs,"S|i",kwlist);
166 /* SWIG_exception(SWIG_TypeError, "Python dictionary expected"); */
167 }
168 if(!($1))
169 SWIG_exception(SWIG_TypeError, "Error: could not parse argument for " "$symname");
170 //test
171 /* $1->showOptions(); */
172 }
173
174 /* %ignore createJim(); */
175 /* %ignore createJim(const std::shared_ptr<Jim>, bool); */
176 /* %ignore createJim(const std::string&, bool); */
177 %pythoncode %{
178
179 t_UCHAR = 3
180 t_SHORT = 4
181 t_USHORT = 5
182 t_INT32 = 6
183 t_UINT32 = 7
184 t_INT64 = 8
185 t_UINT64 = 9
186 t_FLOAT = 10
187 _MIAFLOAT = 10
188 t_DOUBLE = 11
189 GDT_Byte = 1
190 GDT_UInt16 = 2
191 GDT_Int16 = 3
192 GDT_UInt32 = 4
193 GDT_Int32 = 5
194 GDT_Float32 = 6
195 GDT_Float64 = 7
196 JDT_UInt64 = 24
197 JDT_Int64 = 25
198
199 import os.path
200 def createJim(arg1=None,**kwargs):
201 appDict={}
202 if arg1:
203 if isinstance(arg1,Jim):
204 if 'copyData' in kwargs.keys():
205 if 'Jim_createImg' in globals():
206 return Jim_createImg(arg1,kwargs['copyData'])
207 else:
208 return Jim.Jim_createImg(arg1,kwargs['copyData'])
209 else:
210 if 'Jim_createImg' in globals():
211 return Jim_createImg(arg1)
212 else:
213 return Jim.Jim_createImg(arg1)
214 elif isinstance(arg1,str):
215 if os.path.isfile(arg1):
216 appDict.update({'filename':arg1})
217 else:
218 raise IOError("Error: {} is not a regular file".format(arg1))
219 for key, value in kwargs.items():
220 appDict.update({key:value})
221 if appDict:
222 # SWIG generates wrappers that try to work around calling static member functions, replacing :: with _ (underscore)
223 if 'Jim_createImg' in globals():
224 return Jim_createImg(appDict)
225 else:
226 return Jim.Jim_createImg(appDict)
227 else:
228 if 'Jim_createImg' in globals():
229 return Jim_createImg()
230 else:
231 return Jim.Jim_createImg()
232
233 def createVector(arg1=None,**kwargs):
234 appDict={}
235 for key, value in kwargs.items():
236 appDict.update({key:value})
237 if arg1:
238 if isinstance(arg1,VectorOgr):
239 if appDict:
240 if 'VectorOgr_createVector' in globals():
241 return VectorOgr_createVector(arg1,appDict)
242 else:
243 return VectorOgr.VectorOgr_createVector(arg1,appDict)
244 else:
245 return VectorOgr_createVector(arg1)
246 elif isinstance(arg1,str):
247 if os.path.isfile(arg1):
248 appDict.update({'filename':arg1})
249 else:
250 print("Warning: {} is not a regular file".format(arg1))
251 appDict.update({'filename':arg1})
252 else:
253 raise TypeError("Error: bad argument type for createVector, arguments without names should be a path or of VectorOgr type")
254 if appDict:
255 # SWIG generates wrappers that try to work around calling static member functions, replacing :: with _ (underscore)
256 if 'VectorOgr_createVector' in globals():
257 return VectorOgr_createVector(appDict)
258 else:
259 return VectorOgr.VectorOgr_createVector(appDict)
260 else:
261 if 'VectorOgr_createVector' in globals():
262 return VectorOgr_createVector()
263 else:
264 return VectorOgr.VectorOgr_createVector()
265 %}
266
267 /* !!! from: http://svn.salilab.org/imp/branches/1.0/kernel/pyext/IMP_streams.i */
268 /* to allow overloading and select the appropriate typemap when a Python object is provided */
269 %typemap(typecheck) (app::AppFactory&) = PyObject *;
270 /* %typemap(typecheck) (app::AppFactory&) = PyDict *; */
271
272 /* we provide SWIG with a typecheck to determine which of the C++ functions to use. */
273 /* if Python function argument $input is a PyDict, then use the C++ function with the AppFactory */
274 /* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) so we might want to include a second argument precedence=X after app?*/
275 %typemap(typecheck) (const app::AppFactory& app) {
276 $1 = PyDict_Check($input) ? 1 : 0;
277 }
278
279 %typemap(typecheck) (app::AppFactory& app) {
280 $1 = PyDict_Check($input) ? 1 : 0;
281 }
282
283 /* %typemap(in) const Vector2d<double> &taps */
284 /* { */
285 /* std::cout << "we are in typemap(in) std::vector<double>& for $symname with taps" << std::endl; */
286 /* if ($input != NULL && PyArray_Check($input)) */
287 /* { */
288 /* /\* $1=&tmpTaps; *\/ */
289 /* int nrow=PyArray_DIM((PyArrayObject*)($input),0); */
290 /* int ncol=PyArray_DIM((PyArrayObject*)($input),1); */
291 /* $1->resize(nrow,ncol); */
292 /* for(size_t irow=0;irow<nrow;++irow){ */
293 /* for(size_t icol=0;icol<ncol;++icol){ */
294 /* //todo: check if row and col should be reversed? */
295 /* ($1->at(irow)).at(icol)=*((double*)(PyArray_GETPTR2($input, irow, icol))); */
296 /* } */
297 /* } */
298 /* } */
299 /* else */
300 /* { */
301 /* PyErr_SetString(PyExc_TypeError, "not a numpy array"); */
302 /* SWIG_fail; */
303 /* } */
304 /* } */
305
306 /* https://stackoverflow.com/questions/15185010/how-to-receive-reference-and-pointer-arguments-in-python-swig */
307 %typemap(in,numinputs=0) double& ulx (double temp) "$1 = &temp;"
308 %typemap(in,numinputs=0) double& uly (double temp) "$1 = &temp;"
309 %typemap(in,numinputs=0) double& lrx (double temp) "$1 = &temp;"
310 %typemap(in,numinputs=0) double& lry (double temp) "$1 = &temp;"
311
312 %typemap(argout) double& ulx {
313 %append_output(PyFloat_FromDouble(*$1));
314 }
315
316 %typemap(argout) double& uly {
317 %append_output(PyFloat_FromDouble(*$1));
318 }
319
320 %typemap(argout) double& lrx {
321 %append_output(PyFloat_FromDouble(*$1));
322 }
323
324 %typemap(argout) double& lry {
325 %append_output(PyFloat_FromDouble(*$1));
326 }
327
328 %typemap(in,numinputs=0) double& gt0 (double temp) "$1 = &temp;"
329 %typemap(in,numinputs=0) double& gt1 (double temp) "$1 = &temp;"
330 %typemap(in,numinputs=0) double& gt2 (double temp) "$1 = &temp;"
331 %typemap(in,numinputs=0) double& gt3 (double temp) "$1 = &temp;"
332 %typemap(in,numinputs=0) double& gt4 (double temp) "$1 = &temp;"
333 %typemap(in,numinputs=0) double& gt5 (double temp) "$1 = &temp;"
334
335 %typemap(argout) double& gt0 {
336 %append_output(PyFloat_FromDouble(*$1));
337 }
338
339 %typemap(argout) double& gt1 {
340 %append_output(PyFloat_FromDouble(*$1));
341 }
342
343 %typemap(argout) double& gt2 {
344 %append_output(PyFloat_FromDouble(*$1));
345 }
346
347 %typemap(argout) double& gt3 {
348 %append_output(PyFloat_FromDouble(*$1));
349 }
350
351 %typemap(argout) double& gt4 {
352 %append_output(PyFloat_FromDouble(*$1));
353 }
354
355 %typemap(argout) double& gt5 {
356 %append_output(PyFloat_FromDouble(*$1));
357 }
358
359 %typemap(in,numinputs=0) double& centerX (double temp) "$1 = &temp;"
360 %typemap(in,numinputs=0) double& centerY (double temp) "$1 = &temp;"
361
362 %typemap(argout) double& centerX {
363 %append_output(PyFloat_FromDouble(*$1));
364 }
365
366 %typemap(argout) double& centerY {
367 %append_output(PyFloat_FromDouble(*$1));
368 }
369
370 %typemap(in,numinputs=0) double& refX (double temp) "$1 = &temp;"
371 %typemap(in,numinputs=0) double& refY (double temp) "$1 = &temp;"
372
373 %typemap(argout) double& refX {
374 %append_output(PyFloat_FromDouble(*$1));
375 }
376
377 %typemap(argout) double& refY {
378 %append_output(PyFloat_FromDouble(*$1));
379 }
380
381 /* Set the input argument to point to a temporary variable */
382 /* %typemap(in, numinputs=0) double *gt (double temp) { */
383 /* $1 = &temp; */
384 /* } */
385
386 /* %typemap(argout) double* { */
387 /* // Append output value $1 to $result */
388 /* int n=6; */
389 /* PyObject *pyList; */
390 /* pyList=PyList_New(n); */
391 /* for(int i=0; i<n; ++i){ */
392 /* PyList_SET_ITEM(pyList, i, PyFloat_FromDouble($1[i])); */
393 /* } */
394 /* $result = pyList; */
395 /* } */
396
397 %typemap(in, numinputs=0) double *minval (double temp) {
398 $1 = &temp;
399 }
400
401 %typemap(argout) double* minval {
402 %append_output(PyFloat_FromDouble(*$1));
403 }
404
405 %typemap(in, numinputs=0) double *maxval (double temp) {
406 $1 = &temp;
407 }
408
409 %typemap(argout) double* maxval {
410 %append_output(PyFloat_FromDouble(*$1));
411 }
412
413 %typemap(argout) unsigned long int* ofs{
•414 %append_output(PyLong_FromLong(*$1));
415 }
416
417 %typemap(in) double* gt(double temp[6]){
418 int i;
419 if (!PySequence_Check($input)) {
420 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
421 return NULL;
422 }
423 if (PySequence_Length($input) != 6) {
424 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 6 elements");
425 return NULL;
426 }
427 for (i = 0; i < 6; i++) {
428 PyObject *o = PySequence_GetItem($input,i);
429 if (PyNumber_Check(o)) {
430 temp[i] = PyFloat_AsDouble(o);
431 } else {
432 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
433 return NULL;
434 }
435 }
436 $1 = temp;
437 }
438
439 /* From: http://biomol.bme.utexas.edu/~mh43854/openmm/archive/openmm-master/wrappers/python/src/swig_doxygen/swig_lib/python/typemaps.i */
440 /* The following two typemaps cause a non-const vector<string>& named fields to become a return list of values. */
441
442 %typemap(in, numinputs=0) std::vector<double>& noDataValues (std::vector<double> temp) {
443 $1 = &temp;
444 }
445
446 %typemap(argout) std::vector<double>& noDataValues{
447 int i, n;
448 PyObject *pyList;
449
450 n=(*$1).size();
451 pyList=PyList_New(n);
452 for (i=0; i<n; i++) {
453 double theValue=(*$1).at(i);
454 PyList_SET_ITEM(pyList, i, PyFloat_FromDouble(theValue));
455 }
456 $result = pyList;
457 }
458
459 %typemap(in, numinputs=0) std::vector<std::string>& fields (std::vector<std::string> temp) {
460 $1 = &temp;
461 }
462
463 %typemap(argout) std::vector<std::string>& fields{
464 int i, n;
465 PyObject *pyList;
466
467 n=(*$1).size();
468 pyList=PyList_New(n);
469 for (i=0; i<n; i++) {
470 std::string theField=(*$1).at(i);
•471 PyList_SET_ITEM(pyList, i, PyUnicode_FromString(theField.c_str()));
472 }
473 $result = pyList;
474 }
475
476 %typemap(in, numinputs=0) std::vector<double>& bbvector (std::vector<double> temp) {
477 $1 = &temp;
478 }
479
480 %typemap(argout) std::vector<double>& bbvector{
481 int i, n;
482 PyObject *pyList;
483
484 n=(*$1).size();
485 pyList=PyList_New(n);
486 for (i=0; i<n; i++) {
487 double theValue=(*$1).at(i);
488 PyList_SET_ITEM(pyList, i, PyFloat_FromDouble(theValue));
489 }
490 $result = pyList;
491 }
492
493 /* %typemap(in, numinputs=0) std::vector<double>& field (std::vector<double> temp) { */
494 /* $1 = &temp; */
495 /* } */
496
497 %typemap(in, numinputs=0) (double& i, double& j) (double i, double j){
498 $1 = &i;
499 $2 = &j;
500 }
501
502 %typemap(argout) (double& i, double& j){
503 PyObject *pyList;
504
505 pyList=PyList_New(2);
506 double theValue1=*$1;
507 double theValue2=*$2;
508 PyList_SET_ITEM(pyList, 0, PyFloat_FromDouble(theValue1));
509 PyList_SET_ITEM(pyList, 1, PyFloat_FromDouble(theValue2));
510 $result = pyList;
511 }
512
513 %typemap(in, numinputs=0) (double& x, double& y) (double x, double y){
514 $1 = &x;
515 $2 = &y;
516 }
517
518 %typemap(argout) (double& x, double& y){
519 PyObject *pyList;
520
521 pyList=PyList_New(2);
522 double theValue1=*$1;
523 double theValue2=*$2;
524 PyList_SET_ITEM(pyList, 0, PyFloat_FromDouble(theValue1));
525 PyList_SET_ITEM(pyList, 1, PyFloat_FromDouble(theValue2));
526 $result = pyList;
527 }
528
529 /* %typemap(typecheck) (std::vector<double>&) = PyObject *; */
530 /* %apply std::vector<double> & OUTPUT { std::vector<double>& dVector }; */
531 /* %typemap(argout) const std::vector<double>& dVector ""; */
532 /* %apply const std::vector<double> & { const std::vector<double>& dVector }; */
533
534 //$input is the input Python object
535 //$1 is the (c/c++) function call argument
536 /* %typemap(argout) std::vector<double>& { */
537 /* std::cout << "we are in typemap(argout) std::vector<double>& for $symname" << std::endl; */
538 /* PyObject * o = 0 ; */
539 /* for(int i=0;i<$1->size();++i){ */
540 /* o=PyFloat_FromDouble($1->at(i)); */
541 /* PyList_SetItem($result,i,o); */
542 /* } */
543 /* } */
544
545 //Forgetting to place these commands will show itself as an ugly segmentation fault (crash) as soon as any C-API subroutine is actually called
546 //see also: https://docs.scipy.org/doc/numpy-1.10.0/user/c-info.how-to-extend.html
547 %init %{
548 import_array();
549 %}
550
551 //typemaps for jiplib::Jim
552 ///SWIG applies typemaps in the order in which they are defined in the interface file. This means that typemaps only take effect for declarations that follow the typemap definition
553 ///therefore: define typemaps before including the classes with %include!!! (https://github.com/swig/swig/wiki/FAQ)
554 %{
555 #include <memory>
556 %}
557
558 /* %rename jiplib::Jim::crop jiplib::Jim::geospatial::crop; */
559
560 %{
561 #include <memory>
562 #include <algorithm>
563 #include "imageclasses/Jim.h"
564 #include "imageclasses/JimList.h"
565 /* #include "../../build/src/imageclasses/Jim.h" */
566 /* #include "../../build/src/imageclasses/JimList.h" */
567 /* #include "../../build/src/imageclasses/VectorOgr.h" */
568 #include "apps/AppFactory.h"
569 #include "algorithms/Filter2d.h"
570 #if MIALLIB == 1
571 #include "miallib_swig.h"
572 #include "op.h"
573 #endif
574 #include <cpl_error.h>
575 %}
576
577 /* namespace jiplib{ */
578 /* NPY_INT8, NPY_INT16, NPY_INT32, NPY_INT64, NPY_UINT8, NPY_UINT16, NPY_UINT32, NPY_UINT64, NPY_FLOAT32, NPY_FLOAT64, NPY_COMPLEX64, NPY_COMPLEX128. */
579
580
581 //return the object itself for all functions returning CPLErr
582 %typemap(out) CPLErr {
583 //std::cout << "we are in typemap(out) CPLErr for jiplib::Jim::$symname" << std::endl;
584 if($1==CE_Failure)
585 std::cout << "Warning: CE_Failure in method $symname" << std::endl;
586 void *argp2;
587 int res2=0;
588 res2 = SWIG_ConvertPtr($self, &argp2, SWIGTYPE_p_std__shared_ptrT_Jim_t, 0 | 0);
589 if (!SWIG_IsOK(res2)) {
590 SWIG_exception_fail(SWIG_ArgError(res2), "in method " "$symname");
591 }
592 if (!argp2) {
593 SWIG_exception_fail(SWIG_ValueError, "invalid null reference , argument " "2"" of type '" "shared_ptr<const Jim&>""'");
594 }
595 std::shared_ptr<Jim> result=(*(reinterpret_cast< std::shared_ptr< Jim > * >(argp2)))->getShared();
596 PyObject* o=0;
597 std::shared_ptr< Jim > *smartresult = result ? new std::shared_ptr< Jim >(result) : 0;
598 o = SWIG_NewPointerObj(SWIG_as_voidptr(smartresult), SWIGTYPE_p_std__shared_ptrT_Jim_t, SWIG_POINTER_OWN | 0);
599 if(o)
600 $result=o;
601 else
602 SWIG_exception_fail(SWIG_ArgError(res2), "in method " "$symname");
603 }
604 //return the object itself for all functions returning OGRErr
605 %typemap(out) OGRErr {
606 //std::cout << "we are in typemap(out) OGRErr for jiplib::VectorOgr::$symname" << std::endl;
607 if($1==OGRERR_FAILURE)
608 std::cout << "Warning: OGRERR_FAILURE" << std::endl;
609 void *argp2;
610 int res2=0;
611 res2 = SWIG_ConvertPtr($self, &argp2, SWIGTYPE_p_std__shared_ptrT_VectorOgr_t, 0 | 0);
612 if (!SWIG_IsOK(res2)) {
613 SWIG_exception_fail(SWIG_ArgError(res2), "in method " "$symname");
614 }
615 if (!argp2) {
616 SWIG_exception_fail(SWIG_ValueError, "invalid null reference , argument " "2"" of type '" "shared_ptr<const VectorOgr&>""'");
617 }
618 std::shared_ptr<VectorOgr> result=(*(reinterpret_cast< std::shared_ptr< VectorOgr > * >(argp2)))->getShared();
619 PyObject* o=0;
620 std::shared_ptr< VectorOgr > *smartresult = result ? new std::shared_ptr< VectorOgr >(result) : 0;
621 o = SWIG_NewPointerObj(SWIG_as_voidptr(smartresult), SWIGTYPE_p_std__shared_ptrT_VectorOgr_t, SWIG_POINTER_OWN | 0);
622 if(o)
623 $result=o;
624 else
625 SWIG_exception_fail(SWIG_ArgError(res2), "in method " "$symname");
626 }
627
628 //convert multimap to PyDict
629 %typemap(out) std::multimap<std::string,std::string> getStats {
630 PyObject *d = PyDict_New();
631 std::multimap<std::string,std::string>::const_iterator mit=$1.begin();
632 while(mit!=$1.end()){
633 std::string key=mit->first;
634 std::string val=mit->second;
635 if(key.find("histogram")!=std::string::npos){
636 //for creating PyArrayObject from c array, check https://codereview.stackexchange.com/questions/92266/sending-a-c-array-to-python-numpy-and-back/92353#92353
637 PyObject *lb = PyList_New(0);
638 PyObject *lh = PyList_New(0);
639 //construct dictionary as list of values
640 std::istringstream buf(val);
641 std::istream_iterator<std::string> beg(buf), end;
642 std::vector<std::string> tokens(beg, end); // done!
643 for(int ibin=0;ibin<tokens.size()-1;ibin=ibin+2){
644 double binValue=std::stod(tokens[ibin].c_str());
645 std::string histString=tokens[ibin+1];
646 histString.erase(std::remove(histString.begin(), histString.end(), '\n'), histString.end());
647 double histValue=std::stod(histString.c_str());
648 PyList_Append(lb,PyFloat_FromDouble(binValue));
649 PyList_Append(lh,PyFloat_FromDouble(histValue));
650 }
651 std::string keyBin="bin";
•652 PyDict_SetItem(d, PyUnicode_FromString(keyBin.c_str()), lb);
653 PyDict_SetItem(d, PyUnicode_FromString(key.c_str()), lh);
654 }
655 else if(val.find("[")==std::string::npos)
•656 PyDict_SetItem(d, PyUnicode_FromString(key.c_str()), PyFloat_FromDouble(std::stod(val.c_str())));
657 else{
658 PyObject *lb = PyList_New(0);
659 val.erase(std::remove(val.begin(), val.end(), '['), val.end());
660 val.erase(std::remove(val.begin(), val.end(), ']'), val.end());
661
662 std::stringstream ss(val);
663
664 for (double dv; ss >> dv;) {
665
666 PyList_Append(lb,PyFloat_FromDouble(dv));
667 if (ss.peek() == ',')
668 ss.ignore();
669 }
•670 PyDict_SetItem(d, PyUnicode_FromString(key.c_str()), lb);
671 }
672 ++mit;
673 }
674 $result=d;
675 }
676 /* } */
677
678 /* %typemap(out) std::string getUniquePixels { */
•679 /* $result=PyUnicode_FromString($1.c_str()); */
680 /* } */
681 /* %typemap(out) std::map<std::vector<unsigned short>,unsigned short>& getUniquePixels { */
•682 /* $result=PyUnicode_FromString("hello"); */
683 /* } */
684 /* %typemap(out) std::map<unsigned short,unsigned short> getUniquePixels { */
•685 /* $result=PyUnicode_FromString("hello"); */
686 /* } */
687 /* %typemap(out) std::vector<unsigned short> getUniquePixels { */
•688 /* $result=PyUnicode_FromString("hello"); */
689 /* } */
690 //convert map to PyDict
691 /* %typemap(out) std::map<std::vector<unsigned short>,std::vector<std::pair<unsigned short,unsigned short> > > getUniquePixels { */
692 /* PyObject *d = PyDict_New(); */
693 /* std::map<std::vector<unsigned short>,std::vector<std::pair<unsigned short,unsigned short> > >::const_iterator mit=$1.begin(); */
694 /* while(mit!=$1.end()){ */
695 /* std::vector<unsigned short> pv=mit->first; */
696 /* PyObject *pyv = PyList_New(mit->first.size()); */
697 /* for(int index=0;index<mit->first.size();++index) */
•698 /* PyList_SetItem(pyv, index,PyLong_FromLong(mit->first[index])); */
699 /* PyObject *coordinates = PyList_New(mit->second.size()); */
700 /* //construct dictionary as list of values */
701 /* for(int icoord=0;icoord<mit->second.size();++icoord){ */
702 /* PyObject *lc = PyList_New(2); */
703 /* unsigned int xcoord=mit->second[icoord].first; */
704 /* unsigned int ycoord=mit->second[icoord].second; */
•705 /* PyList_SetItem(lc,0,PyLong_FromLong(xcoord)); */
706 /* PyList_SetItem(lc,1,PyLong_FromLong(ycoord)); */
707 /* PyList_SetItem(coordinates,icoord,lc); */
708 /* } */
709 /* PyDict_SetItem(d, pyv, coordinates); */
710 /* ++mit; */
711 /* } */
712 /* $result=d; */
713 /* } */
714
715
716
717 %template(ImgVectorJim) std::vector< std::shared_ptr< Jim > >;
718 %template(JimListJim) std::list< std::shared_ptr< Jim > >;
719 %template(VectorDouble) std::vector<double>;
720 %template(VectorString) std::vector<std::string>;
721 /* %template(ImgVectorJim) std::vector< std::shared_ptr< jiplib::Jim > >; */
722 /* %template(JimListJim) std::list< std::shared_ptr< jiplib::Jim > >; */
723 /* %template(VectorDouble) std::vector<double>; */
724
725 //Parse the header file
726 %include "swig/miallib_tmp.i"
727
728 %include "op.h"
729 /* %include "swig/jiplib_python.i" */
730
731 %{
732 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
733 #include <limits>
734 #include "Python.h"
735 #include "numpy/arrayobject.h"
736 #include "config_jiplib.h"
737 %}
738
739 %typemap(in,numinputs=1) (PyArrayObject *psArray)
740 {
741 if ($input != NULL && PyArray_Check($input))
742 {
743 $1 = (PyArrayObject*)($input);
744 }
745 else
746 {
747 PyErr_SetString(PyExc_TypeError, "not a numpy array");
748 SWIG_fail;
749 }
750 }
751
752 %inline %{
753 std::shared_ptr<Jim> np2jim(PyObject* npArray) {
754 app::AppFactory afactory;
755 /* jim.np2jim(npArray); */
756 if(PyArray_Check(npArray)){
757 PyArrayObject *obj=(PyArrayObject *)npArray;
758 int typ=PyArray_TYPE((PyArrayObject *)npArray);
759
760 switch(PyArray_TYPE((PyArrayObject*)npArray)){
761 case NPY_UINT8:
762 afactory.pushLongOption("otype","GDT_Byte");
763 break;
764 case NPY_UINT16:
765 afactory.pushLongOption("otype","GDT_UInt16");
766 break;
767 case NPY_INT16:
768 afactory.pushLongOption("otype","GDT_Int16");
769 break;
770 case NPY_UINT32:
771 afactory.pushLongOption("otype","GDT_UInt32");
772 break;
773 case NPY_INT32:
774 afactory.pushLongOption("otype","GDT_Int32");
775 break;
776 case NPY_FLOAT32:
777 afactory.pushLongOption("otype","GDT_Float32");
778 break;
779 case NPY_FLOAT64:
780 afactory.pushLongOption("otype","GDT_Float64");
781 break;
782 case NPY_UINT64:
783 afactory.pushLongOption("otype","JDT_UInt64");
784 break;
785 case NPY_INT64:
786 afactory.pushLongOption("otype","JDT_Int64");
787 break;
788 default:
789 std::string errorString="Error: Unknown data type";
790 throw(errorString);
791 }
792 int ndim=(PyArray_NDIM((PyArrayObject*)npArray)==3)? 3 : 2;
793 int nplane=(PyArray_NDIM((PyArrayObject*)npArray)==3) ? PyArray_DIM((PyArrayObject*)npArray,0): 1;
794 int nrow=(PyArray_NDIM((PyArrayObject*)npArray)==3) ? PyArray_DIM((PyArrayObject*)npArray,1): PyArray_DIM((PyArrayObject*)npArray,0);
795 int ncol=(PyArray_NDIM((PyArrayObject*)npArray)==3) ? PyArray_DIM((PyArrayObject*)npArray,2): PyArray_DIM((PyArrayObject*)npArray,1);
796 /* int nrow=PyArray_DIM((PyArrayObject*)npArray,1); */
797 /* int ncol=PyArray_DIM((PyArrayObject*)npArray,2); */
798 int nband=1;//only single band supported for now
799 afactory.pushLongOption("ncol",ncol);
800 afactory.pushLongOption("nrow",nrow);
801 afactory.pushLongOption("nplane",nplane);
802 afactory.pushLongOption("nband",nband);
803 std::shared_ptr<Jim> jim=Jim::createImg();
804 jim->open(afactory);
805 memcpy(jim->getDataPointer(),(void*)(PyArray_DATA((PyArrayObject*)npArray)),jim->getDataTypeSizeBytes()*jim->nrOfCol()*jim->nrOfRow()*jim->nrOfPlane());
806 return(jim);
807 /* return(jim->getShared()); */
808 }
809 else{
810 std::cerr << "Error: expected a numpy array as input, returning empty Jim image" << std::endl;
811 /* return create; */
812 return 0;
813 }
814 }
815
816 //todo: return multi-plane/band images according to: http://scikit-image.org/docs/dev/user_guide/numpy_images.html
817 PyObject* jim2np(std::shared_ptr<Jim> aJim, size_t band=0, bool copyData=true) {
818 if(band>=aJim->nrOfBand()){
819 std::string errorString="Error: band out of range";
820 throw(errorString);
821 }
822 int npDataType;
823 switch (aJim->getDataType()){
824 case GDT_Byte:
825 npDataType=NPY_UINT8;
826 break;
827 case GDT_UInt16:
828 npDataType=NPY_UINT16;
829 break;
830 case GDT_Int16:
831 npDataType=NPY_INT16;
832 break;
833 case GDT_UInt32:
834 npDataType=NPY_UINT32;
835 break;
836 case GDT_Int32:
837 npDataType=NPY_INT32;
838 break;
839 case GDT_Float32:
840 npDataType=NPY_FLOAT32;
841 break;
842 case GDT_Float64:
843 npDataType=NPY_FLOAT64;
844 break;
845 case JDT_UInt64:
846 npDataType=NPY_UINT64;
847 break;
848 case JDT_Int64:
849 npDataType=NPY_INT64;
850 break;
851 case GDT_Unknown:
852 default:
853 std::string errorString="Error: Unknown data type";
854 throw(errorString);
855 }
856 void *npdata=0;
857 if(copyData){
858 //alllocate memory for npdata
859 npdata=(void *) calloc(static_cast<size_t>(aJim->nrOfPlane()*aJim->nrOfCol()*aJim->nrOfRow()),aJim->getDataTypeSizeBytes());
860 //copy data from jim to npdata
861 aJim->copyData(npdata,band);
862 }
863 else
864 npdata=(void*)(aJim->getDataPointer(band));
865 int ndim=(aJim->nrOfPlane()>1)? 3 : 2;
866 if(aJim->nrOfPlane()>1){
867 npy_intp dims[3];
868 dims[0]=aJim->nrOfPlane();
869 dims[1]=aJim->nrOfRow();
870 dims[2]=aJim->nrOfCol();
871 PyArrayObject *npArray=(PyArrayObject*)PyArray_SimpleNewFromData(ndim,dims,npDataType,npdata);
872 if(npArray)
873 return(PyArray_Return(npArray));
874 else
875 return(0);
876 }
877 else{
878 npy_intp dims[2];
879 dims[0]=aJim->nrOfRow();
880 dims[1]=aJim->nrOfCol();
881 PyArrayObject *npArray=(PyArrayObject*)PyArray_SimpleNewFromData(ndim,dims,npDataType,npdata);
882 if(npArray)
883 return(PyArray_Return(npArray));
884 else
885 return(0);
886 }
887 }
888
889 PyObject* jimvect2np(std::shared_ptr<VectorOgr> aJimVect, std::vector<std::string> fname, size_t ilayer) {
890 size_t ntotalfeatures=0;
891 size_t nfeatures=0;
892 size_t nfields=0;
893 int npDataType=NPY_FLOAT64;
894 if(aJimVect->isEmpty())
895 return(0);
896 if(ilayer>=aJimVect->getLayerCount())
897 return(0);
898 //todo: destroy empty features?
899
900 ntotalfeatures=aJimVect->getFeatureCount(ilayer);
901 std::vector<OGRFieldDefn*> fields;
902 std::vector<size_t> fieldindexes;
903 aJimVect->getFields(fields,ilayer);
904 for(unsigned int ifield=0;ifield<fields.size();++ifield){
905 if(fname.size()){
906 if(std::find(fname.begin(),fname.end(),fields[ifield]->GetNameRef())!=fname.end())
907 fieldindexes.push_back(ifield);
908 }
909 else
910 fieldindexes.push_back(ifield);
911 }
912 nfields=fieldindexes.size();
913 int ndim=2;
914 npy_intp dims[2]{static_cast<int>(ntotalfeatures),static_cast<int>(nfields)};
915 PyArrayObject *npArray =(PyArrayObject*) PyArray_SimpleNew(ndim, dims, npDataType);
916 double *ad = (double *) PyArray_DATA((PyArrayObject *) npArray);
917 OGRFeatureDefn *poFDefn = aJimVect->getLayer(ilayer)->GetLayerDefn();
918 for(size_t ifeature = 0; ifeature < aJimVect->getFeatureCount(ilayer); ++ifeature) {
919 OGRFeature *thisFeature=aJimVect->getFeatureRef(ifeature,ilayer);
920 if(!thisFeature){
921 // std::cerr << "Warning: " << ifeature << " is NULL" << std::endl;
922 continue;
923 }
924 for(std::vector<size_t>::const_iterator fit=fieldindexes.begin();fit!=fieldindexes.end();++fit)
925 *ad++=thisFeature->GetFieldAsDouble(*fit);
926 }
927 if(npArray){
928 return(PyArray_Return(npArray));
929 }
930 else{
931 return(0);
932 }
933 }
934
935 PyObject* dict(std::shared_ptr<VectorOgr> aJimVect, std::vector<std::string> fname, size_t ilayer) {
936 size_t ntotalfeatures=0;
937 size_t nfeatures=0;
938 size_t nfields=0;
939 int npDataType=NPY_FLOAT64;
940 if(aJimVect->isEmpty())
941 return(0);
942 if(ilayer>=aJimVect->getLayerCount())
943 return(0);
944 //todo: destroy empty features?
945
946 ntotalfeatures=aJimVect->getFeatureCount(ilayer);
947 std::vector<OGRFieldDefn*> fields;
948 std::vector<size_t> fieldindexes;
949 aJimVect->getFields(fields,ilayer);
950 std::vector<PyObject*> pyListVector;
951 for(unsigned int ifield=0;ifield<fields.size();++ifield){
952 if(fname.size()){
953 if(std::find(fname.begin(),fname.end(),fields[ifield]->GetNameRef())==fname.end())
954 continue;
955 }
956 fieldindexes.push_back(ifield);
957 pyListVector.push_back(PyList_New(ntotalfeatures));
958 }
959 nfields=fieldindexes.size();
960
961 size_t ifield=0;
962 for(size_t ifeature = 0; ifeature < ntotalfeatures; ++ifeature) {
963 OGRFeature *thisFeature=aJimVect->getFeatureRef(ifeature,ilayer);
964 if(!thisFeature){
965 // std::cerr << "Warning: " << ifeature << " is NULL" << std::endl;
966 continue;
967 }
968 ifield=0;
969 for(std::vector<size_t>::const_iterator fit=fieldindexes.begin();fit!=fieldindexes.end();++fit){
970 //get field type
971 switch(fields[*fit]->GetType()){
972 case(OFTReal):
973 PyList_SET_ITEM(pyListVector[ifield], ifeature, PyFloat_FromDouble(thisFeature->GetFieldAsDouble(*fit)));
974 break;
975 case(OFTString):
•976 PyList_SET_ITEM(pyListVector[ifield], ifeature, PyUnicode_FromString(thisFeature->GetFieldAsString(*fit)));
977 break;
978 case(OFTInteger):
979 case(OFTInteger64):
980 PyList_SET_ITEM(pyListVector[ifield], ifeature, PyLong_FromLong(thisFeature->GetFieldAsInteger64(*fit)));
981 break;
982 case(OFTBinary):
983 case(OFTTime):
984 case(OFTDateTime):
985 case(OFTWideString):
986 case(OFTDate):
987 case(OFTRealList):
988 case(OFTIntegerList):
989 case(OFTStringList):
990 case(OFTWideStringList):
991 case(OFTInteger64List):
992 default:{
993 std::ostringstream errorStringStream;
994 std::string ftypename = OGRFieldDefn::GetFieldTypeName(fields[*fit]->GetType());
995 errorStringStream << "Error: field type " << ftypename << " not supported";
996 throw(errorStringStream.str());
997 break;
998 }
999 }
1000 ++ifield;
1001 }
1002 }
1003
1004 ifield=0;
1005 PyObject *returnDict = PyDict_New();
1006 for(std::vector<size_t>::const_iterator fit=fieldindexes.begin();fit!=fieldindexes.end();++fit){
1007 std::string key = fields[*fit]->GetNameRef();
•1008 PyDict_SetItem(returnDict, PyUnicode_FromString(key.c_str()), pyListVector[ifield]);
1009 ++ifield;
1010 }
1011 if(returnDict)
1012 return returnDict;
1013 else
1014 return(0);
1015 }
1016
1017 %}
1018
1019 %include "imageclasses/Jim.h"
1020 %include "imageclasses/JimList.h"
1021 %include "imageclasses/VectorOgr.h"
1022 %include "apps/AppFactory.h"
1023 %include "algorithms/Filter2d.h"
1024 enum CPLErr {CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4};
1025 enum GDALDataType {GDT_Unknown = 0, GDT_Byte = 1, GDT_UInt16 = 2, GDT_Int16 = 3, GDT_UInt32 = 4, GDT_Int32 = 5, GDT_Float32 = 6, GDT_Float64 = 7, GDT_CInt16 = 8, GDT_CInt32 = 9, GDT_CFloat32 = 10, GDT_CFloat64 = 11, GDT_TypeCount = 12};