dtype.rst 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. How to use dtypes
  2. =================
  3. 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
  4. Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
  5. #include <boost/python/numpy.hpp>
  6. #include <iostream>
  7. namespace p = boost::python;
  8. namespace np = boost::python::numpy;
  9. int main(int argc, char **argv)
  10. {
  11. Py_Initialize();
  12. np::initialize();
  13. Next, we create the shape and dtype. We use the get_builtin method to get the numpy dtype corresponding to the builtin C++ dtype
  14. Here, we will create a 3x3 array passing a tuple with (3,3) for the size, and double as the data type ::
  15. p::tuple shape = p::make_tuple(3, 3);
  16. np::dtype dtype = np::dtype::get_builtin<double>();
  17. np::ndarray a = np::zeros(shape, dtype);
  18. Finally, we can print the array using the extract method in the python namespace.
  19. 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 ::
  20. std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
  21. We can also print the dtypes of the data members of the ndarray by using the get_dtype method for the ndarray ::
  22. std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
  23. We can also create custom dtypes and build ndarrays with the custom dtypes
  24. We use the dtype constructor to create a custom dtype. This constructor takes a list as an argument.
  25. The list should contain one or more tuples of the format (variable name, variable type)
  26. So first create a tuple with a variable name and its dtype, double, to create a custom dtype ::
  27. p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
  28. Next, create a list, and add this tuple to the list. Then use the list to create the custom dtype ::
  29. p::list list_for_dtype ;
  30. list_for_dtype.append(for_custom_dtype) ;
  31. np::dtype custom_dtype = np::dtype(list_for_dtype) ;
  32. We are now ready to create an ndarray with dimensions specified by \*shape\* and of custom dtpye ::
  33. np::ndarray new_array = np::zeros(shape,custom_dtype);
  34. }