numpy.h 15.1 KB
Newer Older
Wenzel Jakob's avatar
Wenzel Jakob committed
1
/*
2
    pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
Wenzel Jakob's avatar
Wenzel Jakob committed
3

4
    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob's avatar
Wenzel Jakob committed
5
6
7
8
9
10
11

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

#pragma once

12
13
#include "pybind11.h"
#include "complex.h"
14
15
#include <numeric>
#include <algorithm>
16

Wenzel Jakob's avatar
Wenzel Jakob committed
17
18
19
20
21
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
#endif

22
NAMESPACE_BEGIN(pybind11)
23
namespace detail { template <typename type, typename SFINAE = void> struct npy_format_descriptor { }; }
Wenzel Jakob's avatar
Wenzel Jakob committed
24

Wenzel Jakob's avatar
Wenzel Jakob committed
25
class array : public buffer {
Wenzel Jakob's avatar
Wenzel Jakob committed
26
public:
Wenzel Jakob's avatar
Wenzel Jakob committed
27
28
29
30
31
32
33
    struct API {
        enum Entries {
            API_PyArray_Type = 2,
            API_PyArray_DescrFromType = 45,
            API_PyArray_FromAny = 69,
            API_PyArray_NewCopy = 85,
            API_PyArray_NewFromDescr = 94,
34
35
36
37
38
39
40
41
42
43
44
45
46

            NPY_C_CONTIGUOUS_ = 0x0001,
            NPY_F_CONTIGUOUS_ = 0x0002,
            NPY_ARRAY_FORCECAST_ = 0x0010,
            NPY_ENSURE_ARRAY_ = 0x0040,
            NPY_BOOL_ = 0,
            NPY_BYTE_, NPY_UBYTE_,
            NPY_SHORT_, NPY_USHORT_,
            NPY_INT_, NPY_UINT_,
            NPY_LONG_, NPY_ULONG_,
            NPY_LONGLONG_, NPY_ULONGLONG_,
            NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_,
            NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_
Wenzel Jakob's avatar
Wenzel Jakob committed
47
48
49
        };

        static API lookup() {
50
51
            module m = module::import("numpy.core.multiarray");
            object c = (object) m.attr("_ARRAY_API");
52
#if PY_MAJOR_VERSION >= 3
53
            void **api_ptr = (void **) (c ? PyCapsule_GetPointer(c.ptr(), NULL) : nullptr);
54
#else
55
            void **api_ptr = (void **) (c ? PyCObject_AsVoidPtr(c.ptr()) : nullptr);
56
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
57
            API api;
58
59
60
61
62
63
64
#define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
            DECL_NPY_API(PyArray_Type);
            DECL_NPY_API(PyArray_DescrFromType);
            DECL_NPY_API(PyArray_FromAny);
            DECL_NPY_API(PyArray_NewCopy);
            DECL_NPY_API(PyArray_NewFromDescr);
#undef DECL_NPY_API
Wenzel Jakob's avatar
Wenzel Jakob committed
65
66
67
            return api;
        }

68
        bool PyArray_Check_(PyObject *obj) const { return (bool) PyObject_TypeCheck(obj, PyArray_Type_); }
Wenzel Jakob's avatar
Wenzel Jakob committed
69

70
71
        PyObject *(*PyArray_DescrFromType_)(int);
        PyObject *(*PyArray_NewFromDescr_)
Wenzel Jakob's avatar
Wenzel Jakob committed
72
73
            (PyTypeObject *, PyObject *, int, Py_intptr_t *,
             Py_intptr_t *, void *, int, PyObject *);
74
75
76
        PyObject *(*PyArray_NewCopy_)(PyObject *, int);
        PyTypeObject *PyArray_Type_;
        PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *);
Wenzel Jakob's avatar
Wenzel Jakob committed
77
    };
Wenzel Jakob's avatar
Wenzel Jakob committed
78

79
    PYBIND11_OBJECT_DEFAULT(array, buffer, lookup_api().PyArray_Check_)
Wenzel Jakob's avatar
Wenzel Jakob committed
80

81
82
    enum {
        c_style = API::NPY_C_CONTIGUOUS_,
83
84
        f_style = API::NPY_F_CONTIGUOUS_,
        forcecast = API::NPY_ARRAY_FORCECAST_
85
86
    };

Wenzel Jakob's avatar
Wenzel Jakob committed
87
88
    template <typename Type> array(size_t size, const Type *ptr) {
        API& api = lookup_api();
89
        PyObject *descr = api.PyArray_DescrFromType_(detail::npy_format_descriptor<Type>::typenum());
Wenzel Jakob's avatar
Wenzel Jakob committed
90
        if (descr == nullptr)
Wenzel Jakob's avatar
Wenzel Jakob committed
91
            pybind11_fail("NumPy: unsupported buffer format!");
Wenzel Jakob's avatar
Wenzel Jakob committed
92
        Py_intptr_t shape = (Py_intptr_t) size;
93
94
95
96
97
        object tmp = object(api.PyArray_NewFromDescr_(
            api.PyArray_Type_, descr, 1, &shape, nullptr, (void *) ptr, 0, nullptr), false);
        if (ptr && tmp)
            tmp = object(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */), false);
        if (!tmp)
