[DEV] add v1.66.0

This commit is contained in:
2018-01-12 21:47:58 +01:00
parent 87059bb1af
commit a97e9ae7d4
49032 changed files with 7668950 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
.. Boost.Python NumPy extension documentation master file, created by
sphinx-quickstart on Thu Oct 27 09:04:58 2011.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to the documentation of the Boost.Python NumPy extension!
=================================================================
.. toctree::
:maxdepth: 2
Tutorial <tutorial/index>
Reference <reference/index>

View File

@@ -0,0 +1,110 @@
binary_ufunc
============
.. contents :: Table of Contents
A ``binary_ufunc`` is a struct used as an intermediate step to broadcast two arguments so that a C++ function can be converted to a ufunc like function
``<boost/python/numpy/ufunc.hpp>`` contains the ``binary_ufunc`` structure definitions
synopsis
--------
::
namespace boost
{
namespace python
{
namespace numpy
{
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
struct binary_ufunc
{
static object call(TBinaryFunctor & self,
object const & input1,
object const & input2,
object const & output);
static object make();
};
}
}
}
constructors
------------
::
struct example_binary_ufunc
{
typedef any_valid first_argument_type;
typedef any_valid second_argument_type;
typedef any_valid result_type;
};
:Requirements: The ``any_valid`` type must be defined using typedef as a valid C++ type in order to use the struct methods correctly
:Note: The struct must be exposed as a Python class, and an instance of the class must be created to use the ``call`` method corresponding to the ``__call__`` attribute of the Python object
accessors
---------
::
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
static object call(TBinaryFunctor & self,
object const & input,
object const & output);
:Requires: Typenames ``TBinaryFunctor`` and optionally ``TArgument1`` and ``TArgument2`` for argument type and ``TResult`` for result type
:Effects: Passes a Python object to the underlying C++ functor after broadcasting its arguments
::
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
static object make();
:Requires: Typenames ``TBinaryFunctor`` and optionally ``TArgument1`` and ``TArgument2`` for argument type and ``TResult`` for result type
:Returns: A Python function object to call the overloaded () operator in the struct (in typical usage)
Example(s)
----------
::
namespace p = boost::python;
namespace np = boost::python::numpy;
struct BinarySquare
{
typedef double first_argument_type;
typedef double second_argument_type;
typedef double result_type;
double operator()(double a,double b) const { return (a*a + b*b) ; }
};
p::object ud = p::class_<BinarySquare, boost::shared_ptr<BinarySquare> >("BinarySquare").def("__call__", np::binary_ufunc<BinarySquare>::make());
p::object inst = ud();
result_array = inst.attr("__call__")(demo_array,demo_array) ;
std::cout << "Square of list with binary ufunc is " << p::extract <char const * > (p::str(result_array)) << std::endl ;

View File

@@ -0,0 +1,92 @@
dtype
=====
.. contents :: Table of Contents
A `dtype`_ is an object describing the type of the elements of an ndarray
.. _dtype: http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#data-type-objects-dtype
``<boost/python/numpy/dtype.hpp>`` contains the method calls necessary to generate a python object equivalent to a numpy.dtype from builtin C++ objects, as well as to create custom dtypes from user defined types
synopsis
--------
::
namespace boost
{
namespace python
{
namespace numpy
{
class dtype : public object
{
static python::detail::new_reference convert(object::object_cref arg, bool align);
public:
// Convert an arbitrary Python object to a data-type descriptor object.
template <typename T>
explicit dtype(T arg, bool align=false);
// Get the built-in numpy dtype associated with the given scalar template type.
template <typename T> static dtype get_builtin();
// Return the size of the data type in bytes.
int get_itemsize() const;
};
}
}
}
constructors
------------
::
template <typename T>
explicit dtype(T arg, bool align=false)
:Requirements: ``T`` must be either :
* a built-in C++ typename convertible to object
* a valid python object or convertible to object
:Effects: Constructs an object from the supplied python object / convertible
to object / builtin C++ data type
:Throws: Nothing
::
template <typename T> static dtype get_builtin();
:Requirements: The typename supplied, ``T`` must be a builtin C++ type also supported by numpy
:Returns: Numpy dtype corresponding to builtin C++ type
accessors
---------
::
int get_itemsize() const;
:Returns: the size of the data type in bytes.
Example(s)
----------
::
namespace p = boost::python;
namespace np = boost::python::numpy;
np::dtype dtype = np::dtype::get_builtin<double>();
p::tuple for_custom_dtype = p::make_tuple("ha",dtype);
np::dtype custom_dtype = np::dtype(list_for_dtype);

