/usr/include/openturns/PythonWrappingFunctions.hxx is in libopenturns-dev 1.7-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 | // -*- C++ -*-
/**
* @brief This file provides functions to ease Python wrapping
*
* Copyright 2005-2015 Airbus-EDF-IMACS-Phimeca
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef OPENTURNS_PYTHONWRAPPINGFUNCTIONS_HXX
#define OPENTURNS_PYTHONWRAPPINGFUNCTIONS_HXX
#include <Python.h>
#include "OT.hxx"
BEGIN_NAMESPACE_OPENTURNS
/** Scoped PyObject pointer: automatically triggers garbage collection */
class ScopedPyObjectPointer
{
public:
explicit ScopedPyObjectPointer( PyObject * pyObj = 0 )
: pyObj_(pyObj)
{
}
~ScopedPyObjectPointer()
{
Py_XDECREF( pyObj_ );
}
ScopedPyObjectPointer & operator=(PyObject * pyObj)
{
Py_XDECREF( pyObj_ );
pyObj_ = pyObj;
return *this;
}
PyObject & operator*() const
{
return *pyObj_;
}
PyObject * get() const
{
return pyObj_;
}
bool isNull()
{
return !pyObj_;
}
private:
PyObject* pyObj_;
};
/** These templates are just declared, not defined. Only specializations are. */
template <class CPP_Type> struct traitsPythonType;
template <class PYTHON_Type> static inline int isAPython(PyObject * pyObj);
template <class PYTHON_Type> static inline const char * namePython();
template <class PYTHON_Type, class CPP_Type> static inline CPP_Type convert(PyObject * pyObj);
template <class CPP_Type, class PYTHON_Type> static inline PyObject * convert(CPP_Type);
template <class PYTHON_Type, class CPP_Type> static inline bool canConvert(PyObject * pyObj);
template <class PYTHON_Type> static inline void check(PyObject * pyObj);
template <class PYTHON_Type, class CPP_Type> static inline CPP_Type checkAndConvert(PyObject * pyObj);
template <class T> static inline T * buildObjectFromPySequence(PyObject * pyObj);
/** Specializations */
/* PyObject */
struct _PyObject_ {};
template <>
inline
int
isAPython<_PyObject_>(PyObject * pyObj)
{
return 1;
}
template <>
inline
const char *
namePython<_PyObject_>()
{
return "object";
}
/* PyBool */
struct _PyBool_ {};
template <>
inline
int
isAPython<_PyBool_>(PyObject * pyObj)
{
return PyBool_Check(pyObj);
}
template <>
inline
const char *
namePython<_PyBool_>()
{
return "bool";
}
template <>
struct traitsPythonType<Bool>
{
typedef _PyBool_ Type;
};
template <>
inline
Bool
convert< _PyBool_, Bool >(PyObject * pyObj)
{
return pyObj == Py_True;
}
template <>
inline
PyObject *
convert< Bool, _PyBool_ >(Bool inB)
{
return PyBool_FromLong(inB ? 1 : 0);
}
/* PyInt */
struct _PyInt_ {};
template <>
inline
int
isAPython< _PyInt_ >(PyObject * pyObj)
{
// PyInt type is deprecated
#if PY_MAJOR_VERSION >= 3
return PyLong_Check(pyObj);
#else
return PyInt_Check(pyObj) || PyLong_Check(pyObj);
#endif
}
template <>
inline
const char *
namePython< _PyInt_ >()
{
return "integer";
}
template <>
struct traitsPythonType< UnsignedInteger >
{
typedef _PyInt_ Type;
};
template <>
inline
bool
canConvert< _PyInt_, UnsignedInteger >(PyObject * pyObj)
{
return true;
}
template <>
inline
UnsignedInteger
convert< _PyInt_, UnsignedInteger >(PyObject * pyObj)
{
return PyLong_AsUnsignedLong(pyObj);
}
template <>
inline
PyObject *
convert< UnsignedInteger, _PyInt_ >(UnsignedInteger n)
{
return PyLong_FromUnsignedLong(n);
}
/* PyFloat */
struct _PyFloat_ {};
template <>
inline
int
isAPython< _PyFloat_ >(PyObject * pyObj)
{
// check also against sequence protocol as numpy array complies to several protocols
return PyNumber_Check(pyObj) && !PyComplex_Check(pyObj) && !PySequence_Check(pyObj);
}
template <>
inline
const char *
namePython<_PyFloat_>()
{
return "double";
}
template <>
struct traitsPythonType< NumericalScalar >
{
typedef _PyFloat_ Type;
};
template <>
inline
NumericalScalar
convert< _PyFloat_, NumericalScalar >(PyObject * pyObj)
{
return PyFloat_AsDouble(pyObj);
}
template <>
inline
PyObject *
convert< NumericalScalar, _PyFloat_ >(NumericalScalar x)
{
return PyFloat_FromDouble(x);
}
/* PyComplex */
struct _PyComplex_ {};
template <>
inline
int
isAPython<_PyComplex_>(PyObject * pyObj)
{
return PyNumber_Check(pyObj);
}
template <>
inline
const char *
namePython<_PyComplex_>()
{
return "complex";
}
template <>
struct traitsPythonType< NumericalComplex >
{
typedef _PyComplex_ Type;
};
template <>
inline
NumericalComplex
convert< _PyComplex_, NumericalComplex >(PyObject * pyObj)
{
return NumericalComplex(PyComplex_RealAsDouble(pyObj), PyComplex_ImagAsDouble(pyObj));
}
template <>
inline
PyObject *
convert< NumericalComplex, _PyComplex_ >(NumericalComplex x)
{
return PyComplex_FromDoubles(x.real(), x.imag());
}
/* PyBytes */
struct _PyBytes_ {};
template <>
inline
int
isAPython< _PyBytes_ >(PyObject * pyObj)
{
#if PY_MAJOR_VERSION >= 3
return PyBytes_Check(pyObj);
#else
return PyString_Check(pyObj);
#endif
}
template <>
inline
const char *
namePython< _PyBytes_ >()
{
return "bytes";
}
template <>
inline
String
convert< _PyBytes_, String >(PyObject * pyObj)
{
#if PY_MAJOR_VERSION >= 3
return PyBytes_AsString(pyObj);
#else
return PyString_AsString(pyObj);
#endif
}
template <>
inline
PyObject *
convert< String, _PyBytes_ >( String s )
{
#if PY_MAJOR_VERSION >= 3
return PyBytes_FromString(s.data());
#else
return PyString_FromString(s.data());
#endif
}
/* PyUnicode */
struct _PyUnicode_ {};
template <>
inline
int
isAPython< _PyUnicode_ >(PyObject * pyObj)
{
return PyUnicode_Check(pyObj);
}
template <>
inline
const char *
namePython< _PyUnicode_ >()
{
return "unicode";
}
template <>
inline
String
convert< _PyUnicode_, String >(PyObject * pyObj)
{
ScopedPyObjectPointer encodedBytes(PyUnicode_AsUTF8String(pyObj));
assert(encodedBytes.get());
return convert<_PyBytes_, String>(encodedBytes.get());
}
template <>
inline
PyObject *
convert< String, _PyUnicode_ >(String s)
{
return PyUnicode_FromString(s.data());
}
/* PyString */
struct _PyString_ {};
template <>
inline
int
isAPython< _PyString_ >(PyObject * pyObj)
{
#if PY_MAJOR_VERSION >= 3
return PyUnicode_Check(pyObj);
#else
return PyString_Check(pyObj) || PyUnicode_Check(pyObj);
#endif
}
template <>
inline
const char *
namePython<_PyString_>()
{
return "string";
}
template <>
struct traitsPythonType< String >
{
typedef _PyString_ Type;
};
template <>
inline
String
convert< _PyString_, String >(PyObject * pyObj)
{
String result;
#if PY_MAJOR_VERSION >= 3
result = convert< _PyUnicode_, String >(pyObj);
#else
if(isAPython<_PyBytes_>(pyObj))
{
result = convert<_PyBytes_, String>(pyObj);
}
else if (isAPython<_PyUnicode_>(pyObj))
{
result = convert<_PyUnicode_, String>(pyObj);
}
#endif
return result;
}
template <>
inline
PyObject *
convert< String, _PyString_ >( String s )
{
#if PY_MAJOR_VERSION >= 3
return convert<String, _PyUnicode_>(s);
#else
return convert<String, _PyBytes_>(s);
#endif
}
/* PySequence */
struct _PySequence_ {};
template <>
inline
int
isAPython< _PySequence_ >(PyObject * pyObj)
{
return PySequence_Check(pyObj);
}
template <>
inline
const char *
namePython<_PySequence_>()
{
return "sequence object";
}
template <class PYTHON_Type>
static inline
int
isAPythonSequenceOf(PyObject * pyObj)
{
int ok = isAPython<_PySequence_>(pyObj) && (! isAPython< _PyString_ >(pyObj));
if ( ok )
{
const UnsignedInteger size = PySequence_Size(pyObj);
for( UnsignedInteger i = 0; ok && (i < size); ++i )
{
ScopedPyObjectPointer elt(PySequence_ITEM( pyObj, i ));
int elt_ok = isAPython<PYTHON_Type>(elt.get());
ok *= elt_ok;
}
}
return ok;
}
template <class PYTHON_Type>
static inline
void
check(PyObject * pyObj)
{
if (! isAPython<PYTHON_Type>(pyObj))
{
throw InvalidArgumentException(HERE) << "Object passed as argument is not a " << namePython<PYTHON_Type>();
}
}
template <class PYTHON_Type, class CPP_Type>
static inline
CPP_Type
checkAndConvert(PyObject * pyObj)
{
check<PYTHON_Type>(pyObj);
return convert< PYTHON_Type, CPP_Type >(pyObj);
}
template <class T>
static inline
bool
canConvertCollectionObjectFromPySequence(PyObject * pyObj)
{
try
{
check<_PySequence_>(pyObj);
}
catch( InvalidArgumentException & ex )
{
return false;
}
ScopedPyObjectPointer newPyObj(PySequence_Fast( pyObj, "" ));
const UnsignedInteger size = PySequence_Fast_GET_SIZE( newPyObj.get() );
for(UnsignedInteger i = 0; i < size; ++i)
{
PyObject * elt = PySequence_Fast_GET_ITEM( newPyObj.get(), i );
if (!canConvert< typename traitsPythonType< T >::Type, T >( elt ))
{
return false;
}
}
return true;
}
template <class T>
static inline
Collection<T> *
buildCollectionFromPySequence(PyObject * pyObj, int sz = 0)
{
check<_PySequence_>(pyObj);
ScopedPyObjectPointer newPyObj(PySequence_Fast( pyObj, "" ));
if (!newPyObj.get()) throw InvalidArgumentException(HERE) << "Not a sequence object";
const UnsignedInteger size = PySequence_Fast_GET_SIZE( newPyObj.get() );
if ((sz != 0) && (sz != (int)size))
{
throw InvalidArgumentException(HERE) << "Sequence object has incorrect size " << size << ". Must be " << sz << ".";
}
Collection<T> * p_coll = new Collection< T >( size );
for(UnsignedInteger i = 0; i < size; ++i)
{
PyObject * elt = PySequence_Fast_GET_ITEM( newPyObj.get(), i );
try
{
check<typename traitsPythonType< T >::Type>( elt );
}
catch( InvalidArgumentException & ex )
{
delete p_coll;
throw;
}
(*p_coll)[i] = convert< typename traitsPythonType< T >::Type, T >( elt );
}
return p_coll;
}
template <>
struct traitsPythonType< NumericalPoint >
{
typedef _PySequence_ Type;
};
template <>
inline
NumericalPoint
convert< _PySequence_, NumericalPoint >(PyObject * pyObj)
{
Pointer<Collection<NumericalScalar> > ptr = buildCollectionFromPySequence<NumericalScalar>(pyObj);
return NumericalPoint( *ptr );
}
template <>
inline
PyObject *
convert< NumericalPoint, _PySequence_ >(NumericalPoint inP)
{
UnsignedInteger dimension = inP.getDimension();
PyObject * point = PyTuple_New( dimension );
for ( UnsignedInteger i = 0; i < dimension; ++ i )
{
PyTuple_SetItem( point, i, convert< NumericalScalar, _PyFloat_ >( inP[i] ) );
}
return point;
}
template <>
struct traitsPythonType< Collection < NumericalComplex> >
{
typedef _PySequence_ Type;
};
template <>
inline
Collection<NumericalComplex>
convert<_PySequence_, Collection<NumericalComplex> >(PyObject * pyObj)
{
Pointer<Collection<NumericalComplex> > ptr = buildCollectionFromPySequence<NumericalComplex>(pyObj);
return Collection<NumericalComplex>( *ptr );
}
template <>
struct traitsPythonType< NumericalSample >
{
typedef _PySequence_ Type;
};
template <>
inline
NumericalSample
convert< _PySequence_, NumericalSample >(PyObject * pyObj)
{
Pointer<Collection<NumericalPoint> > ptr = buildCollectionFromPySequence<NumericalPoint>(pyObj);
return NumericalSample( *ptr );
}
template <>
struct traitsPythonType< Collection< UnsignedInteger > >
{
typedef _PySequence_ Type;
};
template <>
inline
Collection< UnsignedInteger >
convert< _PySequence_, Collection<UnsignedInteger> >(PyObject * pyObj)
{
Pointer<Collection<UnsignedInteger> > ptr = buildCollectionFromPySequence<UnsignedInteger>(pyObj);
return Collection<UnsignedInteger>( ptr->begin(), ptr->end() );
}
template <>
struct traitsPythonType< Indices >
{
typedef _PySequence_ Type;
};
template <>
inline
Indices
convert< _PySequence_, Indices >(PyObject * pyObj)
{
Pointer<Collection<UnsignedInteger> > ptr = buildCollectionFromPySequence<UnsignedInteger>(pyObj);
return Indices( ptr->begin(), ptr->end() );
}
template <>
inline
PyObject *
convert< Indices, _PySequence_ >(Indices inP)
{
UnsignedInteger dimension = inP.getSize();
PyObject * point = PyTuple_New(dimension);
for (UnsignedInteger i = 0; i < dimension; ++ i)
{
PyTuple_SetItem( point, i, convert< UnsignedInteger, _PyInt_ >(inP[i]));
}
return point;
}
template <>
struct traitsPythonType< Description >
{
typedef _PySequence_ Type;
};
template <>
inline
Description
convert<_PySequence_, Description>(PyObject * pyObj)
{
Pointer<Collection<String> > ptr = buildCollectionFromPySequence<String>(pyObj);
return Description( *ptr );
}
template <>
struct traitsPythonType< Collection< NumericalScalar > >
{
typedef _PySequence_ Type;
};
template <>
inline
Collection<NumericalScalar>
convert< _PySequence_, Collection<NumericalScalar> >(PyObject * pyObj)
{
Pointer<Collection<NumericalScalar> > ptr = buildCollectionFromPySequence<NumericalScalar>(pyObj);
return Collection<NumericalScalar>( *ptr );
}
template <>
struct traitsPythonType< MatrixImplementation >
{
typedef _PySequence_ Type;
};
template <>
inline
MatrixImplementation*
convert< _PySequence_, MatrixImplementation* >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = 0;
// use the same conversion function for numpy array/matrix, knowing numpy matrix is not a sequence
if ( PyObject_HasAttrString(pyObj, const_cast<char *>("shape")) )
{
ScopedPyObjectPointer shapeObj(PyObject_GetAttrString( pyObj, "shape" ));
if ( shapeObj.get() )
{
Indices shape( checkAndConvert< _PySequence_, Indices >( shapeObj.get() ) );
if ( shape.getSize() == 2 )
{
UnsignedInteger nbRows = shape[0];
UnsignedInteger nbColumns = shape[1];
ScopedPyObjectPointer askObj(PyTuple_New(2));
ScopedPyObjectPointer methodObj(convert< String, _PyString_ >("__getitem__"));
p_implementation = new MatrixImplementation( nbRows, nbColumns );
for ( UnsignedInteger i = 0; i < nbRows; ++ i )
{
PyTuple_SetItem( askObj.get(), 0, convert< UnsignedInteger, _PyInt_ >(i) );
for ( UnsignedInteger j = 0; j < nbColumns; ++ j )
{
PyTuple_SetItem( askObj.get(), 1, convert< UnsignedInteger, _PyInt_ >(j) );
ScopedPyObjectPointer elt(PyObject_CallMethodObjArgs( pyObj, methodObj.get(), askObj.get(), NULL));
if (elt.get())
{
try
{
p_implementation->operator()( i, j ) = checkAndConvert<_PyFloat_, NumericalScalar>(elt.get());
}
catch( InvalidArgumentException & ex )
{
delete p_implementation;
throw;
}
}
}
}
}
else
throw InvalidArgumentException(HERE) << "Invalid array dimension: " << shape.getSize();
}
}
else if ( PyObject_HasAttrString(pyObj, const_cast<char *>("getNbColumns")) )
{
// case of conversion from XMatrix to YMatrix
// X could be Square,Triangular,Identity...
// YMatrix might be Matrix of one of its inheritance types
ScopedPyObjectPointer colunmsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbColumns" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer rowsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbRows" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer implObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getImplementation" ),
const_cast<char *>( "()" ) ));
Pointer< Collection< NumericalScalar > > ptr = buildCollectionFromPySequence< NumericalScalar >( implObj.get() );
UnsignedInteger nbColumns( checkAndConvert< _PyInt_, UnsignedInteger >( colunmsObj.get() ) );
UnsignedInteger nbRows( checkAndConvert< _PyInt_, UnsignedInteger >( rowsObj.get() ) );
p_implementation = new MatrixImplementation( nbRows, nbColumns, *ptr );
}
else
{
// try to convert from a sequence of sequences
Pointer< Collection< NumericalPoint > > ptr = buildCollectionFromPySequence< NumericalPoint >(pyObj);
NumericalSample sample( *ptr );
UnsignedInteger nbRows = sample.getSize();
UnsignedInteger nbColumns = sample.getDimension();
p_implementation = new MatrixImplementation( nbRows, nbColumns );
for ( UnsignedInteger i = 0; i < nbRows; ++ i )
for ( UnsignedInteger j = 0; j < nbColumns; ++ j )
p_implementation->operator()( i, j ) = sample[i][j];
}
return p_implementation;
}
template <>
inline
Matrix
convert< _PySequence_, Matrix >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = convert< _PySequence_, MatrixImplementation* >(pyObj);
return Matrix( p_implementation );
}
template <>
inline
SquareMatrix
convert< _PySequence_, SquareMatrix >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = convert< _PySequence_, MatrixImplementation* >(pyObj);
if ( p_implementation->getNbRows() != p_implementation->getNbColumns() )
throw InvalidArgumentException(HERE) << "The matrix is not square";
return SquareMatrix( p_implementation );
}
template <>
inline
TriangularMatrix
convert< _PySequence_, TriangularMatrix >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = convert< _PySequence_, MatrixImplementation* >(pyObj);
if (!(p_implementation->isTriangular(true) || p_implementation->isTriangular(false)))
throw InvalidArgumentException(HERE) << "The matrix is not triangular";
return TriangularMatrix( p_implementation, p_implementation->isTriangular(true) );
}
template <>
inline
SymmetricMatrix
convert< _PySequence_, SymmetricMatrix >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = convert< _PySequence_, MatrixImplementation* >(pyObj);
if (!p_implementation->isSymmetric())
throw InvalidArgumentException(HERE) << "The matrix is not symmetric";
return SymmetricMatrix( p_implementation );
}
template <>
inline
CovarianceMatrix
convert< _PySequence_, CovarianceMatrix >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = convert< _PySequence_, MatrixImplementation* >(pyObj);
if (!p_implementation->isSymmetric())
throw InvalidArgumentException(HERE) << "The matrix is not symmetric";
// SPD check is too expensive
return CovarianceMatrix( p_implementation );
}
template <>
inline
CorrelationMatrix
convert< _PySequence_, CorrelationMatrix >(PyObject * pyObj)
{
MatrixImplementation *p_implementation = convert< _PySequence_, MatrixImplementation* >(pyObj);
if (!p_implementation->isSymmetric())
throw InvalidArgumentException(HERE) << "The matrix is not symmetric";
// SPD check is too expensive
if (!p_implementation->hasUnitRange())
throw InvalidArgumentException(HERE) << "The matrix range is not (-1;1)";
return CorrelationMatrix( p_implementation );
}
template <>
struct traitsPythonType< TensorImplementation >
{
typedef _PySequence_ Type;
};
template <>
inline
TensorImplementation*
convert< _PySequence_, TensorImplementation* >(PyObject * pyObj)
{
Pointer< Collection< NumericalSample > > ptr = buildCollectionFromPySequence< NumericalSample >(pyObj);
UnsignedInteger nbRows = ptr->getSize();
UnsignedInteger nbColumns = ptr->getSize() > 0 ? (*ptr)[0].getSize() : 0;
UnsignedInteger nbSheets = ptr->getSize() > 0 ? (*ptr)[0].getDimension() : 0;
TensorImplementation *p_implementation = new TensorImplementation( nbRows, nbColumns, nbSheets );
for ( UnsignedInteger i = 0; i < nbRows; ++ i )
for ( UnsignedInteger j = 0; j < nbColumns; ++ j )
for ( UnsignedInteger k = 0; k < nbSheets; ++ k )
p_implementation->operator()( i, j, k ) = (*ptr)[i][j][k];
return p_implementation;
}
template <>
inline
Tensor
convert< _PySequence_, Tensor >(PyObject * pyObj)
{
TensorImplementation *p_implementation = convert<_PySequence_, TensorImplementation*>(pyObj);
return Tensor( p_implementation );
}
template <>
inline
SymmetricTensor
convert< _PySequence_, SymmetricTensor >(PyObject * pyObj)
{
TensorImplementation *p_implementation = convert< _PySequence_, TensorImplementation* >(pyObj);
if (!p_implementation->isSymmetric())
throw InvalidArgumentException(HERE) << "The tensor is not symmetric";
return SymmetricTensor( p_implementation );
}
template <>
struct traitsPythonType< ComplexMatrixImplementation* >
{
typedef _PySequence_ Type;
};
template <>
inline
ComplexMatrixImplementation*
convert< _PySequence_, ComplexMatrixImplementation* >(PyObject * pyObj)
{
// use the same conversion function for numpy array/matrix, knowing numpy matrix is not a sequence
if ( PyObject_HasAttrString(pyObj, const_cast<char *>("shape")) )
{
ScopedPyObjectPointer shapeObj(PyObject_GetAttrString( pyObj, "shape" ));
if (shapeObj.get())
{
Indices shape( checkAndConvert< _PySequence_, Indices >( shapeObj.get() ) );
if ( shape.getSize() == 2 )
{
UnsignedInteger nbRows = shape[0];
UnsignedInteger nbColumns = shape[1];
ScopedPyObjectPointer askObj(PyTuple_New(2));
ScopedPyObjectPointer methodObj(convert< String, _PyString_ >("__getitem__"));
ComplexMatrixImplementation *p_implementation = new ComplexMatrixImplementation( nbRows, nbColumns );
for ( UnsignedInteger i = 0; i < nbRows; ++ i )
{
PyTuple_SetItem( askObj.get(), 0, convert< UnsignedInteger, _PyInt_ >(i) );
for ( UnsignedInteger j = 0; j < nbColumns; ++ j )
{
PyTuple_SetItem( askObj.get(), 1, convert< UnsignedInteger, _PyInt_ >(j) );
ScopedPyObjectPointer elt(PyObject_CallMethodObjArgs( pyObj, methodObj.get(), askObj.get(), NULL));
if (elt.get())
{
try
{
p_implementation->operator()( i, j ) = checkAndConvert<_PyComplex_, NumericalComplex>(elt.get());
}
catch( InvalidArgumentException & ex )
{
delete p_implementation;
throw;
}
}
}
}
return p_implementation;
}
else
throw InvalidArgumentException(HERE) << "Invalid array dimension: " << shape.getSize();
}
}
// case of conversion from XMatrix to YMatrix
// X could be Square,Triangular,Identity...
// YMatrix might be Matrix of one of its inheritance types
if ( PyObject_HasAttrString(pyObj, const_cast<char *>("getNbColumns")) )
{
ScopedPyObjectPointer colunmsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbColumns" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer rowsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbRows" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer implObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getImplementation" ),
const_cast<char *>( "()" ) ));
Pointer< Collection< NumericalComplex > > ptr = buildCollectionFromPySequence< NumericalComplex >( implObj.get() );
UnsignedInteger nbColumns( checkAndConvert< _PyInt_, UnsignedInteger >( colunmsObj.get() ) );
UnsignedInteger nbRows( checkAndConvert< _PyInt_, UnsignedInteger >( rowsObj.get() ) );
ComplexMatrixImplementation *p_implementation = new ComplexMatrixImplementation( nbRows, nbColumns, *ptr );
return p_implementation;
}
// else try to convert from a sequence of sequences
Pointer< Collection< Collection< NumericalComplex > > > ptr = buildCollectionFromPySequence< Collection< NumericalComplex > >(pyObj);
UnsignedInteger nbRows = ptr->getSize();
UnsignedInteger nbColumns = ptr->getSize() > 0 ? (*ptr)[0].getSize() : 0;
ComplexMatrixImplementation *p_implementation = new ComplexMatrixImplementation( nbRows, nbColumns );
for ( UnsignedInteger i = 0; i < nbRows; ++ i )
for ( UnsignedInteger j = 0; j < nbColumns; ++ j )
p_implementation->operator()( i, j ) = (*ptr)[i][j];
return p_implementation;
}
template <>
inline
ComplexMatrix
convert< _PySequence_, ComplexMatrix >(PyObject * pyObj)
{
ComplexMatrixImplementation *p_implementation = convert< _PySequence_, ComplexMatrixImplementation* >(pyObj);
return ComplexMatrix( p_implementation );
}
template <>
inline
SquareComplexMatrix
convert< _PySequence_, SquareComplexMatrix >(PyObject * pyObj)
{
ComplexMatrixImplementation *p_implementation = convert< _PySequence_, ComplexMatrixImplementation* >(pyObj);
if ( p_implementation->getNbRows() != p_implementation->getNbColumns() )
throw InvalidArgumentException(HERE) << "The matrix is not square";
return SquareComplexMatrix( p_implementation );
}
template <>
inline
TriangularComplexMatrix
convert< _PySequence_, TriangularComplexMatrix >(PyObject * pyObj)
{
ComplexMatrixImplementation *p_implementation = convert< _PySequence_, ComplexMatrixImplementation* >(pyObj);
Bool lower = p_implementation->isTriangular(true);
if ( !lower && !p_implementation->isTriangular(false) )
throw InvalidArgumentException(HERE) << "The matrix is not triangular";
return TriangularComplexMatrix( p_implementation, lower );
}
template <>
struct traitsPythonType< HermitianMatrix >
{
typedef _PySequence_ Type;
};
template <>
inline
HermitianMatrix
convert< _PySequence_, HermitianMatrix >(PyObject * pyObj)
{
ComplexMatrixImplementation *p_implementation = convert< _PySequence_, ComplexMatrixImplementation* >(pyObj);
if ( !p_implementation->isHermitian() )
throw InvalidArgumentException(HERE) << "The matrix is not hermitian";
return HermitianMatrix( p_implementation );
}
template <>
struct traitsPythonType< ComplexTensorImplementation >
{
typedef _PySequence_ Type;
};
template <>
inline
ComplexTensorImplementation*
convert< _PySequence_, ComplexTensorImplementation* >(PyObject * pyObj)
{
ComplexTensorImplementation *p_implementation = 0;
// use the same conversion function for numpy array/matrix, knowing numpy matrix is not a sequence
if ( PyObject_HasAttrString(pyObj, const_cast<char *>("shape")) )
{
ScopedPyObjectPointer shapeObj(PyObject_GetAttrString( pyObj, "shape" ));
if (shapeObj.get())
{
Indices shape( checkAndConvert< _PySequence_, Indices >( shapeObj.get() ) );
if ( shape.getSize() == 3 )
{
UnsignedInteger nbRows = shape[0];
UnsignedInteger nbColumns = shape[1];
UnsignedInteger nbSheets = shape[2];
ScopedPyObjectPointer askObj(PyTuple_New(3));
ScopedPyObjectPointer methodObj(convert< String, _PyString_ >("__getitem__"));
p_implementation = new ComplexTensorImplementation( nbRows, nbColumns, nbSheets );
for ( UnsignedInteger i = 0; i < nbRows; ++ i )
{
PyTuple_SetItem( askObj.get(), 0, convert< UnsignedInteger, _PyInt_ >(i) );
for ( UnsignedInteger j = 0; j < nbColumns; ++ j )
{
PyTuple_SetItem( askObj.get(), 1, convert< UnsignedInteger, _PyInt_ >(j) );
for ( UnsignedInteger k = 0; k < nbSheets; ++ k )
{
PyTuple_SetItem( askObj.get(), 2, convert< UnsignedInteger, _PyInt_ >(k) );
ScopedPyObjectPointer elt(PyObject_CallMethodObjArgs( pyObj, methodObj.get(), askObj.get(), NULL));
if (elt.get())
{
try
{
p_implementation->operator()( i, j, k ) = checkAndConvert<_PyComplex_, NumericalComplex>(elt.get());
}
catch( InvalidArgumentException & ex )
{
delete p_implementation;
throw;
}
}
}
}
}
}
else
throw InvalidArgumentException(HERE) << "Invalid array dimension: " << shape.getSize();
}
}
else if ( PyObject_HasAttrString(pyObj, const_cast<char *>("getNbSheets")) )
{
// case of conversion from XTensor to YTensor
ScopedPyObjectPointer colunmsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbColumns" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer rowsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbRows" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer sheetsObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getNbSheets" ),
const_cast<char *>( "()" ) ));
ScopedPyObjectPointer implObj(PyObject_CallMethod ( pyObj,
const_cast<char *>( "getImplementation" ),
const_cast<char *>( "()" ) ));
Pointer< Collection< NumericalComplex > > ptr = buildCollectionFromPySequence< NumericalComplex >( implObj.get() );
UnsignedInteger nbColumns( checkAndConvert< _PyInt_, UnsignedInteger >( colunmsObj.get() ) );
UnsignedInteger nbRows( checkAndConvert< _PyInt_, UnsignedInteger >( rowsObj.get() ) );
UnsignedInteger nbSheets( checkAndConvert< _PyInt_, UnsignedInteger >( sheetsObj.get() ) );
p_implementation = new ComplexTensorImplementation( nbRows, nbColumns, nbSheets, *ptr );
}
return p_implementation;
}
template <>
inline
ComplexTensor
convert< _PySequence_, ComplexTensor >(PyObject * pyObj)
{
ComplexTensorImplementation *p_implementation = convert<_PySequence_, ComplexTensorImplementation*>(pyObj);
return ComplexTensor( p_implementation );
}
template <>
struct traitsPythonType< WhittleFactoryState >
{
typedef _PySequence_ Type;
};
template <>
inline
WhittleFactoryState
convert< _PySequence_, WhittleFactoryState >(PyObject * pyObj)
{
return WhittleFactoryState();
}
template <>
struct traitsPythonType< CovarianceModel >
{
typedef _PySequence_ Type;
};
template <>
inline
CovarianceModel
convert< _PySequence_, CovarianceModel >(PyObject * pyObj)
{
return CovarianceModel();
}
template <>
struct traitsPythonType< Process >
{
typedef _PySequence_ Type;
};
template <>
inline
Process
convert< _PySequence_, Process >(PyObject * pyObj)
{
return Process();
}
inline
void handleException()
{
PyObject * exception = PyErr_Occurred();
if ( exception )
{
PyObject *type = NULL, *value = NULL, *traceback = NULL;
PyErr_Fetch( &type, &value, &traceback );
String exceptionMessage("Python exception");
// get the name of the exception
if ( type )
{
ScopedPyObjectPointer nameObj(PyObject_GetAttrString( type, "__name__" ));
if ( nameObj.get() )
{
String typeString = checkAndConvert< _PyString_, String >(nameObj.get());
exceptionMessage += ": " + typeString;
}
}
// try to get error msg, value and traceback can be NULL
if(value)
{
try
{
String valueString = checkAndConvert< _PyString_, String >(value);
exceptionMessage += ": " + valueString;
}
catch( InvalidArgumentException & ex )
{
// could not get msg from strings
}
}
PyErr_Restore( type, value, traceback );
PyErr_Print();
throw InternalException(HERE) << exceptionMessage;
}
}
// PySliceObject type is deprecated
#if PY_VERSION_HEX >= 0x03020000
inline PyObject* SliceCast(PyObject* pyObj)
{
return pyObj;
}
#else
inline PySliceObject* SliceCast(PyObject* pyObj)
{
return (PySliceObject*)pyObj;
}
#endif
inline
void pickleSave(Advocate & adv, PyObject * pyObj)
{
ScopedPyObjectPointer pickleModule(PyImport_ImportModule( "pickle" )); // new reference
assert( pickleModule.get() );
PyObject * pickleDict = PyModule_GetDict( pickleModule.get() );
assert(pickleDict);
PyObject * dumpsMethod = PyDict_GetItemString( pickleDict, "dumps" );
assert( dumpsMethod );
if ( ! PyCallable_Check( dumpsMethod ) )
throw InternalException(HERE) << "Python 'pickle' module has no 'dumps' method";
assert(pyObj);
ScopedPyObjectPointer rawDump(PyObject_CallFunctionObjArgs(dumpsMethod, pyObj, NULL)); // new reference
handleException();
assert( rawDump.get() );
ScopedPyObjectPointer base64Module(PyImport_ImportModule( "base64" )); // new reference
assert( base64Module.get() );
PyObject * base64Dict = PyModule_GetDict( base64Module.get() );
assert( base64Dict );
PyObject * b64encodeMethod = PyDict_GetItemString( base64Dict, "standard_b64encode" );
assert( b64encodeMethod );
if ( ! PyCallable_Check( b64encodeMethod ) )
throw InternalException(HERE) << "Python 'base64' module has no 'standard_b64encode' method";
ScopedPyObjectPointer base64Dump(PyObject_CallFunctionObjArgs(b64encodeMethod, rawDump.get(), NULL)); // new reference
handleException();
assert( base64Dump.get() );
String pyInstanceSt(convert< _PyBytes_, String >( base64Dump.get() ));
adv.saveAttribute( "pyInstance_", pyInstanceSt );
}
inline
void pickleLoad(Advocate & adv, PyObject * & pyObj)
{
String pyInstanceSt;
adv.loadAttribute( "pyInstance_", pyInstanceSt );
ScopedPyObjectPointer base64Dump(convert< String, _PyBytes_ >( pyInstanceSt )); // new reference
assert( base64Dump.get() );
ScopedPyObjectPointer base64Module(PyImport_ImportModule( "base64" )); // new reference
assert( base64Module.get() );
PyObject * base64Dict = PyModule_GetDict( base64Module.get() );
assert( base64Dict );
PyObject * b64decodeMethod = PyDict_GetItemString( base64Dict, "standard_b64decode" );
assert( b64decodeMethod );
if ( ! PyCallable_Check( b64decodeMethod ) )
throw InternalException(HERE) << "Python 'base64' module has no 'standard_b64decode' method";
ScopedPyObjectPointer rawDump(PyObject_CallFunctionObjArgs(b64decodeMethod, base64Dump.get(), NULL)); // new reference
handleException();
assert( rawDump.get() );
ScopedPyObjectPointer pickleModule(PyImport_ImportModule( "pickle" )); // new reference
assert( pickleModule.get() );
PyObject * pickleDict = PyModule_GetDict( pickleModule.get() );
assert( pickleDict );
PyObject * loadsMethod = PyDict_GetItemString( pickleDict, "loads" );
assert( loadsMethod );
if ( ! PyCallable_Check( loadsMethod ) )
throw InternalException(HERE) << "Python 'pickle' module has no 'loads' method";
Py_XDECREF(pyObj);
pyObj = PyObject_CallFunctionObjArgs(loadsMethod, rawDump.get(), NULL); // new reference
handleException();
assert(pyObj);
}
END_NAMESPACE_OPENTURNS
#endif /* OPENTURNS_PYTHONWRAPPINGFUNCTIONS_HXX */
|