Wenzel Jakob's avatar
Wenzel Jakob committed
98
99
            pybind11_fail("NumPy: unable to create array!");
        m_ptr = tmp.release().ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
100
101
102
103
    }

    array(const buffer_info &info) {
        API& api = lookup_api();
104
        if ((info.format.size() < 1) || (info.format.size() > 2))
Wenzel Jakob's avatar
Wenzel Jakob committed
105
            pybind11_fail("Unsupported buffer format!");
Wenzel Jakob's avatar
Wenzel Jakob committed
106
        int fmt = (int) info.format[0];
107
108
109
110
        if (info.format == "Zd")      fmt = API::NPY_CDOUBLE_;
        else if (info.format == "Zf") fmt = API::NPY_CFLOAT_;

        PyObject *descr = api.PyArray_DescrFromType_(fmt);
Wenzel Jakob's avatar
Wenzel Jakob committed
111
        if (descr == nullptr)
Wenzel Jakob's avatar
Wenzel Jakob committed
112
            pybind11_fail("NumPy: unsupported buffer format '" + info.format + "'!");
113
        object tmp(api.PyArray_NewFromDescr_(
114
            api.PyArray_Type_, descr, (int) info.ndim, (Py_intptr_t *) &info.shape[0],
115
116
117
118
            (Py_intptr_t *) &info.strides[0], info.ptr, 0, nullptr), false);
        if (info.ptr && tmp)
            tmp = object(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */), false);
        if (!tmp)
Wenzel Jakob's avatar
Wenzel Jakob committed
119
120
            pybind11_fail("NumPy: unable to create array!");
        m_ptr = tmp.release().ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
121
122
123
124
125
126
127
128
129
    }

protected:
    static API &lookup_api() {
        static API api = API::lookup();
        return api;
    }
};

130
template <typename T, int ExtraFlags = array::forcecast> class array_t : public array {
Wenzel Jakob's avatar
Wenzel Jakob committed
131
public:
132
    PYBIND11_OBJECT_CVT(array_t, array, is_non_null, m_ptr = ensure(m_ptr));
133
    array_t() : array() { }
Johan Mabille's avatar
Johan Mabille committed
134
    array_t(const buffer_info& info) : array(info) {}
Wenzel Jakob's avatar
Wenzel Jakob committed
135
    static bool is_non_null(PyObject *ptr) { return ptr != nullptr; }
136
    static PyObject *ensure(PyObject *ptr) {
137
138
        if (ptr == nullptr)
            return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
139
        API &api = lookup_api();
140
        PyObject *descr = api.PyArray_DescrFromType_(detail::npy_format_descriptor<T>::typenum());
141
142
143
        PyObject *result = api.PyArray_FromAny_(ptr, descr, 0, 0, API::NPY_ENSURE_ARRAY_ | ExtraFlags, nullptr);
        if (!result)
            PyErr_Clear();
144
145
        Py_DECREF(ptr);
        return result;
Wenzel Jakob's avatar
Wenzel Jakob committed
146
147
148
    }
};