View File

@@ -0,0 +1,12 @@
Boost.Python NumPy extension Reference
======================================
.. toctree::
:maxdepth: 2
dtype
ndarray
unary_ufunc
binary_ufunc
multi_iter

View File

@@ -0,0 +1,94 @@
multi_iter
==========
.. contents :: Table of Contents
A ``multi_iter`` is a Python object, intended to be used as an iterator It should generally only be used in loops.
``<boost/python/numpy/ufunc.hpp>`` contains the class definitions for ``multi_iter``
synopsis
--------
::
namespace boost
{
namespace python
{
namespace numpy
{
class multi_iter : public object
{
public:
void next();
bool not_done() const;
char * get_data(int n) const;
int const get_nd() const;
Py_intptr_t const * get_shape() const;
Py_intptr_t const shape(int n) const;
};
multi_iter make_multi_iter(object const & a1);
multi_iter make_multi_iter(object const & a1, object const & a2);
multi_iter make_multi_iter(object const & a1, object const & a2, object const & a3);
}
}
}
constructors
------------
::
multi_iter make_multi_iter(object const & a1);
multi_iter make_multi_iter(object const & a1, object const & a2);
multi_iter make_multi_iter(object const & a1, object const & a2, object const & a3);
:Returns: A Python iterator object broadcasting over one, two or three sequences as supplied
accessors
---------
::
void next();
:Effects: Increments the iterator
::
bool not_done() const;
:Returns: boolean value indicating whether the iterator is at its end
::
char * get_data(int n) const;
:Returns: a pointer to the element of the nth broadcasted array.
::
int const get_nd() const;
:Returns: the number of dimensions of the broadcasted array expression
::
Py_intptr_t const * get_shape() const;
:Returns: the shape of the broadcasted array expression as an array of integers.
::
Py_intptr_t const shape(int n) const;
:Returns: the shape of the broadcasted array expression in the nth dimension.

View File

