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/python/detail/type_traits.hpp>
17 #include <boost/python/numpy/numpy_object_mgr_traits.hpp>
18 #include <boost/python/numpy/dtype.hpp>
19 #include <boost/python/numpy/config.hpp>
23 namespace boost { namespace python { namespace numpy {
26 * @brief A boost.python "object manager" (subclass of object) for numpy.ndarray.
28 * @todo This could have a lot more functionality (like boost::python::numeric::array).
29 * Right now all that exists is what was needed to move raw data between C++ and Python.
32 class BOOST_NUMPY_DECL ndarray : public object
36 * @brief An internal struct that's byte-compatible with PyArrayObject.
38 * This is just a hack to allow inline access to this stuff while hiding numpy/arrayobject.h
47 Py_intptr_t * strides;
51 PyObject * weakreflist;
54 /// @brief Return the held Python object as an array_struct.
55 array_struct * get_struct() const { return reinterpret_cast<array_struct*>(this->ptr()); }
60 * @brief Enum to represent (some) of Numpy's internal flags.
62 * These don't match the actual Numpy flag values; we can't get those without including
63 * numpy/arrayobject.h or copying them directly. That's very unfortunate.
65 * @todo I'm torn about whether this should be an enum. It's very convenient to not
66 * make these simple integer values for overloading purposes, but the need to
67 * define every possible combination and custom bitwise operators is ugly.
71 NONE=0x0, C_CONTIGUOUS=0x1, F_CONTIGUOUS=0x2, V_CONTIGUOUS=0x1|0x2,
72 ALIGNED=0x4, WRITEABLE=0x8, BEHAVED=0x4|0x8,
73 CARRAY_RO=0x1|0x4, CARRAY=0x1|0x4|0x8, CARRAY_MIS=0x1|0x8,
74 FARRAY_RO=0x2|0x4, FARRAY=0x2|0x4|0x8, FARRAY_MIS=0x2|0x8,
75 UPDATE_ALL=0x1|0x2|0x4, VARRAY=0x1|0x2|0x8, ALL=0x1|0x2|0x4|0x8
78 BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(ndarray, object);
80 /// @brief Return a view of the scalar with the given dtype.
81 ndarray view(dtype const & dt) const;
83 /// @brief Copy the array, cast to a specified type.
84 ndarray astype(dtype const & dt) const;
86 /// @brief Copy the scalar (deep for all non-object fields).
89 /// @brief Return the size of the nth dimension. raises IndexError if k not in [-get_nd() : get_nd()-1 ]
90 Py_intptr_t shape(int n) const;
92 /// @brief Return the stride of the nth dimension. raises IndexError if k not in [-get_nd() : get_nd()-1]
93 Py_intptr_t strides(int n) const;
96 * @brief Return the array's raw data pointer.
98 * This returns char so stride math works properly on it. It's pretty much
99 * expected that the user will have to reinterpret_cast it.
101 char * get_data() const { return get_struct()->data; }
103 /// @brief Return the array's data-type descriptor object.
104 dtype get_dtype() const;
106 /// @brief Return the object that owns the array's data, or None if the array owns its own data.
107 object get_base() const;
109 /// @brief Set the object that owns the array's data. Use with care.
110 void set_base(object const & base);
112 /// @brief Return the shape of the array as an array of integers (length == get_nd()).
113 Py_intptr_t const * get_shape() const { return get_struct()->shape; }
115 /// @brief Return the stride of the array as an array of integers (length == get_nd()).
116 Py_intptr_t const * get_strides() const { return get_struct()->strides; }
118 /// @brief Return the number of array dimensions.
119 int get_nd() const { return get_struct()->nd; }
121 /// @brief Return the array flags.
122 bitflag get_flags() const;
124 /// @brief Reverse the dimensions of the array.
125 ndarray transpose() const;
127 /// @brief Eliminate any unit-sized dimensions.
128 ndarray squeeze() const;
130 /// @brief Equivalent to self.reshape(*shape) in Python.
131 ndarray reshape(python::tuple const & shape) const;
134 * @brief If the array contains only a single element, return it as an array scalar; otherwise return
137 * @internal This is simply a call to PyArray_Return();
139 object scalarize() const;
143 * @brief Construct a new array with the given shape and data type, with data initialized to zero.
145 BOOST_NUMPY_DECL ndarray zeros(python::tuple const & shape, dtype const & dt);
146 BOOST_NUMPY_DECL ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
149 * @brief Construct a new array with the given shape and data type, with data left uninitialized.
151 BOOST_NUMPY_DECL ndarray empty(python::tuple const & shape, dtype const & dt);
152 BOOST_NUMPY_DECL ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
155 * @brief Construct a new array from an arbitrary Python sequence.
157 * @todo This does't seem to handle ndarray subtypes the same way that "numpy.array" does in Python.
159 BOOST_NUMPY_DECL ndarray array(object const & obj);
160 BOOST_NUMPY_DECL ndarray array(object const & obj, dtype const & dt);
165 BOOST_NUMPY_DECL ndarray from_data_impl(void * data,
167 std::vector<Py_intptr_t> const & shape,
168 std::vector<Py_intptr_t> const & strides,
169 object const & owner,
172 template <typename Container>
173 ndarray from_data_impl(void * data,
177 object const & owner,
179 typename boost::enable_if< boost::python::detail::is_integral<typename Container::value_type> >::type * enabled = NULL)
181 std::vector<Py_intptr_t> shape_(shape.begin(),shape.end());
182 std::vector<Py_intptr_t> strides_(strides.begin(), strides.end());
183 return from_data_impl(data, dt, shape_, strides_, owner, writeable);
186 BOOST_NUMPY_DECL ndarray from_data_impl(void * data,
188 object const & shape,
189 object const & strides,
190 object const & owner,
193 } // namespace boost::python::numpy::detail
196 * @brief Construct a new ndarray object from a raw pointer.
198 * @param[in] data Raw pointer to the first element of the array.
199 * @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
200 * @param[in] shape Shape of the array as STL container of integers; must have begin() and end().
201 * @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
202 * @param[in] owner An arbitray Python object that owns that data pointer. The array object will
203 * keep a reference to the object, and decrement it's reference count when the
204 * array goes out of scope. Pass None at your own peril.
206 * @todo Should probably take ranges of iterators rather than actual container objects.
208 template <typename Container>
209 inline ndarray from_data(void * data,
213 python::object const & owner)
215 return numpy::detail::from_data_impl(data, dt, shape, strides, owner, true);
219 * @brief Construct a new ndarray object from a raw pointer.
221 * @param[in] data Raw pointer to the first element of the array.
222 * @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
223 * @param[in] shape Shape of the array as STL container of integers; must have begin() and end().
224 * @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
225 * @param[in] owner An arbitray Python object that owns that data pointer. The array object will
226 * keep a reference to the object, and decrement it's reference count when the
227 * array goes out of scope. Pass None at your own peril.
229 * This overload takes a const void pointer and sets the "writeable" flag of the array to false.
231 * @todo Should probably take ranges of iterators rather than actual container objects.
233 template <typename Container>
234 inline ndarray from_data(void const * data,
238 python::object const & owner)
240 return numpy::detail::from_data_impl(const_cast<void*>(data), dt, shape, strides, owner, false);
244 * @brief Transform an arbitrary object into a numpy array with the given requirements.
246 * @param[in] obj An arbitrary python object to convert. Arrays that meet the requirements
247 * will be passed through directly.
248 * @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
249 * @param[in] nd_min Minimum number of dimensions.
250 * @param[in] nd_max Maximum number of dimensions.
251 * @param[in] flags Bitwise OR of flags specifying additional requirements.
253 BOOST_NUMPY_DECL ndarray from_object(object const & obj,
257 ndarray::bitflag flags=ndarray::NONE);
259 BOOST_NUMPY_DECL inline ndarray from_object(object const & obj,
262 ndarray::bitflag flags=ndarray::NONE)
264 return from_object(obj, dt, nd, nd, flags);
267 BOOST_NUMPY_DECL inline ndarray from_object(object const & obj,
269 ndarray::bitflag flags=ndarray::NONE)
271 return from_object(obj, dt, 0, 0, flags);
274 BOOST_NUMPY_DECL ndarray from_object(object const & obj,
277 ndarray::bitflag flags=ndarray::NONE);
279 BOOST_NUMPY_DECL inline ndarray from_object(object const & obj,
281 ndarray::bitflag flags=ndarray::NONE)
283 return from_object(obj, nd, nd, flags);
286 BOOST_NUMPY_DECL inline ndarray from_object(object const & obj,
287 ndarray::bitflag flags=ndarray::NONE)
289 return from_object(obj, 0, 0, flags);
292 BOOST_NUMPY_DECL inline ndarray::bitflag operator|(ndarray::bitflag a,
295 return ndarray::bitflag(int(a) | int(b));
298 BOOST_NUMPY_DECL inline ndarray::bitflag operator&(ndarray::bitflag a,
301 return ndarray::bitflag(int(a) & int(b));
304 } // namespace boost::python::numpy
309 NUMPY_OBJECT_MANAGER_TRAITS(numpy::ndarray);
311 }}} // namespace boost::python::converter