149
150
NAMESPACE_BEGIN(detail)

151
152
template <typename T> struct npy_format_descriptor<T, typename std::enable_if<std::is_integral<T>::value>::type> {
private:
Johan Mabille's avatar
Johan Mabille committed
153
    constexpr static const int values[8] = {
154
155
156
        array::API::NPY_BYTE_, array::API::NPY_UBYTE_, array::API::NPY_SHORT_,    array::API::NPY_USHORT_,
        array::API::NPY_INT_,  array::API::NPY_UINT_,  array::API::NPY_LONGLONG_, array::API::NPY_ULONGLONG_ };
public:
157
    static int typenum() { return values[detail::log2(sizeof(T)) * 2 + (std::is_unsigned<T>::value ? 1 : 0)]; }
158
159
160
161
    template <typename T2 = T, typename std::enable_if<std::is_signed<T2>::value, int>::type = 0>
    static PYBIND11_DESCR name() { return _("int") + _<sizeof(T)*8>(); }
    template <typename T2 = T, typename std::enable_if<!std::is_signed<T2>::value, int>::type = 0>
    static PYBIND11_DESCR name() { return _("uint") + _<sizeof(T)*8>(); }
162
163
164
165
};
template <typename T> constexpr const int npy_format_descriptor<
    T, typename std::enable_if<std::is_integral<T>::value>::type>::values[8];

166
#define DECL_FMT(Type, NumPyName, Name) template<> struct npy_format_descriptor<Type> { \
167
    static int typenum() { return array::API::NumPyName; }         \
168
    static PYBIND11_DESCR name() { return _(Name); } }
169
170
171
172
173
DECL_FMT(float, NPY_FLOAT_, "float32");
DECL_FMT(double, NPY_DOUBLE_, "float64");
DECL_FMT(bool, NPY_BOOL_, "bool");
DECL_FMT(std::complex<float>, NPY_CFLOAT_, "complex64");
DECL_FMT(std::complex<double>, NPY_CDOUBLE_, "complex128");
174
175
#undef DECL_FMT

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
template  <class T>
using array_iterator = typename std::add_pointer<T>::type;

template <class T>
array_iterator<T> array_begin(const buffer_info& buffer) {
    return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr));
}

template <class T>
array_iterator<T> array_end(const buffer_info& buffer) {
    return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr) + buffer.size);
}

class common_iterator {
public:
    using container_type = std::vector<size_t>;
    using value_type = container_type::value_type;
    using size_type = container_type::size_type;

    common_iterator() : p_ptr(0), m_strides() {}
196

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    common_iterator(void* ptr, const container_type& strides, const std::vector<size_t>& shape)
        : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) {
        m_strides.back() = static_cast<value_type>(strides.back());
        for (size_type i = m_strides.size() - 1; i != 0; --i) {
            size_type j = i - 1;
            value_type s = static_cast<value_type>(shape[i]);
            m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
        }
    }

    void increment(size_type dim) {
        p_ptr += m_strides[dim];
    }

    void* data() const {
        return p_ptr;
    }

private:
    char* p_ptr;
    container_type m_strides;
};