@@ -0,0 +1,382 @@
ndarray
=======
.. contents :: Table of Contents
A `ndarray`_ is an N-dimensional array which contains items of the same type and size, where N is the number of dimensions and is specified in the form of a ``shape`` tuple. Optionally, the numpy ``dtype`` for the objects contained may also be specified.
.. _ndarray: http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html
.. _dtype: http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#data-type-objects-dtype
``<boost/python/numpy/ndarray.hpp>`` contains the structures and methods necessary to move raw data between C++ and Python and create ndarrays from the data
synopsis
--------
::
namespace boost
{
namespace python
{
namespace numpy
{
class ndarray : public object
{
public:
enum bitflag
{
NONE=0x0, C_CONTIGUOUS=0x1, F_CONTIGUOUS=0x2, V_CONTIGUOUS=0x1|0x2,
ALIGNED=0x4, WRITEABLE=0x8, BEHAVED=0x4|0x8,
CARRAY_RO=0x1|0x4, CARRAY=0x1|0x4|0x8, CARRAY_MIS=0x1|0x8,
FARRAY_RO=0x2|0x4, FARRAY=0x2|0x4|0x8, FARRAY_MIS=0x2|0x8,
UPDATE_ALL=0x1|0x2|0x4, VARRAY=0x1|0x2|0x8, ALL=0x1|0x2|0x4|0x8
};
ndarray view(dtype const & dt) const;
ndarray astype(dtype const & dt) const;
ndarray copy() const;
int const shape(int n) const;
int const strides(int n) const;
char * get_data() const;
dtype get_dtype() const;
python::object get_base() const;
void set_base(object const & base);
Py_intptr_t const * get_shape() const;
Py_intptr_t const * get_strides() const;
int const get_nd() const;
bitflag const get_flags() const;
ndarray transpose() const;
ndarray squeeze() const;
ndarray reshape(tuple const & shape) const;
object scalarize() const;
};
ndarray zeros(tuple const & shape, dtype const & dt);
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
ndarray empty(tuple const & shape, dtype const & dt);
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
ndarray array(object const & obj);
ndarray array(object const & obj, dtype const & dt);
template <typename Container>
ndarray from_data(void * data,dtype const & dt,Container shape,Container strides,python::object const & owner);
template <typename Container>
ndarray from_data(void const * data, dtype const & dt, Container shape, Container strides, object const & owner);
ndarray from_object(object const & obj, dtype const & dt,int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(object const & obj, dtype const & dt,int nd, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(object const & obj, int nd_min, int nd_max,ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(object const & obj, ndarray::bitflag flags=ndarray::NONE)
ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b) ;
ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b);
}
constructors
------------
::
ndarray view(dtype const & dt) const;
:Returns: new ndarray with old ndarray data cast as supplied dtype
::
ndarray astype(dtype const & dt) const;
:Returns: new ndarray with old ndarray data converted to supplied dtype
::
ndarray copy() const;
:Returns: Copy of calling ndarray object
::
ndarray transpose() const;
:Returns: An ndarray with the rows and columns interchanged
::
ndarray squeeze() const;
:Returns: An ndarray with all unit-shaped dimensions removed
::
ndarray reshape(tuple const & shape) const;
:Requirements: The new ``shape`` of the ndarray must be supplied as a tuple
:Returns: An ndarray with the same data but reshaped to the ``shape`` supplied
::
object scalarize() const;
:Returns: A scalar if the ndarray has only one element, otherwise it returns the entire array
::
ndarray zeros(tuple const & shape, dtype const & dt);
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
:Requirements: The following parameters must be supplied as required :
* the ``shape`` or the size of all dimensions, as a tuple
* the ``dtype`` of the data
* the ``nd`` size for a square shaped ndarray
* the ``shape`` Py_intptr_t
:Returns: A new ndarray with the given shape and data type, with data initialized to zero.
::
ndarray empty(tuple const & shape, dtype const & dt);
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
:Requirements: The following parameters must be supplied :
* the ``shape`` or the size of all dimensions, as a tuple
* the ``dtype`` of the data
* the ``shape`` Py_intptr_t
:Returns: A new ndarray with the given shape and data type, with data left uninitialized.
::
ndarray array(object const & obj);
ndarray array(object const & obj, dtype const & dt);
:Returns: A new ndarray from an arbitrary Python sequence, with dtype of each element specified optionally
::
template <typename Container>
inline ndarray from_data(void * data,dtype const & dt,Container shape,Container strides,python::object const & owner)
:Requirements: The following parameters must be supplied :
* the ``data`` which is a generic C++ data container
* the dtype ``dt`` of the data
* the ``shape`` of the ndarray as Python object
* the ``strides`` of each dimension of the array as a Python object
* the ``owner`` of the data, in case it is not the ndarray itself
:Returns: ndarray with attributes and data supplied
:Note: The ``Container`` typename must be one that is convertible to a std::vector or python object type
::
ndarray from_object(object const & obj, dtype const & dt,int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* minimum number of dimensions ``nd_min`` of the ndarray as Python object
* maximum number of dimensions ``nd_max`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray constructed with dimensions and data supplied as parameters
::
inline ndarray from_object(object const & obj, dtype const & dt, int nd, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* number of dimensions ``nd`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray with dimensions ``nd`` x ``nd`` and suplied parameters
::
inline ndarray from_object(object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE)
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* optional ``flags`` bitflags
:Returns: Supplied Python object as ndarray
::
ndarray from_object(object const & obj, int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* minimum number of dimensions ``nd_min`` of the ndarray as Python object
* maximum number of dimensions ``nd_max`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray with supplied dimension limits and parameters
:Note: dtype need not be supplied here
::
inline ndarray from_object(object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* number of dimensions ``nd`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray of ``nd`` x ``nd`` dimensions constructed from the supplied object
::
inline ndarray from_object(object const & obj, ndarray::bitflag flags=ndarray::NONE)
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* optional ``flags`` bitflags
:Returns: ndarray of same dimensions and dtype as supplied Python object
accessors
---------
::
int const shape(int n) const;
:Returns: The size of the n-th dimension of the ndarray
::
int const strides(int n) const;
:Returns: The stride of the nth dimension.
::
char * get_data() const;
:Returns: Array's raw data pointer as a char
:Note: This returns char so stride math works properly on it.User will have to reinterpret_cast it.
::
dtype get_dtype() const;
:Returns: Array's data-type descriptor object (dtype)
::
object get_base() const;
:Returns: Object that owns the array's data, or None if the array owns its own data.
::
void set_base(object const & base);
:Returns: Set the object that owns the array's data. Exercise caution while using this
::
Py_intptr_t const * get_shape() const;
:Returns: Shape of the array as an array of integers
::
Py_intptr_t const * get_strides() const;
:Returns: Stride of the array as an array of integers
::
int const get_nd() const;
:Returns: Number of array dimensions
::
bitflag const get_flags() const;
:Returns: Array flags
::
inline ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b)
:Returns: bitflag logically OR-ed as (a | b)
::
inline ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b)
:Returns: bitflag logically AND-ed as (a & b)
Example(s)
----------
::
namespace p = boost::python;
namespace np = boost::python::numpy;
p::object tu = p::make_tuple('a','b','c') ;
np::ndarray example_tuple = np::array (tu) ;
p::list l ;
np::ndarray example_list = np::array (l) ;
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray example_list1 = np::array (l,dt);
int data[] = {1,2,3,4} ;
p::tuple shape = p::make_tuple(4) ;
p::tuple stride = p::make_tuple(4) ;
p::object own ;
np::ndarray data_ex = np::from_data(data,dt,shape,stride,own);
uint8_t mul_data[][4] = {{1,2,3,4},{5,6,7,8},{1,3,5,7}};
shape = p::make_tuple(3,2) ;
stride = p::make_tuple(4,2) ;
np::dtype dt1 = np::dtype::get_builtin<uint8_t>();
np::ndarray mul_data_ex = np::from_data(mul_data,dt1, p::make_tuple(3,4),p::make_tuple(4,1),p::object());
mul_data_ex = np::from_data(mul_data,dt1, shape,stride,p::object());

View File

@@ -0,0 +1,103 @@
unary_ufunc
===========
.. contents :: Table of Contents
A ``unary_ufunc`` is a struct used as an intermediate step to broadcast a single argument so that a C++ function can be converted to a ufunc like function
``<boost/python/numpy/ufunc.hpp>`` contains the ``unary_ufunc`` structure definitions
synopsis
--------
::
namespace boost
{
namespace python
{
namespace numpy
{
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
struct unary_ufunc
{
static object call(TUnaryFunctor & self,
object const & input,
object const & output) ;
static object make();
};
}
}
}
constructors
------------
::
struct example_unary_ufunc
{
typedef any_valid_type argument_type;
typedef any_valid_type result_type;
};
:Requirements: The ``any_valid`` type must be defined using typedef as a valid C++ type in order to use the struct methods correctly
:Note: The struct must be exposed as a Python class, and an instance of the class must be created to use the ``call`` method corresponding to the ``__call__`` attribute of the Python object
accessors
---------
::
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
static object call(TUnaryFunctor & self,
object const & input,
object const & output);
:Requires: Typenames ``TUnaryFunctor`` and optionally ``TArgument`` for argument type and ``TResult`` for result type
:Effects: Passes a Python object to the underlying C++ functor after broadcasting its arguments
::
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
static object make();
:Requires: Typenames ``TUnaryFunctor`` and optionally ``TArgument`` for argument type and ``TResult`` for result type
:Returns: A Python function object to call the overloaded () operator in the struct (in typical usage)
Example(s)
----------
::
namespace p = boost::python;
namespace np = boost::python::numpy;
struct UnarySquare
{
typedef double argument_type;
typedef double result_type;
double operator()(double r) const { return r * r;}
};
p::object ud = p::class_<UnarySquare, boost::shared_ptr<UnarySquare> >("UnarySquare").def("__call__", np::unary_ufunc<UnarySquare>::make());
p::object inst = ud();
std::cout << "Square of unary scalar 1.0 is " << p::extract <char const * > (p::str(inst.attr("__call__")(1.0))) << std::endl ;

View File

@@ -0,0 +1,54 @@
How to use dtypes
=================
Here is a brief tutorial to show how to create ndarrays with built-in python data types, and extract the types and values of member variables
Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
#include <boost/python/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::python::numpy;
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Next, we create the shape and dtype. We use the get_builtin method to get the numpy dtype corresponding to the builtin C++ dtype
Here, we will create a 3x3 array passing a tuple with (3,3) for the size, and double as the data type ::
p::tuple shape = p::make_tuple(3, 3);
np::dtype dtype = np::dtype::get_builtin<double>();
np::ndarray a = np::zeros(shape, dtype);
Finally, we can print the array using the extract method in the python namespace.
Here, we first convert the variable into a string, and then extract it as a C++ character array from the python string using the <char const \* > template ::
std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
We can also print the dtypes of the data members of the ndarray by using the get_dtype method for the ndarray ::
std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
We can also create custom dtypes and build ndarrays with the custom dtypes
We use the dtype constructor to create a custom dtype. This constructor takes a list as an argument.
The list should contain one or more tuples of the format (variable name, variable type)
So first create a tuple with a variable name and its dtype, double, to create a custom dtype ::
p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
Next, create a list, and add this tuple to the list. Then use the list to create the custom dtype ::
p::list list_for_dtype ;
list_for_dtype.append(for_custom_dtype) ;
np::dtype custom_dtype = np::dtype(list_for_dtype) ;
We are now ready to create an ndarray with dimensions specified by \*shape\* and of custom dtpye ::
np::ndarray new_array = np::zeros(shape,custom_dtype);
}

View File

@@ -0,0 +1,56 @@
How to access data using raw pointers
=====================================
One of the advantages of the ndarray wrapper is that the same data can be used in both Python and C++ and changes can be made to reflect at both ends.
The from_data method makes this possible.
Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
#include <boost/python/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::python::numpy;
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Create an array in C++ , and pass the pointer to it to the from_data method to create an ndarray::
int arr[] = {1,2,3,4,5};
np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>(),
p::make_tuple(5),
p::make_tuple(sizeof(int)),
p::object());
Print the source C++ array, as well as the ndarray, to check if they are the same::
std::cout << "C++ array :" << std::endl;
for (int j=0;j<4;j++)
{
std::cout << arr[j] << ' ';
}
std::cout << std::endl
<< "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;
Now, change an element in the Python ndarray, and check if the value changed correspondingly in the source C++ array::
py_array[1] = 5 ;
std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl;
for (int j = 0; j < 5; j++)
{
std::cout << arr[j] << ' ';
}
Next, change an element of the source C++ array and see if it is reflected in the Python ndarray::
arr[2] = 8;
std::cout << std::endl
<< "Is the change reflected in the Python ndarray ?" << std::endl
<< p::extract<char const *>(p::str(py_array)) << std::endl;
}
As we can see, the changes are reflected across the ends. This happens because the from_data method passes the C++ array by reference to create the ndarray, and thus uses the same locations for storing data.

