diff options
Diffstat (limited to 'doc/swig/test')
28 files changed, 3354 insertions, 0 deletions
diff --git a/doc/swig/test/Array.i b/doc/swig/test/Array.i new file mode 100644 index 000000000..d56dd2d1c --- /dev/null +++ b/doc/swig/test/Array.i @@ -0,0 +1,107 @@ +// -*- c++ -*- + +%module Array + +%{ +#define SWIG_FILE_WITH_INIT +#include "Array1.h" +#include "Array2.h" +%} + +// Get the NumPy typemaps +%include "../numpy.i" + + // Get the STL typemaps +%include "stl.i" + +// Handle standard exceptions +%include "exception.i" +%exception +{ + try + { + $action + } + catch (const std::invalid_argument& e) + { + SWIG_exception(SWIG_ValueError, e.what()); + } + catch (const std::out_of_range& e) + { + SWIG_exception(SWIG_IndexError, e.what()); + } +} +%init %{ + import_array(); +%} + +// Global ignores +%ignore *::operator=; +%ignore *::operator[]; + +// Apply the 1D NumPy typemaps +%apply (int DIM1 , long* INPLACE_ARRAY1) + {(int length, long* data )}; +%apply (long** ARGOUTVIEW_ARRAY1, int* DIM1 ) + {(long** data , int* length)}; + +// Apply the 2D NumPy typemaps +%apply (int DIM1 , int DIM2 , long* INPLACE_ARRAY2) + {(int nrows, int ncols, long* data )}; +%apply (int* DIM1 , int* DIM2 , long** ARGOUTVIEW_ARRAY2) + {(int* nrows, int* ncols, long** data )}; +// Note: the %apply for INPLACE_ARRAY2 above gets successfully applied +// to the constructor Array2(int nrows, int ncols, long* data), but +// does not get applied to the method Array2::resize(int nrows, int +// ncols, long* data). I have no idea why. For this reason the test +// for Apply2.resize(numpy.ndarray) in testArray.py is commented out. + +// Array1 support +%include "Array1.h" +%extend Array1 +{ + void __setitem__(int i, long v) + { + self->operator[](i) = v; + } + + long __getitem__(int i) + { + return self->operator[](i); + } + + int __len__() + { + return self->length(); + } + + std::string __str__() + { + return self->asString(); + } +} + +// Array2 support +%include "Array2.h" +%extend Array2 +{ + void __setitem__(int i, Array1 & v) + { + self->operator[](i) = v; + } + + Array1 & __getitem__(int i) + { + return self->operator[](i); + } + + int __len__() + { + return self->nrows() * self->ncols(); + } + + std::string __str__() + { + return self->asString(); + } +} diff --git a/doc/swig/test/Array1.cxx b/doc/swig/test/Array1.cxx new file mode 100644 index 000000000..0c09e02f9 --- /dev/null +++ b/doc/swig/test/Array1.cxx @@ -0,0 +1,131 @@ +#include "Array1.h" +#include <iostream> +#include <sstream> + +// Default/length/array constructor +Array1::Array1(int length, long* data) : + _ownData(false), _length(0), _buffer(0) +{ + resize(length, data); +} + +// Copy constructor +Array1::Array1(const Array1 & source) : + _length(source._length) +{ + allocateMemory(); + *this = source; +} + +// Destructor +Array1::~Array1() +{ + deallocateMemory(); +} + +// Assignment operator +Array1 & Array1::operator=(const Array1 & source) +{ + int len = _length < source._length ? _length : source._length; + for (int i=0; i < len; ++i) + { + (*this)[i] = source[i]; + } + return *this; +} + +// Equals operator +bool Array1::operator==(const Array1 & other) const +{ + if (_length != other._length) return false; + for (int i=0; i < _length; ++i) + { + if ((*this)[i] != other[i]) return false; + } + return true; +} + +// Length accessor +int Array1::length() const +{ + return _length; +} + +// Resize array +void Array1::resize(int length, long* data) +{ + if (length < 0) throw std::invalid_argument("Array1 length less than 0"); + if (length == _length) return; + deallocateMemory(); + _length = length; + if (!data) + { + allocateMemory(); + } + else + { + _ownData = false; + _buffer = data; + } +} + +// Set item accessor +long & Array1::operator[](int i) +{ + if (i < 0 || i >= _length) throw std::out_of_range("Array1 index out of range"); + return _buffer[i]; +} + +// Get item accessor +const long & Array1::operator[](int i) const +{ + if (i < 0 || i >= _length) throw std::out_of_range("Array1 index out of range"); + return _buffer[i]; +} + +// String output +std::string Array1::asString() const +{ + std::stringstream result; + result << "["; + for (int i=0; i < _length; ++i) + { + result << " " << _buffer[i]; + if (i < _length-1) result << ","; + } + result << " ]"; + return result.str(); +} + +// Get view +void Array1::view(long** data, int* length) const +{ + *data = _buffer; + *length = _length; +} + +// Private methods + void Array1::allocateMemory() + { + if (_length == 0) + { + _ownData = false; + _buffer = 0; + } + else + { + _ownData = true; + _buffer = new long[_length]; + } + } + + void Array1::deallocateMemory() + { + if (_ownData && _length && _buffer) + { + delete [] _buffer; + } + _ownData = false; + _length = 0; + _buffer = 0; + } diff --git a/doc/swig/test/Array1.h b/doc/swig/test/Array1.h new file mode 100644 index 000000000..754c248fc --- /dev/null +++ b/doc/swig/test/Array1.h @@ -0,0 +1,55 @@ +#ifndef ARRAY1_H +#define ARRAY1_H + +#include <stdexcept> +#include <string> + +class Array1 +{ +public: + + // Default/length/array constructor + Array1(int length = 0, long* data = 0); + + // Copy constructor + Array1(const Array1 & source); + + // Destructor + ~Array1(); + + // Assignment operator + Array1 & operator=(const Array1 & source); + + // Equals operator + bool operator==(const Array1 & other) const; + + // Length accessor + int length() const; + + // Resize array + void resize(int length, long* data = 0); + + // Set item accessor + long & operator[](int i); + + // Get item accessor + const long & operator[](int i) const; + + // String output + std::string asString() const; + + // Get view + void view(long** data, int* length) const; + +private: + // Members + bool _ownData; + int _length; + long * _buffer; + + // Methods + void allocateMemory(); + void deallocateMemory(); +}; + +#endif diff --git a/doc/swig/test/Array2.cxx b/doc/swig/test/Array2.cxx new file mode 100644 index 000000000..e3558f786 --- /dev/null +++ b/doc/swig/test/Array2.cxx @@ -0,0 +1,168 @@ +#include "Array2.h" +#include <sstream> + +// Default constructor +Array2::Array2() : + _ownData(false), _nrows(0), _ncols(), _buffer(0), _rows(0) +{ } + +// Size/array constructor +Array2::Array2(int nrows, int ncols, long* data) : + _ownData(false), _nrows(0), _ncols(), _buffer(0), _rows(0) +{ + resize(nrows, ncols, data); +} + +// Copy constructor +Array2::Array2(const Array2 & source) : + _nrows(source._nrows), _ncols(source._ncols) +{ + _ownData = true; + allocateMemory(); + *this = source; +} + +// Destructor +Array2::~Array2() +{ + deallocateMemory(); +} + +// Assignment operator +Array2 & Array2::operator=(const Array2 & source) +{ + int nrows = _nrows < source._nrows ? _nrows : source._nrows; + int ncols = _ncols < source._ncols ? _ncols : source._ncols; + for (int i=0; i < nrows; ++i) + { + for (int j=0; j < ncols; ++j) + { + (*this)[i][j] = source[i][j]; + } + } + return *this; +} + +// Equals operator +bool Array2::operator==(const Array2 & other) const +{ + if (_nrows != other._nrows) return false; + if (_ncols != other._ncols) return false; + for (int i=0; i < _nrows; ++i) + { + for (int j=0; j < _ncols; ++j) + { + if ((*this)[i][j] != other[i][j]) return false; + } + } + return true; +} + +// Length accessors +int Array2::nrows() const +{ + return _nrows; +} + +int Array2::ncols() const +{ + return _ncols; +} + +// Resize array +void Array2::resize(int nrows, int ncols, long* data) +{ + if (nrows < 0) throw std::invalid_argument("Array2 nrows less than 0"); + if (ncols < 0) throw std::invalid_argument("Array2 ncols less than 0"); + if (nrows == _nrows && ncols == _ncols) return; + deallocateMemory(); + _nrows = nrows; + _ncols = ncols; + if (!data) + { + allocateMemory(); + } + else + { + _ownData = false; + _buffer = data; + allocateRows(); + } +} + +// Set item accessor +Array1 & Array2::operator[](int i) +{ + if (i < 0 || i > _nrows) throw std::out_of_range("Array2 row index out of range"); + return _rows[i]; +} + +// Get item accessor +const Array1 & Array2::operator[](int i) const +{ + if (i < 0 || i > _nrows) throw std::out_of_range("Array2 row index out of range"); + return _rows[i]; +} + +// String output +std::string Array2::asString() const +{ + std::stringstream result; + result << "[ "; + for (int i=0; i < _nrows; ++i) + { + if (i > 0) result << " "; + result << (*this)[i].asString(); + if (i < _nrows-1) result << "," << std::endl; + } + result << " ]" << std::endl; + return result.str(); +} + +// Get view +void Array2::view(int* nrows, int* ncols, long** data) const +{ + *nrows = _nrows; + *ncols = _ncols; + *data = _buffer; +} + +// Private methods +void Array2::allocateMemory() +{ + if (_nrows * _ncols == 0) + { + _ownData = false; + _buffer = 0; + _rows = 0; + } + else + { + _ownData = true; + _buffer = new long[_nrows*_ncols]; + allocateRows(); + } +} + +void Array2::allocateRows() +{ + _rows = new Array1[_nrows]; + for (int i=0; i < _nrows; ++i) + { + _rows[i].resize(_ncols, &_buffer[i*_ncols]); + } +} + +void Array2::deallocateMemory() +{ + if (_ownData && _nrows*_ncols && _buffer) + { + delete [] _rows; + delete [] _buffer; + } + _ownData = false; + _nrows = 0; + _ncols = 0; + _buffer = 0; + _rows = 0; +} diff --git a/doc/swig/test/Array2.h b/doc/swig/test/Array2.h new file mode 100644 index 000000000..a6e5bfc30 --- /dev/null +++ b/doc/swig/test/Array2.h @@ -0,0 +1,63 @@ +#ifndef ARRAY2_H +#define ARRAY2_H + +#include "Array1.h" +#include <stdexcept> +#include <string> + +class Array2 +{ +public: + + // Default constructor + Array2(); + + // Size/array constructor + Array2(int nrows, int ncols, long* data=0); + + // Copy constructor + Array2(const Array2 & source); + + // Destructor + ~Array2(); + + // Assignment operator + Array2 & operator=(const Array2 & source); + + // Equals operator + bool operator==(const Array2 & other) const; + + // Length accessors + int nrows() const; + int ncols() const; + + // Resize array + void resize(int ncols, int nrows, long* data=0); + + // Set item accessor + Array1 & operator[](int i); + + // Get item accessor + const Array1 & operator[](int i) const; + + // String output + std::string asString() const; + + // Get view + void view(int* nrows, int* ncols, long** data) const; + +private: + // Members + bool _ownData; + int _nrows; + int _ncols; + long * _buffer; + Array1 * _rows; + + // Methods + void allocateMemory(); + void allocateRows(); + void deallocateMemory(); +}; + +#endif diff --git a/doc/swig/test/Farray.cxx b/doc/swig/test/Farray.cxx new file mode 100644 index 000000000..3983c333b --- /dev/null +++ b/doc/swig/test/Farray.cxx @@ -0,0 +1,122 @@ +#include "Farray.h" +#include <sstream> + +// Size constructor +Farray::Farray(int nrows, int ncols) : + _nrows(nrows), _ncols(ncols), _buffer(0) +{ + allocateMemory(); +} + +// Copy constructor +Farray::Farray(const Farray & source) : + _nrows(source._nrows), _ncols(source._ncols) +{ + allocateMemory(); + *this = source; +} + +// Destructor +Farray::~Farray() +{ + delete [] _buffer; +} + +// Assignment operator +Farray & Farray::operator=(const Farray & source) +{ + int nrows = _nrows < source._nrows ? _nrows : source._nrows; + int ncols = _ncols < source._ncols ? _ncols : source._ncols; + for (int i=0; i < nrows; ++i) + { + for (int j=0; j < ncols; ++j) + { + (*this)(i,j) = source(i,j); + } + } + return *this; +} + +// Equals operator +bool Farray::operator==(const Farray & other) const +{ + if (_nrows != other._nrows) return false; + if (_ncols != other._ncols) return false; + for (int i=0; i < _nrows; ++i) + { + for (int j=0; j < _ncols; ++j) + { + if ((*this)(i,j) != other(i,j)) return false; + } + } + return true; +} + +// Length accessors +int Farray::nrows() const +{ + return _nrows; +} + +int Farray::ncols() const +{ + return _ncols; +} + +// Set item accessor +long & Farray::operator()(int i, int j) +{ + if (i < 0 || i > _nrows) throw std::out_of_range("Farray row index out of range"); + if (j < 0 || j > _ncols) throw std::out_of_range("Farray col index out of range"); + return _buffer[offset(i,j)]; +} + +// Get item accessor +const long & Farray::operator()(int i, int j) const +{ + if (i < 0 || i > _nrows) throw std::out_of_range("Farray row index out of range"); + if (j < 0 || j > _ncols) throw std::out_of_range("Farray col index out of range"); + return _buffer[offset(i,j)]; +} + +// String output +std::string Farray::asString() const +{ + std::stringstream result; + result << "[ "; + for (int i=0; i < _nrows; ++i) + { + if (i > 0) result << " "; + result << "["; + for (int j=0; j < _ncols; ++j) + { + result << " " << (*this)(i,j); + if (j < _ncols-1) result << ","; + } + result << " ]"; + if (i < _nrows-1) result << "," << std::endl; + } + result << " ]" << std::endl; + return result.str(); +} + +// Get view +void Farray::view(int* nrows, int* ncols, long** data) const +{ + *nrows = _nrows; + *ncols = _ncols; + *data = _buffer; +} + +// Private methods +void Farray::allocateMemory() +{ + if (_nrows <= 0) throw std::invalid_argument("Farray nrows <= 0"); + if (_ncols <= 0) throw std::invalid_argument("Farray ncols <= 0"); + _buffer = new long[_nrows*_ncols]; +} + +inline int Farray::offset(int i, int j) const +{ + return i + j * _nrows; +} diff --git a/doc/swig/test/Farray.h b/doc/swig/test/Farray.h new file mode 100644 index 000000000..4199a287c --- /dev/null +++ b/doc/swig/test/Farray.h @@ -0,0 +1,56 @@ +#ifndef FARRAY_H +#define FARRAY_H + +#include <stdexcept> +#include <string> + +class Farray +{ +public: + + // Size constructor + Farray(int nrows, int ncols); + + // Copy constructor + Farray(const Farray & source); + + // Destructor + ~Farray(); + + // Assignment operator + Farray & operator=(const Farray & source); + + // Equals operator + bool operator==(const Farray & other) const; + + // Length accessors + int nrows() const; + int ncols() const; + + // Set item accessor + long & operator()(int i, int j); + + // Get item accessor + const long & operator()(int i, int j) const; + + // String output + std::string asString() const; + + // Get view + void view(int* nrows, int* ncols, long** data) const; + +private: + // Members + int _nrows; + int _ncols; + long * _buffer; + + // Default constructor: not implemented + Farray(); + + // Methods + void allocateMemory(); + int offset(int i, int j) const; +}; + +#endif diff --git a/doc/swig/test/Farray.i b/doc/swig/test/Farray.i new file mode 100644 index 000000000..25f6cd025 --- /dev/null +++ b/doc/swig/test/Farray.i @@ -0,0 +1,73 @@ +// -*- c++ -*- + +%module Farray + +%{ +#define SWIG_FILE_WITH_INIT +#include "Farray.h" +%} + +// Get the NumPy typemaps +%include "../numpy.i" + + // Get the STL typemaps +%include "stl.i" + +// Handle standard exceptions +%include "exception.i" +%exception +{ + try + { + $action + } + catch (const std::invalid_argument& e) + { + SWIG_exception(SWIG_ValueError, e.what()); + } + catch (const std::out_of_range& e) + { + SWIG_exception(SWIG_IndexError, e.what()); + } +} +%init %{ + import_array(); +%} + +// Global ignores +%ignore *::operator=; +%ignore *::operator(); + +// Apply the 2D NumPy typemaps +%apply (int* DIM1 , int* DIM2 , long** ARGOUTVIEW_FARRAY2) + {(int* nrows, int* ncols, long** data )}; + +// Farray support +%include "Farray.h" +%extend Farray +{ + PyObject * __setitem__(PyObject* index, long v) + { + int i, j; + if (!PyArg_ParseTuple(index, "ii:Farray___setitem__",&i,&j)) return NULL; + self->operator()(i,j) = v; + return Py_BuildValue(""); + } + + PyObject * __getitem__(PyObject * index) + { + int i, j; + if (!PyArg_ParseTuple(index, "ii:Farray___getitem__",&i,&j)) return NULL; + return SWIG_From_long(self->operator()(i,j)); + } + + int __len__() + { + return self->nrows() * self->ncols(); + } + + std::string __str__() + { + return self->asString(); + } +} diff --git a/doc/swig/test/Fortran.cxx b/doc/swig/test/Fortran.cxx new file mode 100644 index 000000000..475d21ddc --- /dev/null +++ b/doc/swig/test/Fortran.cxx @@ -0,0 +1,24 @@ +#include <stdlib.h> +#include <math.h> +#include <iostream> +#include "Fortran.h" + +#define TEST_FUNCS(TYPE, SNAME) \ +\ +TYPE SNAME ## SecondElement(TYPE * matrix, int rows, int cols) { \ + TYPE result = matrix[1]; \ + return result; \ +} \ + +TEST_FUNCS(signed char , schar ) +TEST_FUNCS(unsigned char , uchar ) +TEST_FUNCS(short , short ) +TEST_FUNCS(unsigned short , ushort ) +TEST_FUNCS(int , int ) +TEST_FUNCS(unsigned int , uint ) +TEST_FUNCS(long , long ) +TEST_FUNCS(unsigned long , ulong ) +TEST_FUNCS(long long , longLong ) +TEST_FUNCS(unsigned long long, ulongLong) +TEST_FUNCS(float , float ) +TEST_FUNCS(double , double ) diff --git a/doc/swig/test/Fortran.h b/doc/swig/test/Fortran.h new file mode 100644 index 000000000..c243bb50f --- /dev/null +++ b/doc/swig/test/Fortran.h @@ -0,0 +1,21 @@ +#ifndef FORTRAN_H +#define FORTRAN_H + +#define TEST_FUNC_PROTOS(TYPE, SNAME) \ +\ +TYPE SNAME ## SecondElement( TYPE * matrix, int rows, int cols); \ + +TEST_FUNC_PROTOS(signed char , schar ) +TEST_FUNC_PROTOS(unsigned char , uchar ) +TEST_FUNC_PROTOS(short , short ) +TEST_FUNC_PROTOS(unsigned short , ushort ) +TEST_FUNC_PROTOS(int , int ) +TEST_FUNC_PROTOS(unsigned int , uint ) +TEST_FUNC_PROTOS(long , long ) +TEST_FUNC_PROTOS(unsigned long , ulong ) +TEST_FUNC_PROTOS(long long , longLong ) +TEST_FUNC_PROTOS(unsigned long long, ulongLong) +TEST_FUNC_PROTOS(float , float ) +TEST_FUNC_PROTOS(double , double ) + +#endif diff --git a/doc/swig/test/Fortran.i b/doc/swig/test/Fortran.i new file mode 100644 index 000000000..131790dd6 --- /dev/null +++ b/doc/swig/test/Fortran.i @@ -0,0 +1,36 @@ +// -*- c++ -*- +%module Fortran + +%{ +#define SWIG_FILE_WITH_INIT +#include "Fortran.h" +%} + +// Get the NumPy typemaps +%include "../numpy.i" + +%init %{ + import_array(); +%} + +%define %apply_numpy_typemaps(TYPE) + +%apply (TYPE* IN_FARRAY2, int DIM1, int DIM2) {(TYPE* matrix, int rows, int cols)}; + +%enddef /* %apply_numpy_typemaps() macro */ + +%apply_numpy_typemaps(signed char ) +%apply_numpy_typemaps(unsigned char ) +%apply_numpy_typemaps(short ) +%apply_numpy_typemaps(unsigned short ) +%apply_numpy_typemaps(int ) +%apply_numpy_typemaps(unsigned int ) +%apply_numpy_typemaps(long ) +%apply_numpy_typemaps(unsigned long ) +%apply_numpy_typemaps(long long ) +%apply_numpy_typemaps(unsigned long long) +%apply_numpy_typemaps(float ) +%apply_numpy_typemaps(double ) + +// Include the header file to be wrapped +%include "Fortran.h" diff --git a/doc/swig/test/Makefile b/doc/swig/test/Makefile new file mode 100644 index 000000000..5360b1ced --- /dev/null +++ b/doc/swig/test/Makefile @@ -0,0 +1,34 @@ +# SWIG +INTERFACES = Array.i Farray.i Vector.i Matrix.i Tensor.i Fortran.i +WRAPPERS = $(INTERFACES:.i=_wrap.cxx) +PROXIES = $(INTERFACES:.i=.py ) + +# Default target: build the tests +.PHONY : all +all: $(WRAPPERS) Array1.cxx Array1.h Farray.cxx Farray.h Vector.cxx Vector.h \ + Matrix.cxx Matrix.h Tensor.cxx Tensor.h Fortran.h Fortran.cxx + ./setup.py build_ext -i + +# Test target: run the tests +.PHONY : test +test: all + python testVector.py + python testMatrix.py + python testTensor.py + python testArray.py + python testFarray.py + python testFortran.py + +# Rule: %.i -> %_wrap.cxx +%_wrap.cxx: %.i %.h ../numpy.i + swig -c++ -python $< +%_wrap.cxx: %.i %1.h %2.h ../numpy.i + swig -c++ -python $< + +# Clean target +.PHONY : clean +clean: + $(RM) -r build + $(RM) *.so + $(RM) $(WRAPPERS) + $(RM) $(PROXIES) diff --git a/doc/swig/test/Matrix.cxx b/doc/swig/test/Matrix.cxx new file mode 100644 index 000000000..b953d7017 --- /dev/null +++ b/doc/swig/test/Matrix.cxx @@ -0,0 +1,112 @@ +#include <stdlib.h> +#include <math.h> +#include <iostream> +#include "Matrix.h" + +// The following macro defines a family of functions that work with 2D +// arrays with the forms +// +// TYPE SNAMEDet( TYPE matrix[2][2]); +// TYPE SNAMEMax( TYPE * matrix, int rows, int cols); +// TYPE SNAMEMin( int rows, int cols, TYPE * matrix); +// void SNAMEScale( TYPE matrix[3][3]); +// void SNAMEFloor( TYPE * array, int rows, int cols, TYPE floor); +// void SNAMECeil( int rows, int cols, TYPE * array, TYPE ceil); +// void SNAMELUSplit(TYPE in[3][3], TYPE lower[3][3], TYPE upper[3][3]); +// +// for any specified type TYPE (for example: short, unsigned int, long +// long, etc.) with given short name SNAME (for example: short, uint, +// longLong, etc.). The macro is then expanded for the given +// TYPE/SNAME pairs. The resulting functions are for testing numpy +// interfaces, respectively, for: +// +// * 2D input arrays, hard-coded length +// * 2D input arrays +// * 2D input arrays, data last +// * 2D in-place arrays, hard-coded lengths +// * 2D in-place arrays +// * 2D in-place arrays, data last +// * 2D argout arrays, hard-coded length +// +#define TEST_FUNCS(TYPE, SNAME) \ +\ +TYPE SNAME ## Det(TYPE matrix[2][2]) { \ + return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]; \ +} \ +\ +TYPE SNAME ## Max(TYPE * matrix, int rows, int cols) { \ + int i, j, index; \ + TYPE result = matrix[0]; \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = j*rows + i; \ + if (matrix[index] > result) result = matrix[index]; \ + } \ + } \ + return result; \ +} \ +\ +TYPE SNAME ## Min(int rows, int cols, TYPE * matrix) { \ + int i, j, index; \ + TYPE result = matrix[0]; \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = j*rows + i; \ + if (matrix[index] < result) result = matrix[index]; \ + } \ + } \ + return result; \ +} \ +\ +void SNAME ## Scale(TYPE array[3][3], TYPE val) { \ + for (int i=0; i<3; ++i) \ + for (int j=0; j<3; ++j) \ + array[i][j] *= val; \ +} \ +\ +void SNAME ## Floor(TYPE * array, int rows, int cols, TYPE floor) { \ + int i, j, index; \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = j*rows + i; \ + if (array[index] < floor) array[index] = floor; \ + } \ + } \ +} \ +\ +void SNAME ## Ceil(int rows, int cols, TYPE * array, TYPE ceil) { \ + int i, j, index; \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = j*rows + i; \ + if (array[index] > ceil) array[index] = ceil; \ + } \ + } \ +} \ +\ +void SNAME ## LUSplit(TYPE matrix[3][3], TYPE lower[3][3], TYPE upper[3][3]) { \ + for (int i=0; i<3; ++i) { \ + for (int j=0; j<3; ++j) { \ + if (i >= j) { \ + lower[i][j] = matrix[i][j]; \ + upper[i][j] = 0; \ + } else { \ + lower[i][j] = 0; \ + upper[i][j] = matrix[i][j]; \ + } \ + } \ + } \ +} + +TEST_FUNCS(signed char , schar ) +TEST_FUNCS(unsigned char , uchar ) +TEST_FUNCS(short , short ) +TEST_FUNCS(unsigned short , ushort ) +TEST_FUNCS(int , int ) +TEST_FUNCS(unsigned int , uint ) +TEST_FUNCS(long , long ) +TEST_FUNCS(unsigned long , ulong ) +TEST_FUNCS(long long , longLong ) +TEST_FUNCS(unsigned long long, ulongLong) +TEST_FUNCS(float , float ) +TEST_FUNCS(double , double ) diff --git a/doc/swig/test/Matrix.h b/doc/swig/test/Matrix.h new file mode 100644 index 000000000..f37836cc4 --- /dev/null +++ b/doc/swig/test/Matrix.h @@ -0,0 +1,52 @@ +#ifndef MATRIX_H +#define MATRIX_H + +// The following macro defines the prototypes for a family of +// functions that work with 2D arrays with the forms +// +// TYPE SNAMEDet( TYPE matrix[2][2]); +// TYPE SNAMEMax( TYPE * matrix, int rows, int cols); +// TYPE SNAMEMin( int rows, int cols, TYPE * matrix); +// void SNAMEScale( TYPE array[3][3]); +// void SNAMEFloor( TYPE * array, int rows, int cols, TYPE floor); +// void SNAMECeil( int rows, int cols, TYPE * array, TYPE ceil ); +// void SNAMELUSplit(TYPE in[3][3], TYPE lower[3][3], TYPE upper[3][3]); +// +// for any specified type TYPE (for example: short, unsigned int, long +// long, etc.) with given short name SNAME (for example: short, uint, +// longLong, etc.). The macro is then expanded for the given +// TYPE/SNAME pairs. The resulting functions are for testing numpy +// interfaces, respectively, for: +// +// * 2D input arrays, hard-coded lengths +// * 2D input arrays +// * 2D input arrays, data last +// * 2D in-place arrays, hard-coded lengths +// * 2D in-place arrays +// * 2D in-place arrays, data last +// * 2D argout arrays, hard-coded length +// +#define TEST_FUNC_PROTOS(TYPE, SNAME) \ +\ +TYPE SNAME ## Det( TYPE matrix[2][2]); \ +TYPE SNAME ## Max( TYPE * matrix, int rows, int cols); \ +TYPE SNAME ## Min( int rows, int cols, TYPE * matrix); \ +void SNAME ## Scale( TYPE array[3][3], TYPE val); \ +void SNAME ## Floor( TYPE * array, int rows, int cols, TYPE floor); \ +void SNAME ## Ceil( int rows, int cols, TYPE * array, TYPE ceil ); \ +void SNAME ## LUSplit(TYPE matrix[3][3], TYPE lower[3][3], TYPE upper[3][3]); + +TEST_FUNC_PROTOS(signed char , schar ) +TEST_FUNC_PROTOS(unsigned char , uchar ) +TEST_FUNC_PROTOS(short , short ) +TEST_FUNC_PROTOS(unsigned short , ushort ) +TEST_FUNC_PROTOS(int , int ) +TEST_FUNC_PROTOS(unsigned int , uint ) +TEST_FUNC_PROTOS(long , long ) +TEST_FUNC_PROTOS(unsigned long , ulong ) +TEST_FUNC_PROTOS(long long , longLong ) +TEST_FUNC_PROTOS(unsigned long long, ulongLong) +TEST_FUNC_PROTOS(float , float ) +TEST_FUNC_PROTOS(double , double ) + +#endif diff --git a/doc/swig/test/Matrix.i b/doc/swig/test/Matrix.i new file mode 100644 index 000000000..e721397a0 --- /dev/null +++ b/doc/swig/test/Matrix.i @@ -0,0 +1,45 @@ +// -*- c++ -*- +%module Matrix + +%{ +#define SWIG_FILE_WITH_INIT +#include "Matrix.h" +%} + +// Get the NumPy typemaps +%include "../numpy.i" + +%init %{ + import_array(); +%} + +%define %apply_numpy_typemaps(TYPE) + +%apply (TYPE IN_ARRAY2[ANY][ANY]) {(TYPE matrix[ANY][ANY])}; +%apply (TYPE* IN_ARRAY2, int DIM1, int DIM2) {(TYPE* matrix, int rows, int cols)}; +%apply (int DIM1, int DIM2, TYPE* IN_ARRAY2) {(int rows, int cols, TYPE* matrix)}; + +%apply (TYPE INPLACE_ARRAY2[ANY][ANY]) {(TYPE array[3][3])}; +%apply (TYPE* INPLACE_ARRAY2, int DIM1, int DIM2) {(TYPE* array, int rows, int cols)}; +%apply (int DIM1, int DIM2, TYPE* INPLACE_ARRAY2) {(int rows, int cols, TYPE* array)}; + +%apply (TYPE ARGOUT_ARRAY2[ANY][ANY]) {(TYPE lower[3][3])}; +%apply (TYPE ARGOUT_ARRAY2[ANY][ANY]) {(TYPE upper[3][3])}; + +%enddef /* %apply_numpy_typemaps() macro */ + +%apply_numpy_typemaps(signed char ) +%apply_numpy_typemaps(unsigned char ) +%apply_numpy_typemaps(short ) +%apply_numpy_typemaps(unsigned short ) +%apply_numpy_typemaps(int ) +%apply_numpy_typemaps(unsigned int ) +%apply_numpy_typemaps(long ) +%apply_numpy_typemaps(unsigned long ) +%apply_numpy_typemaps(long long ) +%apply_numpy_typemaps(unsigned long long) +%apply_numpy_typemaps(float ) +%apply_numpy_typemaps(double ) + +// Include the header file to be wrapped +%include "Matrix.h" diff --git a/doc/swig/test/Tensor.cxx b/doc/swig/test/Tensor.cxx new file mode 100644 index 000000000..dce595291 --- /dev/null +++ b/doc/swig/test/Tensor.cxx @@ -0,0 +1,131 @@ +#include <stdlib.h> +#include <math.h> +#include <iostream> +#include "Tensor.h" + +// The following macro defines a family of functions that work with 3D +// arrays with the forms +// +// TYPE SNAMENorm( TYPE tensor[2][2][2]); +// TYPE SNAMEMax( TYPE * tensor, int rows, int cols, int num); +// TYPE SNAMEMin( int rows, int cols, int num, TYPE * tensor); +// void SNAMEScale( TYPE tensor[3][3][3]); +// void SNAMEFloor( TYPE * array, int rows, int cols, int num, TYPE floor); +// void SNAMECeil( int rows, int cols, int num, TYPE * array, TYPE ceil); +// void SNAMELUSplit(TYPE in[2][2][2], TYPE lower[2][2][2], TYPE upper[2][2][2]); +// +// for any specified type TYPE (for example: short, unsigned int, long +// long, etc.) with given short name SNAME (for example: short, uint, +// longLong, etc.). The macro is then expanded for the given +// TYPE/SNAME pairs. The resulting functions are for testing numpy +// interfaces, respectively, for: +// +// * 3D input arrays, hard-coded length +// * 3D input arrays +// * 3D input arrays, data last +// * 3D in-place arrays, hard-coded lengths +// * 3D in-place arrays +// * 3D in-place arrays, data last +// * 3D argout arrays, hard-coded length +// +#define TEST_FUNCS(TYPE, SNAME) \ +\ +TYPE SNAME ## Norm(TYPE tensor[2][2][2]) { \ + double result = 0; \ + for (int k=0; k<2; ++k) \ + for (int j=0; j<2; ++j) \ + for (int i=0; i<2; ++i) \ + result += tensor[i][j][k] * tensor[i][j][k]; \ + return (TYPE)sqrt(result/8); \ +} \ +\ +TYPE SNAME ## Max(TYPE * tensor, int rows, int cols, int num) { \ + int i, j, k, index; \ + TYPE result = tensor[0]; \ + for (k=0; k<num; ++k) { \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = k*rows*cols + j*rows + i; \ + if (tensor[index] > result) result = tensor[index]; \ + } \ + } \ + } \ + return result; \ +} \ +\ +TYPE SNAME ## Min(int rows, int cols, int num, TYPE * tensor) { \ + int i, j, k, index; \ + TYPE result = tensor[0]; \ + for (k=0; k<num; ++k) { \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = k*rows*cols + j*rows + i; \ + if (tensor[index] < result) result = tensor[index]; \ + } \ + } \ + } \ + return result; \ +} \ +\ +void SNAME ## Scale(TYPE array[3][3][3], TYPE val) { \ + for (int i=0; i<3; ++i) \ + for (int j=0; j<3; ++j) \ + for (int k=0; k<3; ++k) \ + array[i][j][k] *= val; \ +} \ +\ +void SNAME ## Floor(TYPE * array, int rows, int cols, int num, TYPE floor) { \ + int i, j, k, index; \ + for (k=0; k<num; ++k) { \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = k*cols*rows + j*rows + i; \ + if (array[index] < floor) array[index] = floor; \ + } \ + } \ + } \ +} \ +\ +void SNAME ## Ceil(int rows, int cols, int num, TYPE * array, TYPE ceil) { \ + int i, j, k, index; \ + for (k=0; k<num; ++k) { \ + for (j=0; j<cols; ++j) { \ + for (i=0; i<rows; ++i) { \ + index = j*rows + i; \ + if (array[index] > ceil) array[index] = ceil; \ + } \ + } \ + } \ +} \ +\ +void SNAME ## LUSplit(TYPE tensor[2][2][2], TYPE lower[2][2][2], \ + TYPE upper[2][2][2]) { \ + int sum; \ + for (int k=0; k<2; ++k) { \ + for (int j=0; j<2; ++j) { \ + for (int i=0; i<2; ++i) { \ + sum = i + j + k; \ + if (sum < 2) { \ + lower[i][j][k] = tensor[i][j][k]; \ + upper[i][j][k] = 0; \ + } else { \ + upper[i][j][k] = tensor[i][j][k]; \ + lower[i][j][k] = 0; \ + } \ + } \ + } \ + } \ +} + +TEST_FUNCS(signed char , schar ) +TEST_FUNCS(unsigned char , uchar ) +TEST_FUNCS(short , short ) +TEST_FUNCS(unsigned short , ushort ) +TEST_FUNCS(int , int ) +TEST_FUNCS(unsigned int , uint ) +TEST_FUNCS(long , long ) +TEST_FUNCS(unsigned long , ulong ) +TEST_FUNCS(long long , longLong ) +TEST_FUNCS(unsigned long long, ulongLong) +TEST_FUNCS(float , float ) +TEST_FUNCS(double , double ) diff --git a/doc/swig/test/Tensor.h b/doc/swig/test/Tensor.h new file mode 100644 index 000000000..d60eb2d2e --- /dev/null +++ b/doc/swig/test/Tensor.h @@ -0,0 +1,52 @@ +#ifndef TENSOR_H +#define TENSOR_H + +// The following macro defines the prototypes for a family of +// functions that work with 3D arrays with the forms +// +// TYPE SNAMENorm( TYPE tensor[2][2][2]); +// TYPE SNAMEMax( TYPE * tensor, int rows, int cols, int num); +// TYPE SNAMEMin( int rows, int cols, int num, TYPE * tensor); +// void SNAMEScale( TYPE array[3][3][3]); +// void SNAMEFloor( TYPE * array, int rows, int cols, int num, TYPE floor); +// void SNAMECeil( int rows, int cols, int num, TYPE * array, TYPE ceil ); +// void SNAMELUSplit(TYPE in[3][3][3], TYPE lower[3][3][3], TYPE upper[3][3][3]); +// +// for any specified type TYPE (for example: short, unsigned int, long +// long, etc.) with given short name SNAME (for example: short, uint, +// longLong, etc.). The macro is then expanded for the given +// TYPE/SNAME pairs. The resulting functions are for testing numpy +// interfaces, respectively, for: +// +// * 3D input arrays, hard-coded lengths +// * 3D input arrays +// * 3D input arrays, data last +// * 3D in-place arrays, hard-coded lengths +// * 3D in-place arrays +// * 3D in-place arrays, data last +// * 3D argout arrays, hard-coded length +// +#define TEST_FUNC_PROTOS(TYPE, SNAME) \ +\ +TYPE SNAME ## Norm( TYPE tensor[2][2][2]); \ +TYPE SNAME ## Max( TYPE * tensor, int rows, int cols, int num); \ +TYPE SNAME ## Min( int rows, int cols, int num, TYPE * tensor); \ +void SNAME ## Scale( TYPE array[3][3][3], TYPE val); \ +void SNAME ## Floor( TYPE * array, int rows, int cols, int num, TYPE floor); \ +void SNAME ## Ceil( int rows, int cols, int num, TYPE * array, TYPE ceil ); \ +void SNAME ## LUSplit(TYPE tensor[2][2][2], TYPE lower[2][2][2], TYPE upper[2][2][2]); + +TEST_FUNC_PROTOS(signed char , schar ) +TEST_FUNC_PROTOS(unsigned char , uchar ) +TEST_FUNC_PROTOS(short , short ) +TEST_FUNC_PROTOS(unsigned short , ushort ) +TEST_FUNC_PROTOS(int , int ) +TEST_FUNC_PROTOS(unsigned int , uint ) +TEST_FUNC_PROTOS(long , long ) +TEST_FUNC_PROTOS(unsigned long , ulong ) +TEST_FUNC_PROTOS(long long , longLong ) +TEST_FUNC_PROTOS(unsigned long long, ulongLong) +TEST_FUNC_PROTOS(float , float ) +TEST_FUNC_PROTOS(double , double ) + +#endif diff --git a/doc/swig/test/Tensor.i b/doc/swig/test/Tensor.i new file mode 100644 index 000000000..a1198dc9e --- /dev/null +++ b/doc/swig/test/Tensor.i @@ -0,0 +1,49 @@ +// -*- c++ -*- +%module Tensor + +%{ +#define SWIG_FILE_WITH_INIT +#include "Tensor.h" +%} + +// Get the NumPy typemaps +%include "../numpy.i" + +%init %{ + import_array(); +%} + +%define %apply_numpy_typemaps(TYPE) + +%apply (TYPE IN_ARRAY3[ANY][ANY][ANY]) {(TYPE tensor[ANY][ANY][ANY])}; +%apply (TYPE* IN_ARRAY3, int DIM1, int DIM2, int DIM3) + {(TYPE* tensor, int rows, int cols, int num)}; +%apply (int DIM1, int DIM2, int DIM3, TYPE* IN_ARRAY3) + {(int rows, int cols, int num, TYPE* tensor)}; + +%apply (TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) {(TYPE array[3][3][3])}; +%apply (TYPE* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) + {(TYPE* array, int rows, int cols, int num)}; +%apply (int DIM1, int DIM2, int DIM3, TYPE* INPLACE_ARRAY3) + {(int rows, int cols, int num, TYPE* array)}; + +%apply (TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) {(TYPE lower[2][2][2])}; +%apply (TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) {(TYPE upper[2][2][2])}; + +%enddef /* %apply_numpy_typemaps() macro */ + +%apply_numpy_typemaps(signed char ) +%apply_numpy_typemaps(unsigned char ) +%apply_numpy_typemaps(short ) +%apply_numpy_typemaps(unsigned short ) +%apply_numpy_typemaps(int ) +%apply_numpy_typemaps(unsigned int ) +%apply_numpy_typemaps(long ) +%apply_numpy_typemaps(unsigned long ) +%apply_numpy_typemaps(long long ) +%apply_numpy_typemaps(unsigned long long) +%apply_numpy_typemaps(float ) +%apply_numpy_typemaps(double ) + +// Include the header file to be wrapped +%include "Tensor.h" diff --git a/doc/swig/test/Vector.cxx b/doc/swig/test/Vector.cxx new file mode 100644 index 000000000..2c90404da --- /dev/null +++ b/doc/swig/test/Vector.cxx @@ -0,0 +1,100 @@ +#include <stdlib.h> +#include <math.h> +#include <iostream> +#include "Vector.h" + +// The following macro defines a family of functions that work with 1D +// arrays with the forms +// +// TYPE SNAMELength( TYPE vector[3]); +// TYPE SNAMEProd( TYPE * series, int size); +// TYPE SNAMESum( int size, TYPE * series); +// void SNAMEReverse(TYPE array[3]); +// void SNAMEOnes( TYPE * array, int size); +// void SNAMEZeros( int size, TYPE * array); +// void SNAMEEOSplit(TYPE vector[3], TYPE even[3], odd[3]); +// void SNAMETwos( TYPE * twoVec, int size); +// void SNAMEThrees( int size, TYPE * threeVec); +// +// for any specified type TYPE (for example: short, unsigned int, long +// long, etc.) with given short name SNAME (for example: short, uint, +// longLong, etc.). The macro is then expanded for the given +// TYPE/SNAME pairs. The resulting functions are for testing numpy +// interfaces, respectively, for: +// +// * 1D input arrays, hard-coded length +// * 1D input arrays +// * 1D input arrays, data last +// * 1D in-place arrays, hard-coded length +// * 1D in-place arrays +// * 1D in-place arrays, data last +// * 1D argout arrays, hard-coded length +// * 1D argout arrays +// * 1D argout arrays, data last +// +#define TEST_FUNCS(TYPE, SNAME) \ +\ +TYPE SNAME ## Length(TYPE vector[3]) { \ + double result = 0; \ + for (int i=0; i<3; ++i) result += vector[i]*vector[i]; \ + return (TYPE)sqrt(result); \ +} \ +\ +TYPE SNAME ## Prod(TYPE * series, int size) { \ + TYPE result = 1; \ + for (int i=0; i<size; ++i) result *= series[i]; \ + return result; \ +} \ +\ +TYPE SNAME ## Sum(int size, TYPE * series) { \ + TYPE result = 0; \ + for (int i=0; i<size; ++i) result += series[i]; \ + return result; \ +} \ +\ +void SNAME ## Reverse(TYPE array[3]) { \ + TYPE temp = array[0]; \ + array[0] = array[2]; \ + array[2] = temp; \ +} \ +\ +void SNAME ## Ones(TYPE * array, int size) { \ + for (int i=0; i<size; ++i) array[i] = 1; \ +} \ +\ +void SNAME ## Zeros(int size, TYPE * array) { \ + for (int i=0; i<size; ++i) array[i] = 0; \ +} \ +\ +void SNAME ## EOSplit(TYPE vector[3], TYPE even[3], TYPE odd[3]) { \ + for (int i=0; i<3; ++i) { \ + if (i % 2 == 0) { \ + even[i] = vector[i]; \ + odd[ i] = 0; \ + } else { \ + even[i] = 0; \ + odd[ i] = vector[i]; \ + } \ + } \ +} \ +\ +void SNAME ## Twos(TYPE* twoVec, int size) { \ + for (int i=0; i<size; ++i) twoVec[i] = 2; \ +} \ +\ +void SNAME ## Threes(int size, TYPE* threeVec) { \ + for (int i=0; i<size; ++i) threeVec[i] = 3; \ +} + +TEST_FUNCS(signed char , schar ) +TEST_FUNCS(unsigned char , uchar ) +TEST_FUNCS(short , short ) +TEST_FUNCS(unsigned short , ushort ) +TEST_FUNCS(int , int ) +TEST_FUNCS(unsigned int , uint ) +TEST_FUNCS(long , long ) +TEST_FUNCS(unsigned long , ulong ) +TEST_FUNCS(long long , longLong ) +TEST_FUNCS(unsigned long long, ulongLong) +TEST_FUNCS(float , float ) +TEST_FUNCS(double , double ) diff --git a/doc/swig/test/Vector.h b/doc/swig/test/Vector.h new file mode 100644 index 000000000..01da361c6 --- /dev/null +++ b/doc/swig/test/Vector.h @@ -0,0 +1,58 @@ +#ifndef VECTOR_H +#define VECTOR_H + +// The following macro defines the prototypes for a family of +// functions that work with 1D arrays with the forms +// +// TYPE SNAMELength( TYPE vector[3]); +// TYPE SNAMEProd( TYPE * series, int size); +// TYPE SNAMESum( int size, TYPE * series); +// void SNAMEReverse(TYPE array[3]); +// void SNAMEOnes( TYPE * array, int size); +// void SNAMEZeros( int size, TYPE * array); +// void SNAMEEOSplit(TYPE vector[3], TYPE even[3], TYPE odd[3]); +// void SNAMETwos( TYPE * twoVec, int size); +// void SNAMEThrees( int size, TYPE * threeVec); +// +// for any specified type TYPE (for example: short, unsigned int, long +// long, etc.) with given short name SNAME (for example: short, uint, +// longLong, etc.). The macro is then expanded for the given +// TYPE/SNAME pairs. The resulting functions are for testing numpy +// interfaces, respectively, for: +// +// * 1D input arrays, hard-coded length +// * 1D input arrays +// * 1D input arrays, data last +// * 1D in-place arrays, hard-coded length +// * 1D in-place arrays +// * 1D in-place arrays, data last +// * 1D argout arrays, hard-coded length +// * 1D argout arrays +// * 1D argout arrays, data last +// +#define TEST_FUNC_PROTOS(TYPE, SNAME) \ +\ +TYPE SNAME ## Length( TYPE vector[3]); \ +TYPE SNAME ## Prod( TYPE * series, int size); \ +TYPE SNAME ## Sum( int size, TYPE * series); \ +void SNAME ## Reverse(TYPE array[3]); \ +void SNAME ## Ones( TYPE * array, int size); \ +void SNAME ## Zeros( int size, TYPE * array); \ +void SNAME ## EOSplit(TYPE vector[3], TYPE even[3], TYPE odd[3]); \ +void SNAME ## Twos( TYPE * twoVec, int size); \ +void SNAME ## Threes( int size, TYPE * threeVec); \ + +TEST_FUNC_PROTOS(signed char , schar ) +TEST_FUNC_PROTOS(unsigned char , uchar ) +TEST_FUNC_PROTOS(short , short ) +TEST_FUNC_PROTOS(unsigned short , ushort ) +TEST_FUNC_PROTOS(int , int ) +TEST_FUNC_PROTOS(unsigned int , uint ) +TEST_FUNC_PROTOS(long , long ) +TEST_FUNC_PROTOS(unsigned long , ulong ) +TEST_FUNC_PROTOS(long long , longLong ) +TEST_FUNC_PROTOS(unsigned long long, ulongLong) +TEST_FUNC_PROTOS(float , float ) +TEST_FUNC_PROTOS(double , double ) + +#endif diff --git a/doc/swig/test/Vector.i b/doc/swig/test/Vector.i new file mode 100644 index 000000000..e86f21c37 --- /dev/null +++ b/doc/swig/test/Vector.i @@ -0,0 +1,47 @@ +// -*- c++ -*- +%module Vector + +%{ +#define SWIG_FILE_WITH_INIT +#include "Vector.h" +%} + +// Get the NumPy typemaps +%include "../numpy.i" + +%init %{ + import_array(); +%} + +%define %apply_numpy_typemaps(TYPE) + +%apply (TYPE IN_ARRAY1[ANY]) {(TYPE vector[3])}; +%apply (TYPE* IN_ARRAY1, int DIM1) {(TYPE* series, int size)}; +%apply (int DIM1, TYPE* IN_ARRAY1) {(int size, TYPE* series)}; + +%apply (TYPE INPLACE_ARRAY1[ANY]) {(TYPE array[3])}; +%apply (TYPE* INPLACE_ARRAY1, int DIM1) {(TYPE* array, int size)}; +%apply (int DIM1, TYPE* INPLACE_ARRAY1) {(int size, TYPE* array)}; + +%apply (TYPE ARGOUT_ARRAY1[ANY]) {(TYPE even[3])}; +%apply (TYPE ARGOUT_ARRAY1[ANY]) {(TYPE odd[ 3])}; +%apply (TYPE* ARGOUT_ARRAY1, int DIM1) {(TYPE* twoVec, int size)}; +%apply (int DIM1, TYPE* ARGOUT_ARRAY1) {(int size, TYPE* threeVec)}; + +%enddef /* %apply_numpy_typemaps() macro */ + +%apply_numpy_typemaps(signed char ) +%apply_numpy_typemaps(unsigned char ) +%apply_numpy_typemaps(short ) +%apply_numpy_typemaps(unsigned short ) +%apply_numpy_typemaps(int ) +%apply_numpy_typemaps(unsigned int ) +%apply_numpy_typemaps(long ) +%apply_numpy_typemaps(unsigned long ) +%apply_numpy_typemaps(long long ) +%apply_numpy_typemaps(unsigned long long) +%apply_numpy_typemaps(float ) +%apply_numpy_typemaps(double ) + +// Include the header file to be wrapped +%include "Vector.h" diff --git a/doc/swig/test/setup.py b/doc/swig/test/setup.py new file mode 100755 index 000000000..fadf8b5cd --- /dev/null +++ b/doc/swig/test/setup.py @@ -0,0 +1,66 @@ +#! /usr/bin/env python + +# System imports +from distutils.core import * +from distutils import sysconfig + +# Third-party modules - we depend on numpy for everything +import numpy + +# Obtain the numpy include directory. This logic works across numpy versions. +try: + numpy_include = numpy.get_include() +except AttributeError: + numpy_include = numpy.get_numpy_include() + +# Array extension module +_Array = Extension("_Array", + ["Array_wrap.cxx", + "Array1.cxx", + "Array2.cxx"], + include_dirs = [numpy_include], + ) + +# Farray extension module +_Farray = Extension("_Farray", + ["Farray_wrap.cxx", + "Farray.cxx"], + include_dirs = [numpy_include], + ) + +# _Vector extension module +_Vector = Extension("_Vector", + ["Vector_wrap.cxx", + "Vector.cxx"], + include_dirs = [numpy_include], + ) + +# _Matrix extension module +_Matrix = Extension("_Matrix", + ["Matrix_wrap.cxx", + "Matrix.cxx"], + include_dirs = [numpy_include], + ) + +# _Tensor extension module +_Tensor = Extension("_Tensor", + ["Tensor_wrap.cxx", + "Tensor.cxx"], + include_dirs = [numpy_include], + ) + +_Fortran = Extension("_Fortran", + ["Fortran_wrap.cxx", + "Fortran.cxx"], + include_dirs = [numpy_include], + ) + +# NumyTypemapTests setup +setup(name = "NumpyTypemapTests", + description = "Functions that work on arrays", + author = "Bill Spotz", + py_modules = ["Array", "Farray", "Vector", "Matrix", "Tensor", + "Fortran"], + ext_modules = [_Array , _Farray , _Vector , _Matrix , _Tensor, + _Fortran] + ) diff --git a/doc/swig/test/testArray.py b/doc/swig/test/testArray.py new file mode 100755 index 000000000..ba83d14d9 --- /dev/null +++ b/doc/swig/test/testArray.py @@ -0,0 +1,283 @@ +#! /usr/bin/env python + +# System imports +from distutils.util import get_platform +import os +import sys +import unittest + +# Import NumPy +import numpy as np +major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] +if major == 0: + BadListError = TypeError +else: + BadListError = ValueError + +import Array + +###################################################################### + +class Array1TestCase(unittest.TestCase): + + def setUp(self): + self.length = 5 + self.array1 = Array.Array1(self.length) + + def testConstructor0(self): + "Test Array1 default constructor" + a = Array.Array1() + self.failUnless(isinstance(a, Array.Array1)) + self.failUnless(len(a) == 0) + + def testConstructor1(self): + "Test Array1 length constructor" + self.failUnless(isinstance(self.array1, Array.Array1)) + + def testConstructor2(self): + "Test Array1 array constructor" + na = np.arange(self.length) + aa = Array.Array1(na) + self.failUnless(isinstance(aa, Array.Array1)) + + def testConstructor3(self): + "Test Array1 copy constructor" + for i in range(self.array1.length()): self.array1[i] = i + arrayCopy = Array.Array1(self.array1) + self.failUnless(arrayCopy == self.array1) + + def testConstructorBad(self): + "Test Array1 length constructor, negative" + self.assertRaises(ValueError, Array.Array1, -4) + + def testLength(self): + "Test Array1 length method" + self.failUnless(self.array1.length() == self.length) + + def testLen(self): + "Test Array1 __len__ method" + self.failUnless(len(self.array1) == self.length) + + def testResize0(self): + "Test Array1 resize method, length" + newLen = 2 * self.length + self.array1.resize(newLen) + self.failUnless(len(self.array1) == newLen) + + def testResize1(self): + "Test Array1 resize method, array" + a = np.zeros((2*self.length,), dtype='l') + self.array1.resize(a) + self.failUnless(len(self.array1) == len(a)) + + def testResizeBad(self): + "Test Array1 resize method, negative length" + self.assertRaises(ValueError, self.array1.resize, -5) + + def testSetGet(self): + "Test Array1 __setitem__, __getitem__ methods" + n = self.length + for i in range(n): + self.array1[i] = i*i + for i in range(n): + self.failUnless(self.array1[i] == i*i) + + def testSetBad1(self): + "Test Array1 __setitem__ method, negative index" + self.assertRaises(IndexError, self.array1.__setitem__, -1, 0) + + def testSetBad2(self): + "Test Array1 __setitem__ method, out-of-range index" + self.assertRaises(IndexError, self.array1.__setitem__, self.length+1, 0) + + def testGetBad1(self): + "Test Array1 __getitem__ method, negative index" + self.assertRaises(IndexError, self.array1.__getitem__, -1) + + def testGetBad2(self): + "Test Array1 __getitem__ method, out-of-range index" + self.assertRaises(IndexError, self.array1.__getitem__, self.length+1) + + def testAsString(self): + "Test Array1 asString method" + for i in range(self.array1.length()): self.array1[i] = i+1 + self.failUnless(self.array1.asString() == "[ 1, 2, 3, 4, 5 ]") + + def testStr(self): + "Test Array1 __str__ method" + for i in range(self.array1.length()): self.array1[i] = i-2 + self.failUnless(str(self.array1) == "[ -2, -1, 0, 1, 2 ]") + + def testView(self): + "Test Array1 view method" + for i in range(self.array1.length()): self.array1[i] = i+1 + a = self.array1.view() + self.failUnless(isinstance(a, np.ndarray)) + self.failUnless(len(a) == self.length) + self.failUnless((a == [1,2,3,4,5]).all()) + +###################################################################### + +class Array2TestCase(unittest.TestCase): + + def setUp(self): + self.nrows = 5 + self.ncols = 4 + self.array2 = Array.Array2(self.nrows, self.ncols) + + def testConstructor0(self): + "Test Array2 default constructor" + a = Array.Array2() + self.failUnless(isinstance(a, Array.Array2)) + self.failUnless(len(a) == 0) + + def testConstructor1(self): + "Test Array2 nrows, ncols constructor" + self.failUnless(isinstance(self.array2, Array.Array2)) + + def testConstructor2(self): + "Test Array2 array constructor" + na = np.zeros((3,4), dtype="l") + aa = Array.Array2(na) + self.failUnless(isinstance(aa, Array.Array2)) + + def testConstructor3(self): + "Test Array2 copy constructor" + for i in range(self.nrows): + for j in range(self.ncols): + self.array2[i][j] = i * j + arrayCopy = Array.Array2(self.array2) + self.failUnless(arrayCopy == self.array2) + + def testConstructorBad1(self): + "Test Array2 nrows, ncols constructor, negative nrows" + self.assertRaises(ValueError, Array.Array2, -4, 4) + + def testConstructorBad2(self): + "Test Array2 nrows, ncols constructor, negative ncols" + self.assertRaises(ValueError, Array.Array2, 4, -4) + + def testNrows(self): + "Test Array2 nrows method" + self.failUnless(self.array2.nrows() == self.nrows) + + def testNcols(self): + "Test Array2 ncols method" + self.failUnless(self.array2.ncols() == self.ncols) + + def testLen(self): + "Test Array2 __len__ method" + self.failUnless(len(self.array2) == self.nrows*self.ncols) + + def testResize0(self): + "Test Array2 resize method, size" + newRows = 2 * self.nrows + newCols = 2 * self.ncols + self.array2.resize(newRows, newCols) + self.failUnless(len(self.array2) == newRows * newCols) + + #def testResize1(self): + # "Test Array2 resize method, array" + # a = np.zeros((2*self.nrows, 2*self.ncols), dtype='l') + # self.array2.resize(a) + # self.failUnless(len(self.array2) == len(a)) + + def testResizeBad1(self): + "Test Array2 resize method, negative nrows" + self.assertRaises(ValueError, self.array2.resize, -5, 5) + + def testResizeBad2(self): + "Test Array2 resize method, negative ncols" + self.assertRaises(ValueError, self.array2.resize, 5, -5) + + def testSetGet1(self): + "Test Array2 __setitem__, __getitem__ methods" + m = self.nrows + n = self.ncols + array1 = [ ] + a = np.arange(n, dtype="l") + for i in range(m): + array1.append(Array.Array1(i*a)) + for i in range(m): + self.array2[i] = array1[i] + for i in range(m): + self.failUnless(self.array2[i] == array1[i]) + + def testSetGet2(self): + "Test Array2 chained __setitem__, __getitem__ methods" + m = self.nrows + n = self.ncols + for i in range(m): + for j in range(n): + self.array2[i][j] = i*j + for i in range(m): + for j in range(n): + self.failUnless(self.array2[i][j] == i*j) + + def testSetBad1(self): + "Test Array2 __setitem__ method, negative index" + a = Array.Array1(self.ncols) + self.assertRaises(IndexError, self.array2.__setitem__, -1, a) + + def testSetBad2(self): + "Test Array2 __setitem__ method, out-of-range index" + a = Array.Array1(self.ncols) + self.assertRaises(IndexError, self.array2.__setitem__, self.nrows+1, a) + + def testGetBad1(self): + "Test Array2 __getitem__ method, negative index" + self.assertRaises(IndexError, self.array2.__getitem__, -1) + + def testGetBad2(self): + "Test Array2 __getitem__ method, out-of-range index" + self.assertRaises(IndexError, self.array2.__getitem__, self.nrows+1) + + def testAsString(self): + "Test Array2 asString method" + result = """\ +[ [ 0, 1, 2, 3 ], + [ 1, 2, 3, 4 ], + [ 2, 3, 4, 5 ], + [ 3, 4, 5, 6 ], + [ 4, 5, 6, 7 ] ] +""" + for i in range(self.nrows): + for j in range(self.ncols): + self.array2[i][j] = i+j + self.failUnless(self.array2.asString() == result) + + def testStr(self): + "Test Array2 __str__ method" + result = """\ +[ [ 0, -1, -2, -3 ], + [ 1, 0, -1, -2 ], + [ 2, 1, 0, -1 ], + [ 3, 2, 1, 0 ], + [ 4, 3, 2, 1 ] ] +""" + for i in range(self.nrows): + for j in range(self.ncols): + self.array2[i][j] = i-j + self.failUnless(str(self.array2) == result) + + def testView(self): + "Test Array2 view method" + a = self.array2.view() + self.failUnless(isinstance(a, np.ndarray)) + self.failUnless(len(a) == self.nrows) + +###################################################################### + +if __name__ == "__main__": + + # Build the test suite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(Array1TestCase)) + suite.addTest(unittest.makeSuite(Array2TestCase)) + + # Execute the test suite + print "Testing Classes of Module Array" + print "NumPy version", np.__version__ + print + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(len(result.errors) + len(result.failures)) diff --git a/doc/swig/test/testFarray.py b/doc/swig/test/testFarray.py new file mode 100755 index 000000000..614e149bd --- /dev/null +++ b/doc/swig/test/testFarray.py @@ -0,0 +1,158 @@ +#! /usr/bin/env python + +# System imports +from distutils.util import get_platform +import os +import sys +import unittest + +# Import NumPy +import numpy as np +major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] +if major == 0: BadListError = TypeError +else: BadListError = ValueError + +# Add the distutils-generated build directory to the python search path and then +# import the extension module +libDir = "lib.%s-%s" % (get_platform(), sys.version[:3]) +sys.path.insert(0,os.path.join("build", libDir)) +import Farray + +###################################################################### + +class FarrayTestCase(unittest.TestCase): + + def setUp(self): + self.nrows = 5 + self.ncols = 4 + self.array = Farray.Farray(self.nrows, self.ncols) + + def testConstructor1(self): + "Test Farray size constructor" + self.failUnless(isinstance(self.array, Farray.Farray)) + + def testConstructor2(self): + "Test Farray copy constructor" + for i in range(self.nrows): + for j in range(self.ncols): + self.array[i,j] = i + j + arrayCopy = Farray.Farray(self.array) + self.failUnless(arrayCopy == self.array) + + def testConstructorBad1(self): + "Test Farray size constructor, negative nrows" + self.assertRaises(ValueError, Farray.Farray, -4, 4) + + def testConstructorBad2(self): + "Test Farray size constructor, negative ncols" + self.assertRaises(ValueError, Farray.Farray, 4, -4) + + def testNrows(self): + "Test Farray nrows method" + self.failUnless(self.array.nrows() == self.nrows) + + def testNcols(self): + "Test Farray ncols method" + self.failUnless(self.array.ncols() == self.ncols) + + def testLen(self): + "Test Farray __len__ method" + self.failUnless(len(self.array) == self.nrows*self.ncols) + + def testSetGet(self): + "Test Farray __setitem__, __getitem__ methods" + m = self.nrows + n = self.ncols + for i in range(m): + for j in range(n): + self.array[i,j] = i*j + for i in range(m): + for j in range(n): + self.failUnless(self.array[i,j] == i*j) + + def testSetBad1(self): + "Test Farray __setitem__ method, negative row" + self.assertRaises(IndexError, self.array.__setitem__, (-1, 3), 0) + + def testSetBad2(self): + "Test Farray __setitem__ method, negative col" + self.assertRaises(IndexError, self.array.__setitem__, (1, -3), 0) + + def testSetBad3(self): + "Test Farray __setitem__ method, out-of-range row" + self.assertRaises(IndexError, self.array.__setitem__, (self.nrows+1, 0), 0) + + def testSetBad4(self): + "Test Farray __setitem__ method, out-of-range col" + self.assertRaises(IndexError, self.array.__setitem__, (0, self.ncols+1), 0) + + def testGetBad1(self): + "Test Farray __getitem__ method, negative row" + self.assertRaises(IndexError, self.array.__getitem__, (-1, 3)) + + def testGetBad2(self): + "Test Farray __getitem__ method, negative col" + self.assertRaises(IndexError, self.array.__getitem__, (1, -3)) + + def testGetBad3(self): + "Test Farray __getitem__ method, out-of-range row" + self.assertRaises(IndexError, self.array.__getitem__, (self.nrows+1, 0)) + + def testGetBad4(self): + "Test Farray __getitem__ method, out-of-range col" + self.assertRaises(IndexError, self.array.__getitem__, (0, self.ncols+1)) + + def testAsString(self): + "Test Farray asString method" + result = """\ +[ [ 0, 1, 2, 3 ], + [ 1, 2, 3, 4 ], + [ 2, 3, 4, 5 ], + [ 3, 4, 5, 6 ], + [ 4, 5, 6, 7 ] ] +""" + for i in range(self.nrows): + for j in range(self.ncols): + self.array[i,j] = i+j + self.failUnless(self.array.asString() == result) + + def testStr(self): + "Test Farray __str__ method" + result = """\ +[ [ 0, -1, -2, -3 ], + [ 1, 0, -1, -2 ], + [ 2, 1, 0, -1 ], + [ 3, 2, 1, 0 ], + [ 4, 3, 2, 1 ] ] +""" + for i in range(self.nrows): + for j in range(self.ncols): + self.array[i,j] = i-j + self.failUnless(str(self.array) == result) + + def testView(self): + "Test Farray view method" + for i in range(self.nrows): + for j in range(self.ncols): + self.array[i,j] = i+j + a = self.array.view() + self.failUnless(isinstance(a, np.ndarray)) + self.failUnless(a.flags.f_contiguous) + for i in range(self.nrows): + for j in range(self.ncols): + self.failUnless(a[i,j] == i+j) + +###################################################################### + +if __name__ == "__main__": + + # Build the test suite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(FarrayTestCase)) + + # Execute the test suite + print "Testing Classes of Module Farray" + print "NumPy version", np.__version__ + print + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(len(result.errors) + len(result.failures)) diff --git a/doc/swig/test/testFortran.py b/doc/swig/test/testFortran.py new file mode 100644 index 000000000..d2c382869 --- /dev/null +++ b/doc/swig/test/testFortran.py @@ -0,0 +1,169 @@ +#! /usr/bin/env python + +# System imports +from distutils.util import get_platform +import os +import sys +import unittest + +# Import NumPy +import numpy as np +major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] +if major == 0: BadListError = TypeError +else: BadListError = ValueError + +import Fortran + +###################################################################### + +class FortranTestCase(unittest.TestCase): + + def __init__(self, methodName="runTests"): + unittest.TestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + + # Test (type* IN_FARRAY2, int DIM1, int DIM2) typemap + def testSecondElementContiguous(self): + "Test luSplit function with a Fortran-array" + print >>sys.stderr, self.typeStr, "... ", + second = Fortran.__dict__[self.typeStr + "SecondElement"] + matrix = np.arange(9).reshape(3, 3).astype(self.typeCode) + self.assertEquals(second(matrix), 3) + + def testSecondElementFortran(self): + "Test luSplit function with a Fortran-array" + print >>sys.stderr, self.typeStr, "... ", + second = Fortran.__dict__[self.typeStr + "SecondElement"] + matrix = np.asfortranarray(np.arange(9).reshape(3, 3), + self.typeCode) + self.assertEquals(second(matrix), 3) + + def testSecondElementObject(self): + "Test luSplit function with a Fortran-array" + print >>sys.stderr, self.typeStr, "... ", + second = Fortran.__dict__[self.typeStr + "SecondElement"] + matrix = np.asfortranarray([[0,1,2],[3,4,5],[6,7,8]], self.typeCode) + self.assertEquals(second(matrix), 3) + +###################################################################### + +class scharTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "schar" + self.typeCode = "b" + +###################################################################### + +class ucharTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "uchar" + self.typeCode = "B" + +###################################################################### + +class shortTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "short" + self.typeCode = "h" + +###################################################################### + +class ushortTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "ushort" + self.typeCode = "H" + +###################################################################### + +class intTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "int" + self.typeCode = "i" + +###################################################################### + +class uintTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "uint" + self.typeCode = "I" + +###################################################################### + +class longTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "long" + self.typeCode = "l" + +###################################################################### + +class ulongTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "ulong" + self.typeCode = "L" + +###################################################################### + +class longLongTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "longLong" + self.typeCode = "q" + +###################################################################### + +class ulongLongTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "ulongLong" + self.typeCode = "Q" + +###################################################################### + +class floatTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "float" + self.typeCode = "f" + +###################################################################### + +class doubleTestCase(FortranTestCase): + def __init__(self, methodName="runTest"): + FortranTestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + +###################################################################### + +if __name__ == "__main__": + + # Build the test suite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite( scharTestCase)) + suite.addTest(unittest.makeSuite( ucharTestCase)) + suite.addTest(unittest.makeSuite( shortTestCase)) + suite.addTest(unittest.makeSuite( ushortTestCase)) + suite.addTest(unittest.makeSuite( intTestCase)) + suite.addTest(unittest.makeSuite( uintTestCase)) + suite.addTest(unittest.makeSuite( longTestCase)) + suite.addTest(unittest.makeSuite( ulongTestCase)) + suite.addTest(unittest.makeSuite( longLongTestCase)) + suite.addTest(unittest.makeSuite(ulongLongTestCase)) + suite.addTest(unittest.makeSuite( floatTestCase)) + suite.addTest(unittest.makeSuite( doubleTestCase)) + + # Execute the test suite + print "Testing 2D Functions of Module Matrix" + print "NumPy version", np.__version__ + print + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(len(result.errors) + len(result.failures)) diff --git a/doc/swig/test/testMatrix.py b/doc/swig/test/testMatrix.py new file mode 100755 index 000000000..12061702d --- /dev/null +++ b/doc/swig/test/testMatrix.py @@ -0,0 +1,361 @@ +#! /usr/bin/env python + +# System imports +from distutils.util import get_platform +import os +import sys +import unittest + +# Import NumPy +import numpy as np +major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] +if major == 0: BadListError = TypeError +else: BadListError = ValueError + +import Matrix + +###################################################################### + +class MatrixTestCase(unittest.TestCase): + + def __init__(self, methodName="runTests"): + unittest.TestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + + # Test (type IN_ARRAY2[ANY][ANY]) typemap + def testDet(self): + "Test det function" + print >>sys.stderr, self.typeStr, "... ", + det = Matrix.__dict__[self.typeStr + "Det"] + matrix = [[8,7],[6,9]] + self.assertEquals(det(matrix), 30) + + # Test (type IN_ARRAY2[ANY][ANY]) typemap + def testDetBadList(self): + "Test det function with bad list" + print >>sys.stderr, self.typeStr, "... ", + det = Matrix.__dict__[self.typeStr + "Det"] + matrix = [[8,7], ["e", "pi"]] + self.assertRaises(BadListError, det, matrix) + + # Test (type IN_ARRAY2[ANY][ANY]) typemap + def testDetWrongDim(self): + "Test det function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + det = Matrix.__dict__[self.typeStr + "Det"] + matrix = [8,7] + self.assertRaises(TypeError, det, matrix) + + # Test (type IN_ARRAY2[ANY][ANY]) typemap + def testDetWrongSize(self): + "Test det function with wrong size" + print >>sys.stderr, self.typeStr, "... ", + det = Matrix.__dict__[self.typeStr + "Det"] + matrix = [[8,7,6], [5,4,3], [2,1,0]] + self.assertRaises(TypeError, det, matrix) + + # Test (type IN_ARRAY2[ANY][ANY]) typemap + def testDetNonContainer(self): + "Test det function with non-container" + print >>sys.stderr, self.typeStr, "... ", + det = Matrix.__dict__[self.typeStr + "Det"] + self.assertRaises(TypeError, det, None) + + # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap + def testMax(self): + "Test max function" + print >>sys.stderr, self.typeStr, "... ", + max = Matrix.__dict__[self.typeStr + "Max"] + matrix = [[6,5,4],[3,2,1]] + self.assertEquals(max(matrix), 6) + + # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap + def testMaxBadList(self): + "Test max function with bad list" + print >>sys.stderr, self.typeStr, "... ", + max = Matrix.__dict__[self.typeStr + "Max"] + matrix = [[6,"five",4], ["three", 2, "one"]] + self.assertRaises(BadListError, max, matrix) + + # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap + def testMaxNonContainer(self): + "Test max function with non-container" + print >>sys.stderr, self.typeStr, "... ", + max = Matrix.__dict__[self.typeStr + "Max"] + self.assertRaises(TypeError, max, None) + + # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap + def testMaxWrongDim(self): + "Test max function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + max = Matrix.__dict__[self.typeStr + "Max"] + self.assertRaises(TypeError, max, [0, 1, 2, 3]) + + # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap + def testMin(self): + "Test min function" + print >>sys.stderr, self.typeStr, "... ", + min = Matrix.__dict__[self.typeStr + "Min"] + matrix = [[9,8],[7,6],[5,4]] + self.assertEquals(min(matrix), 4) + + # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap + def testMinBadList(self): + "Test min function with bad list" + print >>sys.stderr, self.typeStr, "... ", + min = Matrix.__dict__[self.typeStr + "Min"] + matrix = [["nine","eight"], ["seven","six"]] + self.assertRaises(BadListError, min, matrix) + + # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap + def testMinWrongDim(self): + "Test min function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + min = Matrix.__dict__[self.typeStr + "Min"] + self.assertRaises(TypeError, min, [1,3,5,7,9]) + + # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap + def testMinNonContainer(self): + "Test min function with non-container" + print >>sys.stderr, self.typeStr, "... ", + min = Matrix.__dict__[self.typeStr + "Min"] + self.assertRaises(TypeError, min, False) + + # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap + def testScale(self): + "Test scale function" + print >>sys.stderr, self.typeStr, "... ", + scale = Matrix.__dict__[self.typeStr + "Scale"] + matrix = np.array([[1,2,3],[2,1,2],[3,2,1]],self.typeCode) + scale(matrix,4) + self.assertEquals((matrix == [[4,8,12],[8,4,8],[12,8,4]]).all(), True) + + # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap + def testScaleWrongDim(self): + "Test scale function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + scale = Matrix.__dict__[self.typeStr + "Scale"] + matrix = np.array([1,2,2,1],self.typeCode) + self.assertRaises(TypeError, scale, matrix) + + # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap + def testScaleWrongSize(self): + "Test scale function with wrong size" + print >>sys.stderr, self.typeStr, "... ", + scale = Matrix.__dict__[self.typeStr + "Scale"] + matrix = np.array([[1,2],[2,1]],self.typeCode) + self.assertRaises(TypeError, scale, matrix) + + # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap + def testScaleWrongType(self): + "Test scale function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + scale = Matrix.__dict__[self.typeStr + "Scale"] + matrix = np.array([[1,2,3],[2,1,2],[3,2,1]],'c') + self.assertRaises(TypeError, scale, matrix) + + # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap + def testScaleNonArray(self): + "Test scale function with non-array" + print >>sys.stderr, self.typeStr, "... ", + scale = Matrix.__dict__[self.typeStr + "Scale"] + matrix = [[1,2,3],[2,1,2],[3,2,1]] + self.assertRaises(TypeError, scale, matrix) + + # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap + def testFloor(self): + "Test floor function" + print >>sys.stderr, self.typeStr, "... ", + floor = Matrix.__dict__[self.typeStr + "Floor"] + matrix = np.array([[6,7],[8,9]],self.typeCode) + floor(matrix,7) + np.testing.assert_array_equal(matrix, np.array([[7,7],[8,9]])) + + # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap + def testFloorWrongDim(self): + "Test floor function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + floor = Matrix.__dict__[self.typeStr + "Floor"] + matrix = np.array([6,7,8,9],self.typeCode) + self.assertRaises(TypeError, floor, matrix) + + # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap + def testFloorWrongType(self): + "Test floor function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + floor = Matrix.__dict__[self.typeStr + "Floor"] + matrix = np.array([[6,7], [8,9]],'c') + self.assertRaises(TypeError, floor, matrix) + + # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap + def testFloorNonArray(self): + "Test floor function with non-array" + print >>sys.stderr, self.typeStr, "... ", + floor = Matrix.__dict__[self.typeStr + "Floor"] + matrix = [[6,7], [8,9]] + self.assertRaises(TypeError, floor, matrix) + + # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap + def testCeil(self): + "Test ceil function" + print >>sys.stderr, self.typeStr, "... ", + ceil = Matrix.__dict__[self.typeStr + "Ceil"] + matrix = np.array([[1,2],[3,4]],self.typeCode) + ceil(matrix,3) + np.testing.assert_array_equal(matrix, np.array([[1,2],[3,3]])) + + # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap + def testCeilWrongDim(self): + "Test ceil function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + ceil = Matrix.__dict__[self.typeStr + "Ceil"] + matrix = np.array([1,2,3,4],self.typeCode) + self.assertRaises(TypeError, ceil, matrix) + + # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap + def testCeilWrongType(self): + "Test ceil function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + ceil = Matrix.__dict__[self.typeStr + "Ceil"] + matrix = np.array([[1,2], [3,4]],'c') + self.assertRaises(TypeError, ceil, matrix) + + # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap + def testCeilNonArray(self): + "Test ceil function with non-array" + print >>sys.stderr, self.typeStr, "... ", + ceil = Matrix.__dict__[self.typeStr + "Ceil"] + matrix = [[1,2], [3,4]] + self.assertRaises(TypeError, ceil, matrix) + + # Test (type ARGOUT_ARRAY2[ANY][ANY]) typemap + def testLUSplit(self): + "Test luSplit function" + print >>sys.stderr, self.typeStr, "... ", + luSplit = Matrix.__dict__[self.typeStr + "LUSplit"] + lower, upper = luSplit([[1,2,3],[4,5,6],[7,8,9]]) + self.assertEquals((lower == [[1,0,0],[4,5,0],[7,8,9]]).all(), True) + self.assertEquals((upper == [[0,2,3],[0,0,6],[0,0,0]]).all(), True) + +###################################################################### + +class scharTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "schar" + self.typeCode = "b" + +###################################################################### + +class ucharTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "uchar" + self.typeCode = "B" + +###################################################################### + +class shortTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "short" + self.typeCode = "h" + +###################################################################### + +class ushortTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "ushort" + self.typeCode = "H" + +###################################################################### + +class intTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "int" + self.typeCode = "i" + +###################################################################### + +class uintTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "uint" + self.typeCode = "I" + +###################################################################### + +class longTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "long" + self.typeCode = "l" + +###################################################################### + +class ulongTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "ulong" + self.typeCode = "L" + +###################################################################### + +class longLongTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "longLong" + self.typeCode = "q" + +###################################################################### + +class ulongLongTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "ulongLong" + self.typeCode = "Q" + +###################################################################### + +class floatTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "float" + self.typeCode = "f" + +###################################################################### + +class doubleTestCase(MatrixTestCase): + def __init__(self, methodName="runTest"): + MatrixTestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + +###################################################################### + +if __name__ == "__main__": + + # Build the test suite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite( scharTestCase)) + suite.addTest(unittest.makeSuite( ucharTestCase)) + suite.addTest(unittest.makeSuite( shortTestCase)) + suite.addTest(unittest.makeSuite( ushortTestCase)) + suite.addTest(unittest.makeSuite( intTestCase)) + suite.addTest(unittest.makeSuite( uintTestCase)) + suite.addTest(unittest.makeSuite( longTestCase)) + suite.addTest(unittest.makeSuite( ulongTestCase)) + suite.addTest(unittest.makeSuite( longLongTestCase)) + suite.addTest(unittest.makeSuite(ulongLongTestCase)) + suite.addTest(unittest.makeSuite( floatTestCase)) + suite.addTest(unittest.makeSuite( doubleTestCase)) + + # Execute the test suite + print "Testing 2D Functions of Module Matrix" + print "NumPy version", np.__version__ + print + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(len(result.errors) + len(result.failures)) diff --git a/doc/swig/test/testTensor.py b/doc/swig/test/testTensor.py new file mode 100755 index 000000000..3d0ce097e --- /dev/null +++ b/doc/swig/test/testTensor.py @@ -0,0 +1,401 @@ +#! /usr/bin/env python + +# System imports +from distutils.util import get_platform +from math import sqrt +import os +import sys +import unittest + +# Import NumPy +import numpy as np +major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] +if major == 0: BadListError = TypeError +else: BadListError = ValueError + +import Tensor + +###################################################################### + +class TensorTestCase(unittest.TestCase): + + def __init__(self, methodName="runTests"): + unittest.TestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + self.result = sqrt(28.0/8) + + # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap + def testNorm(self): + "Test norm function" + print >>sys.stderr, self.typeStr, "... ", + norm = Tensor.__dict__[self.typeStr + "Norm"] + tensor = [[[0,1], [2,3]], + [[3,2], [1,0]]] + if isinstance(self.result, int): + self.assertEquals(norm(tensor), self.result) + else: + self.assertAlmostEqual(norm(tensor), self.result, 6) + + # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap + def testNormBadList(self): + "Test norm function with bad list" + print >>sys.stderr, self.typeStr, "... ", + norm = Tensor.__dict__[self.typeStr + "Norm"] + tensor = [[[0,"one"],[2,3]], + [[3,"two"],[1,0]]] + self.assertRaises(BadListError, norm, tensor) + + # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap + def testNormWrongDim(self): + "Test norm function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + norm = Tensor.__dict__[self.typeStr + "Norm"] + tensor = [[0,1,2,3], + [3,2,1,0]] + self.assertRaises(TypeError, norm, tensor) + + # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap + def testNormWrongSize(self): + "Test norm function with wrong size" + print >>sys.stderr, self.typeStr, "... ", + norm = Tensor.__dict__[self.typeStr + "Norm"] + tensor = [[[0,1,0], [2,3,2]], + [[3,2,3], [1,0,1]]] + self.assertRaises(TypeError, norm, tensor) + + # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap + def testNormNonContainer(self): + "Test norm function with non-container" + print >>sys.stderr, self.typeStr, "... ", + norm = Tensor.__dict__[self.typeStr + "Norm"] + self.assertRaises(TypeError, norm, None) + + # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testMax(self): + "Test max function" + print >>sys.stderr, self.typeStr, "... ", + max = Tensor.__dict__[self.typeStr + "Max"] + tensor = [[[1,2], [3,4]], + [[5,6], [7,8]]] + self.assertEquals(max(tensor), 8) + + # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testMaxBadList(self): + "Test max function with bad list" + print >>sys.stderr, self.typeStr, "... ", + max = Tensor.__dict__[self.typeStr + "Max"] + tensor = [[[1,"two"], [3,4]], + [[5,"six"], [7,8]]] + self.assertRaises(BadListError, max, tensor) + + # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testMaxNonContainer(self): + "Test max function with non-container" + print >>sys.stderr, self.typeStr, "... ", + max = Tensor.__dict__[self.typeStr + "Max"] + self.assertRaises(TypeError, max, None) + + # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testMaxWrongDim(self): + "Test max function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + max = Tensor.__dict__[self.typeStr + "Max"] + self.assertRaises(TypeError, max, [0, -1, 2, -3]) + + # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap + def testMin(self): + "Test min function" + print >>sys.stderr, self.typeStr, "... ", + min = Tensor.__dict__[self.typeStr + "Min"] + tensor = [[[9,8], [7,6]], + [[5,4], [3,2]]] + self.assertEquals(min(tensor), 2) + + # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap + def testMinBadList(self): + "Test min function with bad list" + print >>sys.stderr, self.typeStr, "... ", + min = Tensor.__dict__[self.typeStr + "Min"] + tensor = [[["nine",8], [7,6]], + [["five",4], [3,2]]] + self.assertRaises(BadListError, min, tensor) + + # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap + def testMinNonContainer(self): + "Test min function with non-container" + print >>sys.stderr, self.typeStr, "... ", + min = Tensor.__dict__[self.typeStr + "Min"] + self.assertRaises(TypeError, min, True) + + # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap + def testMinWrongDim(self): + "Test min function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + min = Tensor.__dict__[self.typeStr + "Min"] + self.assertRaises(TypeError, min, [[1,3],[5,7]]) + + # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap + def testScale(self): + "Test scale function" + print >>sys.stderr, self.typeStr, "... ", + scale = Tensor.__dict__[self.typeStr + "Scale"] + tensor = np.array([[[1,0,1], [0,1,0], [1,0,1]], + [[0,1,0], [1,0,1], [0,1,0]], + [[1,0,1], [0,1,0], [1,0,1]]],self.typeCode) + scale(tensor,4) + self.assertEquals((tensor == [[[4,0,4], [0,4,0], [4,0,4]], + [[0,4,0], [4,0,4], [0,4,0]], + [[4,0,4], [0,4,0], [4,0,4]]]).all(), True) + + # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap + def testScaleWrongType(self): + "Test scale function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + scale = Tensor.__dict__[self.typeStr + "Scale"] + tensor = np.array([[[1,0,1], [0,1,0], [1,0,1]], + [[0,1,0], [1,0,1], [0,1,0]], + [[1,0,1], [0,1,0], [1,0,1]]],'c') + self.assertRaises(TypeError, scale, tensor) + + # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap + def testScaleWrongDim(self): + "Test scale function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + scale = Tensor.__dict__[self.typeStr + "Scale"] + tensor = np.array([[1,0,1], [0,1,0], [1,0,1], + [0,1,0], [1,0,1], [0,1,0]],self.typeCode) + self.assertRaises(TypeError, scale, tensor) + + # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap + def testScaleWrongSize(self): + "Test scale function with wrong size" + print >>sys.stderr, self.typeStr, "... ", + scale = Tensor.__dict__[self.typeStr + "Scale"] + tensor = np.array([[[1,0], [0,1], [1,0]], + [[0,1], [1,0], [0,1]], + [[1,0], [0,1], [1,0]]],self.typeCode) + self.assertRaises(TypeError, scale, tensor) + + # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap + def testScaleNonArray(self): + "Test scale function with non-array" + print >>sys.stderr, self.typeStr, "... ", + scale = Tensor.__dict__[self.typeStr + "Scale"] + self.assertRaises(TypeError, scale, True) + + # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testFloor(self): + "Test floor function" + print >>sys.stderr, self.typeStr, "... ", + floor = Tensor.__dict__[self.typeStr + "Floor"] + tensor = np.array([[[1,2], [3,4]], + [[5,6], [7,8]]],self.typeCode) + floor(tensor,4) + np.testing.assert_array_equal(tensor, np.array([[[4,4], [4,4]], + [[5,6], [7,8]]])) + + # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testFloorWrongType(self): + "Test floor function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + floor = Tensor.__dict__[self.typeStr + "Floor"] + tensor = np.array([[[1,2], [3,4]], + [[5,6], [7,8]]],'c') + self.assertRaises(TypeError, floor, tensor) + + # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testFloorWrongDim(self): + "Test floor function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + floor = Tensor.__dict__[self.typeStr + "Floor"] + tensor = np.array([[1,2], [3,4], [5,6], [7,8]],self.typeCode) + self.assertRaises(TypeError, floor, tensor) + + # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap + def testFloorNonArray(self): + "Test floor function with non-array" + print >>sys.stderr, self.typeStr, "... ", + floor = Tensor.__dict__[self.typeStr + "Floor"] + self.assertRaises(TypeError, floor, object) + + # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap + def testCeil(self): + "Test ceil function" + print >>sys.stderr, self.typeStr, "... ", + ceil = Tensor.__dict__[self.typeStr + "Ceil"] + tensor = np.array([[[9,8], [7,6]], + [[5,4], [3,2]]],self.typeCode) + ceil(tensor,5) + np.testing.assert_array_equal(tensor, np.array([[[5,5], [5,5]], + [[5,4], [3,2]]])) + + # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap + def testCeilWrongType(self): + "Test ceil function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + ceil = Tensor.__dict__[self.typeStr + "Ceil"] + tensor = np.array([[[9,8], [7,6]], + [[5,4], [3,2]]],'c') + self.assertRaises(TypeError, ceil, tensor) + + # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap + def testCeilWrongDim(self): + "Test ceil function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + ceil = Tensor.__dict__[self.typeStr + "Ceil"] + tensor = np.array([[9,8], [7,6], [5,4], [3,2]], self.typeCode) + self.assertRaises(TypeError, ceil, tensor) + + # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap + def testCeilNonArray(self): + "Test ceil function with non-array" + print >>sys.stderr, self.typeStr, "... ", + ceil = Tensor.__dict__[self.typeStr + "Ceil"] + tensor = [[[9,8], [7,6]], + [[5,4], [3,2]]] + self.assertRaises(TypeError, ceil, tensor) + + # Test (type ARGOUT_ARRAY3[ANY][ANY][ANY]) typemap + def testLUSplit(self): + "Test luSplit function" + print >>sys.stderr, self.typeStr, "... ", + luSplit = Tensor.__dict__[self.typeStr + "LUSplit"] + lower, upper = luSplit([[[1,1], [1,1]], + [[1,1], [1,1]]]) + self.assertEquals((lower == [[[1,1], [1,0]], + [[1,0], [0,0]]]).all(), True) + self.assertEquals((upper == [[[0,0], [0,1]], + [[0,1], [1,1]]]).all(), True) + +###################################################################### + +class scharTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "schar" + self.typeCode = "b" + self.result = int(self.result) + +###################################################################### + +class ucharTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "uchar" + self.typeCode = "B" + self.result = int(self.result) + +###################################################################### + +class shortTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "short" + self.typeCode = "h" + self.result = int(self.result) + +###################################################################### + +class ushortTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "ushort" + self.typeCode = "H" + self.result = int(self.result) + +###################################################################### + +class intTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "int" + self.typeCode = "i" + self.result = int(self.result) + +###################################################################### + +class uintTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "uint" + self.typeCode = "I" + self.result = int(self.result) + +###################################################################### + +class longTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "long" + self.typeCode = "l" + self.result = int(self.result) + +###################################################################### + +class ulongTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "ulong" + self.typeCode = "L" + self.result = int(self.result) + +###################################################################### + +class longLongTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "longLong" + self.typeCode = "q" + self.result = int(self.result) + +###################################################################### + +class ulongLongTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "ulongLong" + self.typeCode = "Q" + self.result = int(self.result) + +###################################################################### + +class floatTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "float" + self.typeCode = "f" + +###################################################################### + +class doubleTestCase(TensorTestCase): + def __init__(self, methodName="runTest"): + TensorTestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + +###################################################################### + +if __name__ == "__main__": + + # Build the test suite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite( scharTestCase)) + suite.addTest(unittest.makeSuite( ucharTestCase)) + suite.addTest(unittest.makeSuite( shortTestCase)) + suite.addTest(unittest.makeSuite( ushortTestCase)) + suite.addTest(unittest.makeSuite( intTestCase)) + suite.addTest(unittest.makeSuite( uintTestCase)) + suite.addTest(unittest.makeSuite( longTestCase)) + suite.addTest(unittest.makeSuite( ulongTestCase)) + suite.addTest(unittest.makeSuite( longLongTestCase)) + suite.addTest(unittest.makeSuite(ulongLongTestCase)) + suite.addTest(unittest.makeSuite( floatTestCase)) + suite.addTest(unittest.makeSuite( doubleTestCase)) + + # Execute the test suite + print "Testing 3D Functions of Module Tensor" + print "NumPy version", np.__version__ + print + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(len(result.errors) + len(result.failures)) diff --git a/doc/swig/test/testVector.py b/doc/swig/test/testVector.py new file mode 100755 index 000000000..2ee918389 --- /dev/null +++ b/doc/swig/test/testVector.py @@ -0,0 +1,380 @@ +#! /usr/bin/env python + +# System imports +from distutils.util import get_platform +import os +import sys +import unittest + +# Import NumPy +import numpy as np +major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] +if major == 0: BadListError = TypeError +else: BadListError = ValueError + +import Vector + +###################################################################### + +class VectorTestCase(unittest.TestCase): + + def __init__(self, methodName="runTest"): + unittest.TestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + + # Test the (type IN_ARRAY1[ANY]) typemap + def testLength(self): + "Test length function" + print >>sys.stderr, self.typeStr, "... ", + length = Vector.__dict__[self.typeStr + "Length"] + self.assertEquals(length([5, 12, 0]), 13) + + # Test the (type IN_ARRAY1[ANY]) typemap + def testLengthBadList(self): + "Test length function with bad list" + print >>sys.stderr, self.typeStr, "... ", + length = Vector.__dict__[self.typeStr + "Length"] + self.assertRaises(BadListError, length, [5, "twelve", 0]) + + # Test the (type IN_ARRAY1[ANY]) typemap + def testLengthWrongSize(self): + "Test length function with wrong size" + print >>sys.stderr, self.typeStr, "... ", + length = Vector.__dict__[self.typeStr + "Length"] + self.assertRaises(TypeError, length, [5, 12]) + + # Test the (type IN_ARRAY1[ANY]) typemap + def testLengthWrongDim(self): + "Test length function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + length = Vector.__dict__[self.typeStr + "Length"] + self.assertRaises(TypeError, length, [[1,2], [3,4]]) + + # Test the (type IN_ARRAY1[ANY]) typemap + def testLengthNonContainer(self): + "Test length function with non-container" + print >>sys.stderr, self.typeStr, "... ", + length = Vector.__dict__[self.typeStr + "Length"] + self.assertRaises(TypeError, length, None) + + # Test the (type* IN_ARRAY1, int DIM1) typemap + def testProd(self): + "Test prod function" + print >>sys.stderr, self.typeStr, "... ", + prod = Vector.__dict__[self.typeStr + "Prod"] + self.assertEquals(prod([1,2,3,4]), 24) + + # Test the (type* IN_ARRAY1, int DIM1) typemap + def testProdBadList(self): + "Test prod function with bad list" + print >>sys.stderr, self.typeStr, "... ", + prod = Vector.__dict__[self.typeStr + "Prod"] + self.assertRaises(BadListError, prod, [[1,"two"], ["e","pi"]]) + + # Test the (type* IN_ARRAY1, int DIM1) typemap + def testProdWrongDim(self): + "Test prod function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + prod = Vector.__dict__[self.typeStr + "Prod"] + self.assertRaises(TypeError, prod, [[1,2], [8,9]]) + + # Test the (type* IN_ARRAY1, int DIM1) typemap + def testProdNonContainer(self): + "Test prod function with non-container" + print >>sys.stderr, self.typeStr, "... ", + prod = Vector.__dict__[self.typeStr + "Prod"] + self.assertRaises(TypeError, prod, None) + + # Test the (int DIM1, type* IN_ARRAY1) typemap + def testSum(self): + "Test sum function" + print >>sys.stderr, self.typeStr, "... ", + sum = Vector.__dict__[self.typeStr + "Sum"] + self.assertEquals(sum([5,6,7,8]), 26) + + # Test the (int DIM1, type* IN_ARRAY1) typemap + def testSumBadList(self): + "Test sum function with bad list" + print >>sys.stderr, self.typeStr, "... ", + sum = Vector.__dict__[self.typeStr + "Sum"] + self.assertRaises(BadListError, sum, [3,4, 5, "pi"]) + + # Test the (int DIM1, type* IN_ARRAY1) typemap + def testSumWrongDim(self): + "Test sum function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + sum = Vector.__dict__[self.typeStr + "Sum"] + self.assertRaises(TypeError, sum, [[3,4], [5,6]]) + + # Test the (int DIM1, type* IN_ARRAY1) typemap + def testSumNonContainer(self): + "Test sum function with non-container" + print >>sys.stderr, self.typeStr, "... ", + sum = Vector.__dict__[self.typeStr + "Sum"] + self.assertRaises(TypeError, sum, True) + + # Test the (type INPLACE_ARRAY1[ANY]) typemap + def testReverse(self): + "Test reverse function" + print >>sys.stderr, self.typeStr, "... ", + reverse = Vector.__dict__[self.typeStr + "Reverse"] + vector = np.array([1,2,4],self.typeCode) + reverse(vector) + self.assertEquals((vector == [4,2,1]).all(), True) + + # Test the (type INPLACE_ARRAY1[ANY]) typemap + def testReverseWrongDim(self): + "Test reverse function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + reverse = Vector.__dict__[self.typeStr + "Reverse"] + vector = np.array([[1,2], [3,4]],self.typeCode) + self.assertRaises(TypeError, reverse, vector) + + # Test the (type INPLACE_ARRAY1[ANY]) typemap + def testReverseWrongSize(self): + "Test reverse function with wrong size" + print >>sys.stderr, self.typeStr, "... ", + reverse = Vector.__dict__[self.typeStr + "Reverse"] + vector = np.array([9,8,7,6,5,4],self.typeCode) + self.assertRaises(TypeError, reverse, vector) + + # Test the (type INPLACE_ARRAY1[ANY]) typemap + def testReverseWrongType(self): + "Test reverse function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + reverse = Vector.__dict__[self.typeStr + "Reverse"] + vector = np.array([1,2,4],'c') + self.assertRaises(TypeError, reverse, vector) + + # Test the (type INPLACE_ARRAY1[ANY]) typemap + def testReverseNonArray(self): + "Test reverse function with non-array" + print >>sys.stderr, self.typeStr, "... ", + reverse = Vector.__dict__[self.typeStr + "Reverse"] + self.assertRaises(TypeError, reverse, [2,4,6]) + + # Test the (type* INPLACE_ARRAY1, int DIM1) typemap + def testOnes(self): + "Test ones function" + print >>sys.stderr, self.typeStr, "... ", + ones = Vector.__dict__[self.typeStr + "Ones"] + vector = np.zeros(5,self.typeCode) + ones(vector) + np.testing.assert_array_equal(vector, np.array([1,1,1,1,1])) + + # Test the (type* INPLACE_ARRAY1, int DIM1) typemap + def testOnesWrongDim(self): + "Test ones function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + ones = Vector.__dict__[self.typeStr + "Ones"] + vector = np.zeros((5,5),self.typeCode) + self.assertRaises(TypeError, ones, vector) + + # Test the (type* INPLACE_ARRAY1, int DIM1) typemap + def testOnesWrongType(self): + "Test ones function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + ones = Vector.__dict__[self.typeStr + "Ones"] + vector = np.zeros((5,5),'c') + self.assertRaises(TypeError, ones, vector) + + # Test the (type* INPLACE_ARRAY1, int DIM1) typemap + def testOnesNonArray(self): + "Test ones function with non-array" + print >>sys.stderr, self.typeStr, "... ", + ones = Vector.__dict__[self.typeStr + "Ones"] + self.assertRaises(TypeError, ones, [2,4,6,8]) + + # Test the (int DIM1, type* INPLACE_ARRAY1) typemap + def testZeros(self): + "Test zeros function" + print >>sys.stderr, self.typeStr, "... ", + zeros = Vector.__dict__[self.typeStr + "Zeros"] + vector = np.ones(5,self.typeCode) + zeros(vector) + np.testing.assert_array_equal(vector, np.array([0,0,0,0,0])) + + # Test the (int DIM1, type* INPLACE_ARRAY1) typemap + def testZerosWrongDim(self): + "Test zeros function with wrong dimensions" + print >>sys.stderr, self.typeStr, "... ", + zeros = Vector.__dict__[self.typeStr + "Zeros"] + vector = np.ones((5,5),self.typeCode) + self.assertRaises(TypeError, zeros, vector) + + # Test the (int DIM1, type* INPLACE_ARRAY1) typemap + def testZerosWrongType(self): + "Test zeros function with wrong type" + print >>sys.stderr, self.typeStr, "... ", + zeros = Vector.__dict__[self.typeStr + "Zeros"] + vector = np.ones(6,'c') + self.assertRaises(TypeError, zeros, vector) + + # Test the (int DIM1, type* INPLACE_ARRAY1) typemap + def testZerosNonArray(self): + "Test zeros function with non-array" + print >>sys.stderr, self.typeStr, "... ", + zeros = Vector.__dict__[self.typeStr + "Zeros"] + self.assertRaises(TypeError, zeros, [1,3,5,7,9]) + + # Test the (type ARGOUT_ARRAY1[ANY]) typemap + def testEOSplit(self): + "Test eoSplit function" + print >>sys.stderr, self.typeStr, "... ", + eoSplit = Vector.__dict__[self.typeStr + "EOSplit"] + even, odd = eoSplit([1,2,3]) + self.assertEquals((even == [1,0,3]).all(), True) + self.assertEquals((odd == [0,2,0]).all(), True) + + # Test the (type* ARGOUT_ARRAY1, int DIM1) typemap + def testTwos(self): + "Test twos function" + print >>sys.stderr, self.typeStr, "... ", + twos = Vector.__dict__[self.typeStr + "Twos"] + vector = twos(5) + self.assertEquals((vector == [2,2,2,2,2]).all(), True) + + # Test the (type* ARGOUT_ARRAY1, int DIM1) typemap + def testTwosNonInt(self): + "Test twos function with non-integer dimension" + print >>sys.stderr, self.typeStr, "... ", + twos = Vector.__dict__[self.typeStr + "Twos"] + self.assertRaises(TypeError, twos, 5.0) + + # Test the (int DIM1, type* ARGOUT_ARRAY1) typemap + def testThrees(self): + "Test threes function" + print >>sys.stderr, self.typeStr, "... ", + threes = Vector.__dict__[self.typeStr + "Threes"] + vector = threes(6) + self.assertEquals((vector == [3,3,3,3,3,3]).all(), True) + + # Test the (type* ARGOUT_ARRAY1, int DIM1) typemap + def testThreesNonInt(self): + "Test threes function with non-integer dimension" + print >>sys.stderr, self.typeStr, "... ", + threes = Vector.__dict__[self.typeStr + "Threes"] + self.assertRaises(TypeError, threes, "threes") + +###################################################################### + +class scharTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "schar" + self.typeCode = "b" + +###################################################################### + +class ucharTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "uchar" + self.typeCode = "B" + +###################################################################### + +class shortTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "short" + self.typeCode = "h" + +###################################################################### + +class ushortTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "ushort" + self.typeCode = "H" + +###################################################################### + +class intTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "int" + self.typeCode = "i" + +###################################################################### + +class uintTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "uint" + self.typeCode = "I" + +###################################################################### + +class longTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "long" + self.typeCode = "l" + +###################################################################### + +class ulongTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "ulong" + self.typeCode = "L" + +###################################################################### + +class longLongTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "longLong" + self.typeCode = "q" + +###################################################################### + +class ulongLongTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "ulongLong" + self.typeCode = "Q" + +###################################################################### + +class floatTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "float" + self.typeCode = "f" + +###################################################################### + +class doubleTestCase(VectorTestCase): + def __init__(self, methodName="runTest"): + VectorTestCase.__init__(self, methodName) + self.typeStr = "double" + self.typeCode = "d" + +###################################################################### + +if __name__ == "__main__": + + # Build the test suite + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite( scharTestCase)) + suite.addTest(unittest.makeSuite( ucharTestCase)) + suite.addTest(unittest.makeSuite( shortTestCase)) + suite.addTest(unittest.makeSuite( ushortTestCase)) + suite.addTest(unittest.makeSuite( intTestCase)) + suite.addTest(unittest.makeSuite( uintTestCase)) + suite.addTest(unittest.makeSuite( longTestCase)) + suite.addTest(unittest.makeSuite( ulongTestCase)) + suite.addTest(unittest.makeSuite( longLongTestCase)) + suite.addTest(unittest.makeSuite(ulongLongTestCase)) + suite.addTest(unittest.makeSuite( floatTestCase)) + suite.addTest(unittest.makeSuite( doubleTestCase)) + + # Execute the test suite + print "Testing 1D Functions of Module Vector" + print "NumPy version", np.__version__ + print + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(len(result.errors) + len(result.failures)) |