220
template <size_t N> class multi_array_iterator {
221
222
223
public:
    using container_type = std::vector<size_t>;

224
225
226
227
228
    multi_array_iterator(const std::array<buffer_info, N> &buffers,
                         const std::vector<size_t> &shape)
        : m_shape(shape.size()), m_index(shape.size(), 0),
          m_common_iterator() {

229
        // Manual copy to avoid conversion warning if using std::copy
230
        for (size_t i = 0; i < shape.size(); ++i)
231
232
233
            m_shape[i] = static_cast<container_type::value_type>(shape[i]);

        container_type strides(shape.size());
234
        for (size_t i = 0; i < N; ++i)
235
236
237
238
239
240
241
242
243
            init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
    }

    multi_array_iterator& operator++() {
        for (size_t j = m_index.size(); j != 0; --j) {
            size_t i = j - 1;
            if (++m_index[i] != m_shape[i]) {
                increment_common_iterator(i);
                break;
244
            } else {
245
246
247
248
249
250
                m_index[i] = 0;
            }
        }
        return *this;
    }

251
    template <size_t K, class T> const T& data() const {
252
253
254
255
256
257
258
        return *reinterpret_cast<T*>(m_common_iterator[K].data());
    }

private:

    using common_iter = common_iterator;

259
260
261
    void init_common_iterator(const buffer_info &buffer,
                              const std::vector<size_t> &shape,
                              common_iter &iterator, container_type &strides) {
262
263
264
265
266
267
268
        auto buffer_shape_iter = buffer.shape.rbegin();
        auto buffer_strides_iter = buffer.strides.rbegin();
        auto shape_iter = shape.rbegin();
        auto strides_iter = strides.rbegin();

        while (buffer_shape_iter != buffer.shape.rend()) {
            if (*shape_iter == *buffer_shape_iter)
269
                *strides_iter = static_cast<size_t>(*buffer_strides_iter);
270
271
272
273
274
275
276
277
278
279
280
281
282
283
            else
                *strides_iter = 0;

            ++buffer_shape_iter;
            ++buffer_strides_iter;
            ++shape_iter;
            ++strides_iter;
        }

        std::fill(strides_iter, strides.rend(), 0);
        iterator = common_iter(buffer.ptr, strides, shape);
    }

    void increment_common_iterator(size_t dim) {
284
        for (auto &iter : m_common_iterator)
285
286
287
288
289
290
291
292
293
            iter.increment(dim);
    }

    container_type m_shape;
    container_type m_index;
    std::array<common_iter, N> m_common_iterator;
};

template <size_t N>
294
295
bool broadcast(const std::array<buffer_info, N>& buffers, size_t& ndim, std::vector<size_t>& shape) {
    ndim = std::accumulate(buffers.begin(), buffers.end(), size_t(0), [](size_t res, const buffer_info& buf) {
296
297
298
        return std::max(res, buf.ndim);
    });

299
    shape = std::vector<size_t>(ndim, 1);
300
301
302
303
    bool trivial_broadcast = true;
    for (size_t i = 0; i < N; ++i) {
        auto res_iter = shape.rbegin();
        bool i_trivial_broadcast = (buffers[i].size == 1) || (buffers[i].ndim == ndim);
304
305
306
307
        for (auto shape_iter = buffers[i].shape.rbegin();
             shape_iter != buffers[i].shape.rend(); ++shape_iter, ++res_iter) {

            if (*res_iter == 1)
308
                *res_iter = *shape_iter;
309
            else if ((*shape_iter != 1) && (*res_iter != *shape_iter))
310
                pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
311

312
313
314
315
316
317
318
            i_trivial_broadcast = i_trivial_broadcast && (*res_iter == *shape_iter);
        }
        trivial_broadcast = trivial_broadcast && i_trivial_broadcast;
    }
    return trivial_broadcast;
}

