dtype.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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)
  5. /**
  6. * @brief An example to show how to create ndarrays with built-in python data types, and extract
  7. * the types and values of member variables
  8. *
  9. * @todo Add an example to show type conversion.
  10. * Add an example to show use of user-defined types
  11. *
  12. */
  13. #include <boost/python/numpy.hpp>
  14. #include <iostream>
  15. namespace p = boost::python;
  16. namespace np = boost::python::numpy;
  17. int main(int argc, char **argv)
  18. {
  19. // Initialize the Python runtime.
  20. Py_Initialize();
  21. // Initialize NumPy
  22. np::initialize();
  23. // Create a 3x3 shape...
  24. p::tuple shape = p::make_tuple(3, 3);
  25. // ...as well as a type for C++ double
  26. np::dtype dtype = np::dtype::get_builtin<double>();
  27. // Construct an array with the above shape and type
  28. np::ndarray a = np::zeros(shape, dtype);
  29. // Print the array
  30. std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
  31. // Print the datatype of the elements
  32. std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
  33. // Using user defined dtypes to create dtype and an array of the custom dtype
  34. // First create a tuple with a variable name and its dtype, double, to create a custom dtype
  35. p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
  36. // The list needs to be created, because the constructor to create the custom dtype
  37. // takes a list of (variable,variable_type) as an argument
  38. p::list list_for_dtype ;
  39. list_for_dtype.append(for_custom_dtype) ;
  40. // Create the custom dtype
  41. np::dtype custom_dtype = np::dtype(list_for_dtype) ;
  42. // Create an ndarray with the custom dtype
  43. np::ndarray new_array = np::zeros(shape,custom_dtype);
  44. }