View File

@@ -0,0 +1,12 @@
Boost.Python NumPy extension Tutorial
=====================================
.. toctree::
:maxdepth: 2
simple
dtype
ndarray
ufunc
fromdata

View File

@@ -0,0 +1,99 @@
Creating ndarrays
=================
The Boost.Numpy library exposes quite a few methods to create ndarrays. ndarrays can be created in a variety of ways, include empty arrays and zero filled arrays.
ndarrays can also be created from arbitrary python sequences as well as from data and dtypes.
This tutorial will introduce you to some of the ways in which you can create ndarrays. The methods covered here include creating ndarrays from arbitrary Python sequences, as well as from C++ containers, using both unit and non-unit strides
First, as before, initialise the necessary namepaces and runtimes ::
#include <boost/python/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::python::numpy;
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Let's now create an ndarray from a simple tuple. We first create a tuple object, and then pass it to the array method, to generate the necessary tuple ::
p::object tu = p::make_tuple('a','b','c');
np::ndarray example_tuple = np::array(tu);
Let's now try the same with a list. We create an empty list, add an element using the append method, and as before, call the array method ::
p::list l;
l.append('a');
np::ndarray example_list = np::array (l);
Optionally, we can also specify a dtype for the array ::
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray example_list1 = np::array (l,dt);
We can also create an array by supplying data arrays and a few other parameters.
First,create an integer array ::
int data[] = {1,2,3,4,5};
Create a shape, and strides, needed by the function ::
p::tuple shape = p::make_tuple(5);
p::tuple stride = p::make_tuple(sizeof(int));
Here, shape is (4,) , and the stride is `sizeof(int)``.
A stride is the number of bytes that must be traveled to get to the next desired element while constructing the ndarray.
The function also needs an owner, to keep track of the data array passed. Passing none is dangerous ::
p::object own;
The from_data function takes the data array, datatype,shape,stride and owner as arguments and returns an ndarray ::
np::ndarray data_ex1 = np::from_data(data,dt, shape,stride,own);
Now let's print the ndarray we created ::
std::cout << "Single dimensional array ::" << std::endl
<< p::extract<char const *>(p::str(data_ex)) << std::endl;
Let's make it a little more interesting. Lets make an 3x2 ndarray from a multi-dimensional array using non-unit strides
First lets create a 3x4 array of 8-bit integers ::
uint8_t mul_data[][4] = {{1,2,3,4},{5,6,7,8},{1,3,5,7}};
Now let's create an array of 3x2 elements, picking the first and third elements from each row . For that, the shape will be 3x2.
The strides will be 4x2 i.e. 4 bytes to go to the next desired row, and 2 bytes to go to the next desired column ::
shape = p::make_tuple(3,2);
stride = p::make_tuple(sizeof(uint8_t)*2,sizeof(uint8_t));
Get the numpy dtype for the built-in 8-bit integer data type ::
np::dtype dt1 = np::dtype::get_builtin<uint8_t>();
Now lets first create and print out the ndarray as is.
Notice how we can pass the shape and strides in the function directly, as well as the owner. The last part can be done because we don't have any use to
manipulate the "owner" object ::
np::ndarray mul_data_ex = np::from_data(mul_data, dt1,
p::make_tuple(3,4),
p::make_tuple(4,1),
p::object());
std::cout << "Original multi dimensional array :: " << std::endl
<< p::extract<char const *>(p::str(mul_data_ex)) << std::endl;
Now create the new ndarray using the shape and strides and print out the array we created using non-unit strides ::
mul_data_ex = np::from_data(mul_data, dt1, shape, stride, p::object());
std::cout << "Selective multidimensional array :: "<<std::endl
<< p::extract<char const *>(p::str(mul_data_ex)) << std::endl ;
}
.. note:: The from_data method will throw ``error_already_set`` if the number of elements dictated by the shape and the corresponding strides don't match.

View File

@@ -0,0 +1,41 @@
A simple tutorial on Arrays
===========================
Let's start with a simple tutorial to create and modify arrays.
Get the necessary headers for numpy components and set up necessary namespaces::
#include <boost/python/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::python::numpy;
Initialise the Python runtime, and the numpy module. Failure to call these results in segmentation errors::
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Zero filled n-dimensional arrays can be created using the shape and data-type of the array as a parameter. Here, the shape is 3x3 and the datatype is the built-in float type::
p::tuple shape = p::make_tuple(3, 3);
np::dtype dtype = np::dtype::get_builtin<float>();
np::ndarray a = np::zeros(shape, dtype);
You can also create an empty array like this ::
np::ndarray b = np::empty(shape,dtype);
Print the original and reshaped array. The array a which is a list is first converted to a string, and each value in the list is extracted using extract< >::
std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
// Reshape the array into a 1D array
a = a.reshape(p::make_tuple(9));
// Print it again.
std::cout << "Reshaped array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
}

View File

@@ -0,0 +1,120 @@
Ufuncs
======
Ufuncs or universal functions operate on ndarrays element by element, and support array broadcasting, type casting, and other features.
Lets try and see how we can use the binary and unary ufunc methods
After the neccessary includes ::
#include <boost/python/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::python::numpy;
Now we create the structs necessary to implement the ufuncs. The typedefs *must* be made as the ufunc generators take these typedefs as inputs and return an error otherwise ::
struct UnarySquare
{
typedef double argument_type;
typedef double result_type;
double operator()(double r) const { return r * r;}
};
struct BinarySquare
{
typedef double first_argument_type;
typedef double second_argument_type;
typedef double result_type;
double operator()(double a,double b) const { return (a*a + b*b) ; }
};
Initialise the Python runtime and the numpy module ::
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Now expose the struct UnarySquare to Python as a class, and let ud be the class object. ::
p::object ud = p::class_<UnarySquare, boost::shared_ptr<UnarySquare> >("UnarySquare");
ud.def("__call__", np::unary_ufunc<UnarySquare>::make());
Let inst be an instance of the class ud ::
p::object inst = ud();
Use the "__call__" method to call the overloaded () operator and print the value ::
std::cout << "Square of unary scalar 1.0 is " << p::extract<char const *>(p::str(inst.attr("__call__")(1.0))) << std::endl;
Create an array in C++ ::
int arr[] = {1,2,3,4} ;
..and use it to create the ndarray in Python ::
np::ndarray demo_array = np::from_data(arr, np::dtype::get_builtin<int>(),
p::make_tuple(4),
p::make_tuple(4),
p::object());
Print out the demo array ::
std::cout << "Demo array is " << p::extract<char const *>(p::str(demo_array)) << std::endl;
Call the "__call__" method to perform the operation and assign the value to result_array ::
p::object result_array = inst.attr("__call__")(demo_array);
Print the resultant array ::
std::cout << "Square of demo array is " << p::extract<char const *>(p::str(result_array)) << std::endl;
Lets try the same with a list ::
p::list li;
li.append(3);
li.append(7);
Print out the demo list ::
std::cout << "Demo list is " << p::extract<char const *>(p::str(li)) << std::endl;
Call the ufunc for the list ::
result_array = inst.attr("__call__")(li);
And print the list out ::
std::cout << "Square of demo list is " << p::extract<char const *>(p::str(result_array)) << std::endl;
Now lets try Binary ufuncs. Again, expose the struct BinarySquare to Python as a class, and let ud be the class object ::
ud = p::class_<BinarySquare, boost::shared_ptr<BinarySquare> >("BinarySquare");
ud.def("__call__", np::binary_ufunc<BinarySquare>::make());
And initialise ud ::
inst = ud();
Print the two input lists ::
std::cout << "The two input list for binary ufunc are " << std::endl
<< p::extract<char const *>(p::str(demo_array)) << std::endl
<< p::extract<char const *>(p::str(demo_array)) << std::endl;
Call the binary ufunc taking demo_array as both inputs ::
result_array = inst.attr("__call__")(demo_array,demo_array);
And print the output ::
std::cout << "Square of list with binary ufunc is " << p::extract<char const *>(p::str(result_array)) << std::endl;
}