319
320
321
322
template <typename Func, typename Return, typename... Args>
struct vectorize_helper {
    typename std::remove_reference<Func>::type f;

323
324
    template <typename T>
    vectorize_helper(T&&f) : f(std::forward<T>(f)) { }
Wenzel Jakob's avatar
Wenzel Jakob committed
325

326
    object operator()(array_t<Args, array::c_style | array::forcecast>... args) {
327
328
        return run(args..., typename make_index_sequence<sizeof...(Args)>::type());
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
329

330
    template <size_t ... Index> object run(array_t<Args, array::c_style | array::forcecast>&... args, index_sequence<Index...> index) {
Wenzel Jakob's avatar
Wenzel Jakob committed
331
        /* Request buffers from all parameters */
332
        const size_t N = sizeof...(Args);
333

Wenzel Jakob's avatar
Wenzel Jakob committed
334
335
336
        std::array<buffer_info, N> buffers {{ args.request()... }};

        /* Determine dimensions parameters of output array */
337
        size_t ndim = 0;
338
339
        std::vector<size_t> shape(0);
        bool trivial_broadcast = broadcast(buffers, ndim, shape);
340

341
        size_t size = 1;
Wenzel Jakob's avatar
Wenzel Jakob committed
342
343
        std::vector<size_t> strides(ndim);
        if (ndim > 0) {
344
            strides[ndim-1] = sizeof(Return);
345
            for (size_t i = ndim - 1; i > 0; --i) {
346
347
348
349
                strides[i - 1] = strides[i] * shape[i];
                size *= shape[i];
            }
            size *= shape[0];
Wenzel Jakob's avatar
Wenzel Jakob committed
350
351
        }

352
        if (size == 1)
353
            return cast(f(*((Args *) buffers[Index].ptr)...));
Wenzel Jakob's avatar
Wenzel Jakob committed
354

355
        array result(buffer_info(nullptr, sizeof(Return),
356
                     format_descriptor<Return>::value(),
Wenzel Jakob's avatar
Wenzel Jakob committed
357
            ndim, shape, strides));
358
359
360
361

        buffer_info buf = result.request();
        Return *output = (Return *) buf.ptr;

362
        if (trivial_broadcast) {
363
364
365
            /* Call the function */
            for (size_t i=0; i<size; ++i) {
                output[i] = f((buffers[Index].size == 1
366
367
                               ? *((Args *) buffers[Index].ptr)
                               : ((Args *) buffers[Index].ptr)[i])...);
368
            }
369
        } else {
370
371
            apply_broadcast<N, Index...>(buffers, buf, index);
        }
372
373

        return result;
374
    }
375
376

    template <size_t N, size_t... Index>
377
378
    void apply_broadcast(const std::array<buffer_info, N> &buffers,
                         buffer_info &output, index_sequence<Index...>) {
379
380
381
382
383
384
        using input_iterator = multi_array_iterator<N>;
        using output_iterator = array_iterator<Return>;

        input_iterator input_iter(buffers, output.shape);
        output_iterator output_end = array_end<Return>(output);

385
386
        for (output_iterator iter = array_begin<Return>(output);
             iter != output_end; ++iter, ++input_iter) {
387
388
389
            *iter = f((input_iter.template data<Index, Args>())...);
        }
    }
390
391
};

392
template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> {
393
    static PYBIND11_DESCR name() { return _("numpy.ndarray[") + type_caster<T>::name() + _("]"); }
394
395
};

396
NAMESPACE_END(detail)
Wenzel Jakob's avatar
Wenzel Jakob committed
397

398
399
400
template <typename Func, typename Return, typename... Args>
detail::vectorize_helper<Func, Return, Args...> vectorize(const Func &f, Return (*) (Args ...)) {
    return detail::vectorize_helper<Func, Return, Args...>(f);
Wenzel Jakob's avatar
Wenzel Jakob committed
401
402
}

403
404
405
template <typename Return, typename... Args>
detail::vectorize_helper<Return (*) (Args ...), Return, Args...> vectorize(Return (*f) (Args ...)) {
    return vectorize<Return (*) (Args ...), Return, Args...>(f, f);
Wenzel Jakob's avatar
Wenzel Jakob committed
406
407
408
409
410
411
412
413
}

template <typename func> auto vectorize(func &&f) -> decltype(
        vectorize(std::forward<func>(f), (typename detail::remove_class<decltype(&std::remove_reference<func>::type::operator())>::type *) nullptr)) {
    return vectorize(std::forward<func>(f), (typename detail::remove_class<decltype(
                   &std::remove_reference<func>::type::operator())>::type *) nullptr);
}

414
NAMESPACE_END(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
415
416
417
418

#if defined(_MSC_VER)
#pragma warning(pop)
#endif