1 // Copyright Jim Bosch 2010-2012.
2 // Copyright Stefan Seefeld 2016.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
7 #ifndef boost_python_numpy_ndarray_hpp_
8 #define boost_python_numpy_ndarray_hpp_
11 * @brief Object manager and various utilities for numpy.ndarray.
14 #include <boost/python.hpp>
15 #include <boost/utility/enable_if.hpp>
16 #include <boost/type_traits/is_integral.hpp>
17 #include <boost/python/numpy/numpy_object_mgr_traits.hpp>
18 #include <boost/python/numpy/dtype.hpp>
21 namespace boost { namespace python { namespace numpy {
24 * @brief A boost.python "object manager" (subclass of object) for numpy.ndarray.
26 * @todo This could have a lot more functionality (like boost::python::numeric::array).
27 * Right now all that exists is what was needed to move raw data between C++ and Python.
29 class ndarray : public object
33 * @brief An internal struct that's byte-compatible with PyArrayObject.
35 * This is just a hack to allow inline access to this stuff while hiding numpy/arrayobject.h
44 Py_intptr_t * strides;
48 PyObject * weakreflist;
51 /// @brief Return the held Python object as an array_struct.
52 array_struct * get_struct() const { return reinterpret_cast<array_struct*>(this->ptr()); }
57 * @brief Enum to represent (some) of Numpy's internal flags.
59 * These don't match the actual Numpy flag values; we can't get those without including
60 * numpy/arrayobject.h or copying them directly. That's very unfortunate.
62 * @todo I'm torn about whether this should be an enum. It's very convenient to not
63 * make these simple integer values for overloading purposes, but the need to
64 * define every possible combination and custom bitwise operators is ugly.
68 NONE=0x0, C_CONTIGUOUS=0x1, F_CONTIGUOUS=0x2, V_CONTIGUOUS=0x1|0x2,
69 ALIGNED=0x4, WRITEABLE=0x8, BEHAVED=0x4|0x8,
70 CARRAY_RO=0x1|0x4, CARRAY=0x1|0x4|0x8, CARRAY_MIS=0x1|0x8,
71 FARRAY_RO=0x2|0x4, FARRAY=0x2|0x4|0x8, FARRAY_MIS=0x2|0x8,
72 UPDATE_ALL=0x1|0x2|0x4, VARRAY=0x1|0x2|0x8, ALL=0x1|0x2|0x4|0x8
75 BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(ndarray, object);
77 /// @brief Return a view of the scalar with the given dtype.
78 ndarray view(dtype const & dt) const;
80 /// @brief Copy the array, cast to a specified type.
81 ndarray astype(dtype const & dt) const;
83 /// @brief Copy the scalar (deep for all non-object fields).
86 /// @brief Return the size of the nth dimension.
87 Py_intptr_t shape(int n) const { return get_shape()[n]; }
89 /// @brief Return the stride of the nth dimension.
90 Py_intptr_t strides(int n) const { return get_strides()[n]; }
93 * @brief Return the array's raw data pointer.
95 * This returns char so stride math works properly on it. It's pretty much
96 * expected that the user will have to reinterpret_cast it.
98 char * get_data() const { return get_struct()->data; }
100 /// @brief Return the array's data-type descriptor object.
101 dtype get_dtype() const;
103 /// @brief Return the object that owns the array's data, or None if the array owns its own data.
104 object get_base() const;
106 /// @brief Set the object that owns the array's data. Use with care.
107 void set_base(object const & base);
109 /// @brief Return the shape of the array as an array of integers (length == get_nd()).
110 Py_intptr_t const * get_shape() const { return get_struct()->shape; }
112 /// @brief Return the stride of the array as an array of integers (length == get_nd()).
113 Py_intptr_t const * get_strides() const { return get_struct()->strides; }
115 /// @brief Return the number of array dimensions.
116 int get_nd() const { return get_struct()->nd; }
118 /// @brief Return the array flags.
119 bitflag get_flags() const;
121 /// @brief Reverse the dimensions of the array.
122 ndarray transpose() const;
124 /// @brief Eliminate any unit-sized dimensions.
125 ndarray squeeze() const;
127 /// @brief Equivalent to self.reshape(*shape) in Python.
128 ndarray reshape(python::tuple const & shape) const;
131 * @brief If the array contains only a single element, return it as an array scalar; otherwise return
134 * @internal This is simply a call to PyArray_Return();
136 object scalarize() const;
140 * @brief Construct a new array with the given shape and data type, with data initialized to zero.
142 ndarray zeros(python::tuple const & shape, dtype const & dt);
143 ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
146 * @brief Construct a new array with the given shape and data type, with data left uninitialized.
148 ndarray empty(python::tuple const & shape, dtype const & dt);
149 ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
152 * @brief Construct a new array from an arbitrary Python sequence.
154 * @todo This does't seem to handle ndarray subtypes the same way that "numpy.array" does in Python.
156 ndarray array(object const & obj);
157 ndarray array(object const & obj, dtype const & dt);
162 ndarray from_data_impl(void * data,
164 std::vector<Py_intptr_t> const & shape,
165 std::vector<Py_intptr_t> const & strides,
166 object const & owner,
169 template <typename Container>
170 ndarray from_data_impl(void * data,
174 object const & owner,
176 typename boost::enable_if< boost::is_integral<typename Container::value_type> >::type * enabled = NULL)
178 std::vector<Py_intptr_t> shape_(shape.begin(),shape.end());
179 std::vector<Py_intptr_t> strides_(strides.begin(), strides.end());
180 return from_data_impl(data, dt, shape_, strides_, owner, writeable);
183 ndarray from_data_impl(void * data,
185 object const & shape,
186 object const & strides,
187 object const & owner,
190 } // namespace boost::python::numpy::detail
193 * @brief Construct a new ndarray object from a raw pointer.
195 * @param[in] data Raw pointer to the first element of the array.
196 * @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
197 * @param[in] shape Shape of the array as STL container of integers; must have begin() and end().
198 * @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
199 * @param[in] owner An arbitray Python object that owns that data pointer. The array object will
200 * keep a reference to the object, and decrement it's reference count when the
201 * array goes out of scope. Pass None at your own peril.
203 * @todo Should probably take ranges of iterators rather than actual container objects.
205 template <typename Container>
206 inline ndarray from_data(void * data,
210 python::object const & owner)
212 return numpy::detail::from_data_impl(data, dt, shape, strides, owner, true);
216 * @brief Construct a new ndarray object from a raw pointer.
218 * @param[in] data Raw pointer to the first element of the array.
219 * @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
220 * @param[in] shape Shape of the array as STL container of integers; must have begin() and end().
221 * @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
222 * @param[in] owner An arbitray Python object that owns that data pointer. The array object will
223 * keep a reference to the object, and decrement it's reference count when the
224 * array goes out of scope. Pass None at your own peril.
226 * This overload takes a const void pointer and sets the "writeable" flag of the array to false.
228 * @todo Should probably take ranges of iterators rather than actual container objects.
230 template <typename Container>
231 inline ndarray from_data(void const * data,
235 python::object const & owner)
237 return numpy::detail::from_data_impl(const_cast<void*>(data), dt, shape, strides, owner, false);
241 * @brief Transform an arbitrary object into a numpy array with the given requirements.
243 * @param[in] obj An arbitrary python object to convert. Arrays that meet the requirements
244 * will be passed through directly.
245 * @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
246 * @param[in] nd_min Minimum number of dimensions.
247 * @param[in] nd_max Maximum number of dimensions.
248 * @param[in] flags Bitwise OR of flags specifying additional requirements.
250 ndarray from_object(object const & obj, dtype const & dt,
251 int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
253 inline ndarray from_object(object const & obj, dtype const & dt,
254 int nd, ndarray::bitflag flags=ndarray::NONE)
256 return from_object(obj, dt, nd, nd, flags);
259 inline ndarray from_object(object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE)
261 return from_object(obj, dt, 0, 0, flags);
264 ndarray from_object(object const & obj, int nd_min, int nd_max,
265 ndarray::bitflag flags=ndarray::NONE);
267 inline ndarray from_object(object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE)
269 return from_object(obj, nd, nd, flags);
272 inline ndarray from_object(object const & obj, ndarray::bitflag flags=ndarray::NONE)
274 return from_object(obj, 0, 0, flags);
277 inline ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b)
279 return ndarray::bitflag(int(a) | int(b));
282 inline ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b)
284 return ndarray::bitflag(int(a) & int(b));
287 } // namespace boost::python::numpy
292 NUMPY_OBJECT_MANAGER_TRAITS(numpy::ndarray);
294 }}} // namespace boost::python::converter