]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/python/example/numpy/dtype.cpp
1 // Copyright Ankit Daftery 2011-2012.
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
7 * @brief An example to show how to create ndarrays with built-in python data types, and extract
8 * the types and values of member variables
10 * @todo Add an example to show type conversion.
11 * Add an example to show use of user-defined types
15 #include <boost/python/numpy.hpp>
18 namespace p
= boost::python
;
19 namespace np
= boost::python::numpy
;
21 int main(int argc
, char **argv
)
23 // Initialize the Python runtime.
27 // Create a 3x3 shape...
28 p::tuple shape
= p::make_tuple(3, 3);
29 // ...as well as a type for C++ double
30 np::dtype dtype
= np::dtype::get_builtin
<double>();
31 // Construct an array with the above shape and type
32 np::ndarray a
= np::zeros(shape
, dtype
);
34 std::cout
<< "Original array:\n" << p::extract
<char const *>(p::str(a
)) << std::endl
;
35 // Print the datatype of the elements
36 std::cout
<< "Datatype is:\n" << p::extract
<char const *>(p::str(a
.get_dtype())) << std::endl
;
37 // Using user defined dtypes to create dtype and an array of the custom dtype
38 // First create a tuple with a variable name and its dtype, double, to create a custom dtype
39 p::tuple for_custom_dtype
= p::make_tuple("ha",dtype
) ;
40 // The list needs to be created, because the constructor to create the custom dtype
41 // takes a list of (variable,variable_type) as an argument
42 p::list list_for_dtype
;
43 list_for_dtype
.append(for_custom_dtype
) ;
44 // Create the custom dtype
45 np::dtype custom_dtype
= np::dtype(list_for_dtype
) ;
46 // Create an ndarray with the custom dtype
47 np::ndarray new_array
= np::zeros(shape
,custom_dtype
);