array.cc 60.1 KB
Newer Older
Christoph Groth's avatar
Christoph Groth committed
1
// Copyright 2012-2016 Tinyarray authors.
Christoph Groth's avatar
Christoph Groth committed
2
3
//
// This file is part of Tinyarray.  It is subject to the license terms in the
4
5
6
7
8
// file LICENSE.rst found in the top-level directory of this distribution and
// at https://gitlab.kwant-project.org/kwant/tinyarray/blob/master/LICENSE.rst.
// A list of Tinyarray authors can be found in the README.rst file at the
// top-level directory of this distribution and at
// https://gitlab.kwant-project.org/kwant/tinyarray.
Christoph Groth's avatar
Christoph Groth committed
9
10
11
12
13

#include <Python.h>
#include <cstddef>
#include <sstream>
#include <limits>
Christoph Groth's avatar
Christoph Groth committed
14
#include <algorithm>
Christoph Groth's avatar
Christoph Groth committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "array.hh"
#include "arithmetic.hh"
#include "functions.hh"
#include "conversion.hh"
#include "version.hh"

template <>
const char *Array<long>::pyformat = "l";
template <>
const char *Array<double>::pyformat = "d";
template <>
const char *Array<Complex>::pyformat = "Zd";

const char *dtype_names[] = {"int", "float", "complex"};

const char *format_names[] = {
    "int32 little endian", "int32 big endian",
    "int64 little endian", "int64 big endian",
    "float64 little endian", "float64 big endian",
    "complex128 little endian", "complex128 big endian",
    "unknown"};

Format format_by_dtype[NONE];

namespace {

bool is_big_endian()
{
    union {
        unsigned int i;
        char c[4];
    } bint = {0x0a0b0c0d};

    if (bint.c[0] == 0x0a) {
        assert(bint.c[1] == 0x0b);
        assert(bint.c[2] == 0x0c);
        assert(bint.c[3] == 0x0d);
        return true;
    } else {
        assert(bint.c[0] == 0x0d);
        assert(bint.c[1] == 0x0c);
        assert(bint.c[2] == 0x0b);
        assert(bint.c[3] == 0x0a);
        return false;
    }
}

PyObject *int_str, *long_str, *float_str, *complex_str, *index_str,
    *reconstruct;

Dtype dtype_of_scalar(PyObject *obj)
{
    if (PyComplex_Check(obj)) return COMPLEX;
    if (PyFloat_Check(obj)) return DOUBLE;
    if (PyInt_Check(obj)) return LONG;
    // TODO: The following line should be removed for Python 3.
    if (PyLong_Check(obj)) return LONG;
    if (PyObject_HasAttr(obj, index_str)) return LONG;

    if (PyObject_HasAttr(obj, complex_str)) return COMPLEX;
    if (PyObject_HasAttr(obj, float_str)) return DOUBLE;
    if (PyObject_HasAttr(obj, int_str)) return LONG;
    // TODO: The following line should be removed for Python 3.
    if (PyObject_HasAttr(obj, long_str)) return LONG;

    return NONE;
}

Michael Wimmer's avatar
Michael Wimmer committed
83
84
Dtype dtype_of_buffer(Py_buffer *view)
{
Joseph Weston's avatar
Joseph Weston committed
85
    const char *fmt = view->format;
Christoph Groth's avatar
Christoph Groth committed
86
    Dtype dtype = NONE;
Michael Wimmer's avatar
Michael Wimmer committed
87

Christoph Groth's avatar
Christoph Groth committed
88
89
    // Currently, we only understand native endianness and alignment.
    if (*fmt == '@') fmt++;
Michael Wimmer's avatar
Michael Wimmer committed
90

91
    if (strchr("cbB?hHiIlLqQnN", *fmt)) {
Christoph Groth's avatar
Christoph Groth committed
92
        dtype = LONG;
Michael Wimmer's avatar
Michael Wimmer committed
93
        fmt++;
Christoph Groth's avatar
Christoph Groth committed
94
95
    } else if (strchr("fdg", *fmt)) {
        dtype = DOUBLE;
Michael Wimmer's avatar
Michael Wimmer committed
96
        fmt++;
Christoph Groth's avatar
Christoph Groth committed
97
    } else if (*fmt == 'Z') {
Michael Wimmer's avatar
Michael Wimmer committed
98
        fmt++;
Christoph Groth's avatar
Christoph Groth committed
99
100
        if (strchr("fdg", *fmt)) {
            dtype = COMPLEX;
Michael Wimmer's avatar
Michael Wimmer committed
101
102
103
104
        }
        fmt++;
    }

Christoph Groth's avatar
Christoph Groth committed
105
    // Right now, no composite data structures are supported; if we found a
Christoph Groth's avatar
Christoph Groth committed
106
    // single supported data type, we should be at the end of the string.
Christoph Groth's avatar
Christoph Groth committed
107
    if (*fmt != '\0') return NONE;
Michael Wimmer's avatar
Michael Wimmer committed
108
109
110
111

    return dtype;
}

Christoph Groth's avatar
Christoph Groth committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
template<typename O, typename I>
PyObject *convert_array(PyObject *in_, int ndim, size_t *shape)
{
    assert(Array<I>::check_exact(in_)); Array<I> *in = (Array<I>*)in_;
    size_t size;
    if (ndim == -1) {
        assert(shape == 0);
        in->ndim_shape(&ndim, &shape);
    } else {
#ifndef NDEBUG
        int in_ndim;
        size_t *in_shape;
        in->ndim_shape(&in_ndim, &in_shape);
        assert(shape);
        assert(calc_size(ndim, shape) == calc_size(in_ndim, in_shape));
#endif
    }
    Array<O> *out = Array<O>::make(ndim, shape, &size);
    I *src = in->data();
    O *dest = out->data();
    for (size_t i = 0; i < size; ++i) dest[i] = src[i];
    return (PyObject*)out;
}

typedef PyObject *Convert_array(PyObject*, int, size_t*);

Convert_array *convert_array_dtable[][3] = {
    {convert_array<long, long>,
     convert_array<long, double>,
     0},
    {convert_array<double, long>,
     convert_array<double, double>,
     0},
    {convert_array<Complex, long>,
     convert_array<Complex, double>,
     convert_array<Complex, Complex>}
};

PyObject *convert_array(Dtype dtype_out, PyObject *in, Dtype dtype_in,
                        int ndim = -1, size_t *shape = 0)
{
    if (dtype_in == NONE)
        dtype_in = get_dtype(in);
    assert(get_dtype(in) == get_dtype(in));
    Convert_array *func = convert_array_dtable[int(dtype_out)][int(dtype_in)];
    if (!func) {
        PyErr_Format(PyExc_TypeError, "Cannot convert %s to %s.",
                     dtype_names[int(dtype_in)], dtype_names[int(dtype_out)]);
        return 0;
    }
    return func(in, ndim, shape);
}

const char *seq_err_msg =
    "A sequence does not support sequence protocol - "
    "this is probably due to a bug in numpy for 0-d arrays.";

169
170
171
// This function determines the shape of an array-like sequence (of
// sequences...) given to it as first parameter.  `dtype_guess' is the dtype of
// the first element of the sequence.
Christoph Groth's avatar
Christoph Groth committed
172
173
174
175
176
177
//
// All four arguments after the first one are written to. `shape' and `seqs'
// must have space for at least `max_ndim' elements.
//
// After successful execution `seqs' will contain `ndim' new references
// returned by PySequence_Fast.
178
179
int examine_sequence(PyObject *arraylike, int *ndim, size_t *shape,
                     PyObject **seqs, Dtype *dtype_guess)
Christoph Groth's avatar
Christoph Groth committed
180
181
182
{
    PyObject *p = arraylike;
    int d = -1;
183
184
185
    assert(PySequence_Check(p));
    for (bool is_sequence = true; ; is_sequence = PySequence_Check(p)) {
        if (is_sequence) {
Christoph Groth's avatar
Christoph Groth committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
            ++d;
            if (d == ptrdiff_t(max_ndim)) {
                // Strings are, in a way, infinitely nested sequences because
                // the first element of a string is a again a string.
                if (PyString_Check(p))
                    PyErr_SetString(PyExc_TypeError, "Expecting a number.");
                else
                    PyErr_SetString(PyExc_ValueError, "Too many dimensions.");
                --d;
                goto fail;
            }
        } else {
            // We are in the innermost sequence.  Determine the dtype if
            // requested.
            if (dtype_guess) {
                *dtype_guess = dtype_of_scalar(p);
                if (*dtype_guess == NONE) {
                    PyErr_SetString(PyExc_TypeError, "Expecting a number.");
                    goto fail;
                }
            }
            break;
        }

Christoph Groth's avatar
Christoph Groth committed
210
        // See https://github.com/numpy/numpy/issues/652.
Christoph Groth's avatar
Christoph Groth committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        seqs[d] = PySequence_Fast(p, seq_err_msg);
        if (!seqs[d]) {--d; goto fail;}

        if ((shape[d] = PySequence_Fast_GET_SIZE(seqs[d]))) {
            p = *PySequence_Fast_ITEMS(seqs[d]);
        } else {
            // We are in the innermost sequence which is empty.
            if (dtype_guess) *dtype_guess = NONE;
            break;
        }
    }
    *ndim = d + 1;
    return 0;

fail:
    for (; d >= 0; --d) Py_DECREF(seqs[d]);
    return -1;
}

230
// This function is designed to be run after examine_sequence.  It takes care
Christoph Groth's avatar
Christoph Groth committed
231
232
// of releasing the references passed to it in seqs.
template <typename T>
233
234
int readin_seqs(PyObject **seqs, T *dest, int ndim, const size_t *shape,
                bool exact)
Christoph Groth's avatar
Christoph Groth committed
235
{
236
    assert(ndim > 0);
Christoph Groth's avatar
Christoph Groth committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

    // seqs is the stack of sequences being processed, all returned by
    // PySequence_Fast.  ps[d] and es[d] are the begin and end of the elements
    // of seqs[d - 1].
    PyObject **ps[max_ndim], **es[max_ndim];
    es[0] = ps[0] = 0;

    for (int d = 1; d < ndim; ++d) {
        PyObject **p = PySequence_Fast_ITEMS(seqs[d - 1]);
        ps[d] = p + 1;
        es[d] = p + shape[d - 1];
    }

    int d = ndim - 1;
    size_t len = shape[d];
    PyObject **p = PySequence_Fast_ITEMS(seqs[d]), **e = p + len;
    while (true) {
        if (len && PySequence_Check(p[0])) {
            if (d + 1 == ndim) {
                PyErr_SetString(PyExc_ValueError,
                                "Input has irregular nesting depth.");
                goto fail;
            }
            ++d;
            ps[d] = p;
            es[d] = e;
        } else {
            // Read-in a leaf sequence.
            while (p < e) {
                T value;
                if (exact)
                    value = number_from_pyobject_exact<T>(*p++);
                else
                    value = number_from_pyobject<T>(*p++);
                if (value == T(-1) && PyErr_Occurred()) goto fail;
                *dest++ = value;
            }
            Py_DECREF(seqs[d]);

            while (ps[d] == es[d]) {
                if (d == 0) {
                    // Success!
                    return 0;
                }
                --d;
                Py_DECREF(seqs[d]);
            }
            if (!PySequence_Check(*ps[d])) {
                --d;
                PyErr_SetString(PyExc_ValueError,
                                "Input has irregular nesting depth.");
                goto fail;
            }
        }

Christoph Groth's avatar
Christoph Groth committed
292
        // See https://github.com/numpy/numpy/issues/652.
Christoph Groth's avatar
Christoph Groth committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        seqs[d] = PySequence_Fast(*ps[d]++, seq_err_msg);
        if (!seqs[d]) {--d; goto fail;}
        len = PySequence_Fast_GET_SIZE(seqs[d]);

        // Verify that the length of the current sequence agrees with the
        // shape.
        if (len != shape[d]) {
            PyErr_SetString(PyExc_ValueError,
                            "Input has irregular shape.");
            goto fail;
        }

        p = PySequence_Fast_ITEMS(seqs[d]);
        e = p + len;
    }

fail:
    while (true) {
        Py_DECREF(seqs[d]);
        if (d == 0) break;
        --d;
    }
    return -1;
}

template <typename T>
319
320
PyObject *readin_seqs_into_new(PyObject **seqs, int ndim_in, int ndim_out,
                               const size_t *shape_out, bool exact)
Christoph Groth's avatar
Christoph Groth committed
321
322
323
324
325
326
327
328
{
    Array<T> *result = Array<T>::make(ndim_out, shape_out);
    assert(ndim_out >= ndim_in);
#ifndef NDEBUG
    for (int d = 0, e = ndim_out - ndim_in; d < e; ++d)
        assert(shape_out[d] == 1);
#endif
    if (result == 0) return 0;
329
330
    if (readin_seqs<T>(seqs, result->data(), ndim_in,
                       shape_out + ndim_out - ndim_in, exact)
Christoph Groth's avatar
Christoph Groth committed
331
332
333
334
335
336
337
        == -1) {
        Py_DECREF(result);
        return 0;
    }
    return (PyObject*)result;
}

338
339
340
PyObject *(*readin_seqs_into_new_dtable[])(
    PyObject**, int, int, const size_t*, bool) =
    DTYPE_DISPATCH(readin_seqs_into_new);
Christoph Groth's avatar
Christoph Groth committed
341

342
template <typename T>
343
PyObject *readin_scalar_into_new(PyObject *in, bool exact, int ndim = 0)
344
345
346
347
348
349
350
351
352
{
    T value;
    if (exact)
        value = number_from_pyobject_exact<T>(in);
    else
        value = number_from_pyobject<T>(in);

    if (value == T(-1) && PyErr_Occurred()) return 0;

353
    Array<T> *result = Array<T>::make(ndim, 1);
354
355
    *result->data() = value;

356
357
358
359
    size_t *shape;
    result->ndim_shape(0, &shape);
    for (int d = 0; d < ndim; ++d) shape[d] = 1;

360
361
362
    return (PyObject*)result;
}

363
364
PyObject *(*readin_scalar_into_new_dtable[])(PyObject*, bool, int) =
    DTYPE_DISPATCH(readin_scalar_into_new);
365

Michael Wimmer's avatar
Michael Wimmer committed
366
367
int examine_buffer(PyObject *in, Py_buffer *view, Dtype *dtype)
{
Christoph Groth's avatar
Christoph Groth committed
368
    if (!PyObject_CheckBuffer(in)) return -1;
Christoph Groth's avatar
Christoph Groth committed
369
    Dtype dt = NONE;
Michael Wimmer's avatar
Michael Wimmer committed
370
    memset(view, 0, sizeof(Py_buffer));
Christoph Groth's avatar
Christoph Groth committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387

    // I don't know if the following makes much sense: I try to get the buffer
    // using less and less demanding flags. NumPy does the same.
    if (PyObject_GetBuffer(in, view, PyBUF_ND | PyBUF_FORMAT) == 0)
        dt = dtype_of_buffer(view);
    else if (PyObject_GetBuffer(in, view, PyBUF_STRIDES | PyBUF_FORMAT) == 0)
        dt = dtype_of_buffer(view);
    else if (PyObject_GetBuffer(in, view, PyBUF_FULL_RO) == 0)
        dt = dtype_of_buffer(view);
    PyErr_Clear();

    // Check if the buffer can actually be converted into one of our
    // formats.
    if (dt == NONE) return -1;

    if (dtype) *dtype = dt;
    return 0;
Michael Wimmer's avatar
Michael Wimmer committed
388
389
390
391
392
393
}

template<typename T>
T (*get_buffer_converter_complex(const char *fmt))(const void *);

template<>
Christoph Groth's avatar
Christoph Groth committed
394
long (*get_buffer_converter_complex(const char *))(const void *)
Michael Wimmer's avatar
Michael Wimmer committed
395
{
Christoph Groth's avatar
Christoph Groth committed
396
    // Complex can only be cast to complex.
Michael Wimmer's avatar
Michael Wimmer committed
397
398
399
400
401
402
    PyErr_Format(PyExc_TypeError, "Complex cannot be cast to int.");

    return 0;
}

template<>
Christoph Groth's avatar
Christoph Groth committed
403
double (*get_buffer_converter_complex(const char *))(const void *)
Michael Wimmer's avatar
Michael Wimmer committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
{
    // complex can only be cast to complex
    PyErr_Format(PyExc_TypeError, "Complex cannot be cast to float.");

    return 0;
}

template<>
Complex (*get_buffer_converter_complex(const char *fmt))(const void *)
{
    switch(*(fmt + 1)){
    case 'f':
        return number_from_ptr<Complex,  std::complex<float> >;
    case 'd':
        return number_from_ptr<Complex, std::complex<double> >;
    case 'g':
        return number_from_ptr<Complex, std::complex<long double> >;
    }

    return 0;
}

template<typename T>
T (*get_buffer_converter(Py_buffer *view))(const void *)
{
    // currently, we only understand native endianness and alignment
    char *fmt = view->format;

Christoph Groth's avatar
Christoph Groth committed
432
    if (*fmt == '@') {
Michael Wimmer's avatar
Michael Wimmer committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        fmt++;
    }

    switch(*fmt) {
    case 'c':
        return number_from_ptr<T, char>;
    case 'b':
        return number_from_ptr<T, signed char>;
    case 'B':
        return number_from_ptr<T, unsigned char>;
    case '?':
        return number_from_ptr<T, bool>;
    case 'h':
        return number_from_ptr<T, short>;
    case 'H':
        return number_from_ptr<T, unsigned short>;
    case 'i':
        return number_from_ptr<T, int>;
    case 'I':
        return number_from_ptr<T, unsigned int>;
    case 'l':
        return number_from_ptr<T, long>;
    case 'L':
        return number_from_ptr<T, unsigned long>;
    case 'q':
        return number_from_ptr<T, long long>;
    case 'Q':
        return number_from_ptr<T, unsigned long long>;
461
    case 'n':
Anton Akhmerov's avatar
Anton Akhmerov committed
462
        return number_from_ptr<T, Py_ssize_t>;
463
464
    case 'N':
        return number_from_ptr<T, size_t>;
Michael Wimmer's avatar
Michael Wimmer committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
    case 'f':
        return number_from_ptr<T, float>;
    case 'd':
        return number_from_ptr<T, double>;
    case 'g':
        return number_from_ptr<T, long double>;
    case 'Z':
        return get_buffer_converter_complex<T>(fmt);
    }

    return 0;
}

template<typename T>
Christoph Groth's avatar
Christoph Groth committed
479
int readin_buffer(T *dest, Py_buffer *view)
Michael Wimmer's avatar
Michael Wimmer committed
480
{
481
482
    if (view->len == 0) return 0;

Michael Wimmer's avatar
Michael Wimmer committed
483
    T (*number_from_ptr)(const void *) = get_buffer_converter<T>(view);
Christoph Groth's avatar
Christoph Groth committed
484
    if (!number_from_ptr) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
485

Christoph Groth's avatar
Christoph Groth committed
486
    if (view->ndim == 0) {
Michael Wimmer's avatar
Michael Wimmer committed
487
        *dest = (*number_from_ptr)(view->buf);
Christoph Groth's avatar
Christoph Groth committed
488
        if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
489
490
491
        else return 0;
    }

Christoph Groth's avatar
Christoph Groth committed
492
493
    Py_ssize_t indices[max_ndim];
    for (int i = 0; i < view->ndim; i++) {
Michael Wimmer's avatar
Michael Wimmer committed
494
495
496
        indices[i] = 0;
    }

Christoph Groth's avatar
Christoph Groth committed
497
    if (view->suboffsets) {
Michael Wimmer's avatar
Michael Wimmer committed
498
499
500
501
502
503
504
505
506
507
        while(indices[0] < view->shape[0]) {
            char *pointer = (char*)view->buf;
            for (int i = 0; i < view->ndim; i++) {
                pointer += view->strides[i] * indices[i];
                if (view->suboffsets[i] >=0 ) {
                    pointer = *((char**)pointer) + view->suboffsets[i];
                }
            }

            *dest++ = (*number_from_ptr)(pointer);
Christoph Groth's avatar
Christoph Groth committed
508
            if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
509
510
511

            indices[view->ndim-1]++;

Christoph Groth's avatar
Christoph Groth committed
512
513
            for (int i = view->ndim - 1; i > 0; i--) {
                if (indices[i] < view->shape[i]) break;
514
                assert(indices[i] == view->shape[i]);
Michael Wimmer's avatar
Michael Wimmer committed
515
516
517
518
                indices[i-1]++;
                indices[i] = 0;
            }
        }
Christoph Groth's avatar
Christoph Groth committed
519
    } else if (view->strides) {
Michael Wimmer's avatar
Michael Wimmer committed
520
521
522
523
        char *ptr = (char *)view->buf;

        while(indices[0] < view->shape[0]) {
            *dest++ = (*number_from_ptr)(ptr);
Christoph Groth's avatar
Christoph Groth committed
524
            if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
525

526
            indices[view->ndim-1]++;
Michael Wimmer's avatar
Michael Wimmer committed
527
528
            ptr += view->strides[view->ndim-1];

Christoph Groth's avatar
Christoph Groth committed
529
530
            for (int i = view->ndim - 1; i > 0; i--) {
                if (indices[i] < view->shape[i]) break;
531
                assert(indices[i] == view->shape[i]);
Michael Wimmer's avatar
Michael Wimmer committed
532
533
534
535
536
537
                indices[i-1]++;
                ptr += view->strides[i-1];
                indices[i] = 0;
                ptr -= view->strides[i] * view->shape[i];
            }
        }
Christoph Groth's avatar
Christoph Groth committed
538
539
    } else {
        // Must be C-contiguous.
Michael Wimmer's avatar
Michael Wimmer committed
540
541
542
543
        char *end = (char *)view->buf + view->len;
        char *p = (char *)view->buf;
        while(p < end) {
            *dest++ = (*number_from_ptr)(p);
Christoph Groth's avatar
Christoph Groth committed
544
            if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
545
546
547
548
549
550
551
552
553
554

            p += view->itemsize;
        }
    }

    return 0;
}

template <typename T>
PyObject *make_and_readin_buffer(Py_buffer *view, int ndim_out,
Christoph Groth's avatar
Christoph Groth committed
555
                                 const size_t *shape_out)
Michael Wimmer's avatar
Michael Wimmer committed
556
557
{
    Array<T> *result = Array<T>::make(ndim_out, shape_out);
Christoph Groth's avatar
Christoph Groth committed
558
    assert(ndim_out >= view->ndim);
Michael Wimmer's avatar
Michael Wimmer committed
559
560
561
562
563
#ifndef NDEBUG
    for (int d = 0, e = ndim_out - view->ndim; d < e; ++d)
        assert(shape_out[d] == 1);
#endif
    if (result == 0) return 0;
Christoph Groth's avatar
Christoph Groth committed
564
    if (readin_buffer<T>(result->data(), view) == -1) {
Michael Wimmer's avatar
Michael Wimmer committed
565
566
567
568
569
570
571
        Py_DECREF(result);
        return 0;
    }
    return (PyObject*)result;
}

PyObject *(*make_and_readin_buffer_dtable[])(
Christoph Groth's avatar
Christoph Groth committed
572
    Py_buffer *, int, const size_t*) = DTYPE_DISPATCH(make_and_readin_buffer);
Michael Wimmer's avatar
Michael Wimmer committed
573

Christoph Groth's avatar
Christoph Groth committed
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
template <typename T>
PyObject *to_pystring(Array<T> *self, PyObject* to_str(PyObject *),
                      const char *header, const char *trailer,
                      const char *indent, const char *separator)
{
    int ndim;
    size_t *shape;
    self->ndim_shape(&ndim, &shape);

    std::ostringstream o;
    o << header;

    const T *p = self->data();
    if (ndim > 0) {
        int d = 0;
        size_t i[max_ndim];
        i[0] = shape[0];

        o << '[';
        while (true) {
            if (i[d]) {
                --i[d];
                if (d < ndim - 1) {
                    o << '[';
                    ++d;
                    i[d] = shape[d];
                } else {
                    PyObject *num = pyobject_from_number(*p++);
                    PyObject *str = to_str(num);
                    o << PyString_AsString(str);
                    Py_DECREF(str);
                    Py_DECREF(num);
                    if (i[d] > 0) o << separator << ' ';
                }
            } else {
                o << ']';
                if (d == 0) break;
                --d;
                if (i[d]) {
                    o << separator << "\n " << indent;
                    for (int i = 0; i < d; ++i) o << ' ';
                }
            }
        }
    } else {
        PyObject *num = pyobject_from_number(*p);
        PyObject *str = to_str(num);
        o << PyString_AsString(str);
        Py_DECREF(str);
        Py_DECREF(num);
    }
    o << trailer;

    return PyString_FromString(o.str().c_str());
}

template <typename T>
Michael Wimmer's avatar
Michael Wimmer committed
631
PyObject *repr(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
632
{
Michael Wimmer's avatar
Michael Wimmer committed
633
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
634
635
636
637
    return to_pystring(self, PyObject_Repr, "array(", ")", "      ", ",");
}

template <typename T>
Michael Wimmer's avatar
Michael Wimmer committed
638
PyObject *str(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
639
{
Michael Wimmer's avatar
Michael Wimmer committed
640
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
    return to_pystring(self, PyObject_Str, "", "", "", "");
}

Py_ssize_t len(Array_base *self)
{
    int ndim;
    size_t *shape;
    self->ndim_shape(&ndim, &shape);
    if (ndim == 0) {
        PyErr_SetString(PyExc_TypeError, "len() of unsized object.");
        return -1;
    }
    return shape[0];
}

Py_ssize_t index_from_key(int ndim, const size_t *shape, PyObject *key)
{
    long indices[max_ndim];
Michael Wimmer's avatar
Michael Wimmer committed
659
    int res = load_index_seq_as_long(key, indices, max_ndim);
Christoph Groth's avatar
Christoph Groth committed
660
661
662
663
    if (res == -1) {
        PyErr_SetString(PyExc_IndexError, "Invalid index.");
        return -1;
    }
Michael Wimmer's avatar
Michael Wimmer committed
664
    if (res != ndim) {
Christoph Groth's avatar
Christoph Groth committed
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        PyErr_SetString(PyExc_IndexError, "Number of indices "
                        "must be equal to number of dimensions.");
        return -1;
    }

    int d = 0;
    Py_ssize_t s = shape[0];
    Py_ssize_t index = indices[0];
    if (index < 0) index += s;
    if (index < 0 || index >= s) goto out_of_range;
    for (d = 1; d < ndim; ++d) {
        s = shape[d];
        Py_ssize_t i = indices[d];
        if (i < 0) i += s;
        if (i < 0 || i >= s) goto out_of_range;
        index *= s;
        index += i;
    }
    return index;

out_of_range:
    PyErr_Format(PyExc_IndexError, "Index %ld out of range "
                 "(-%lu <= index < %lu) in dimension %d.",
                 indices[d], (unsigned long)s, (unsigned long)s, d);
    return -1;
}

template <typename T>
Michael Wimmer's avatar
Michael Wimmer committed
693
PyObject *getitem(PyObject *obj, PyObject *key)
Christoph Groth's avatar
Christoph Groth committed
694
{
Michael Wimmer's avatar
Michael Wimmer committed
695
696
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);

Christoph Groth's avatar
Christoph Groth committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
    if (PySlice_Check(key)) {
        PyErr_SetString(PyExc_NotImplementedError,
                        "Slices are not implemented.");
        return 0;
    } else {
        int ndim;
        size_t *shape;
        self->ndim_shape(&ndim, &shape);
        T *data = self->data();
        Py_ssize_t index = index_from_key(ndim, shape, key);
        if (index == -1) return 0;
        return pyobject_from_number(data[index]);
    }
}

template <typename T>
Michael Wimmer's avatar
Michael Wimmer committed
713
PyObject *seq_getitem(PyObject *obj, Py_ssize_t index)
Christoph Groth's avatar
Christoph Groth committed
714
715
716
{
    int ndim;
    size_t *shape;
Michael Wimmer's avatar
Michael Wimmer committed
717
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
    self->ndim_shape(&ndim, &shape);
    assert(ndim != 0);

    if (index < 0) index += shape[0];
    if (size_t(index) >= shape[0]) {
        PyErr_SetString(PyExc_IndexError, "Invalid index.");
        return 0;
    }

    T *src = self->data();
    if (ndim == 1) {
        assert(index >= 0);
        assert(size_t(index) < shape[0]);
        return pyobject_from_number(src[index]);
    }

    assert(ndim > 1);
    size_t item_size;
    Array<T> *result = Array<T>::make(ndim - 1, shape + 1, &item_size);
    if (!result) return 0;
    src += index * item_size;
    T *dest = result->data();
    for (size_t i = 0; i < item_size; ++i) dest[i] = src[i];
    return (PyObject*)result;
}

template <typename T>
Michael Wimmer's avatar
Michael Wimmer committed
745
int getbuffer(PyObject *obj, Py_buffer *view, int flags)
Christoph Groth's avatar
Christoph Groth committed
746
747
748
{
    int ndim;
    size_t *shape, size;
Michael Wimmer's avatar
Michael Wimmer committed
749
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812

    assert(view);
    if ((flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) {
        PyErr_SetString(PyExc_BufferError,
                        "Tinyarrays are not Fortran contiguous.");
        goto fail;
    }
    // The following has been commented out as a workaround for Cython's
    // inability to deal with read-only buffers.
    //
    // if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE) {
    //     PyErr_SetString(PyExc_BufferError, "Tinyarrays are not writeable");
    //     goto fail;
    // }

    self->ndim_shape(&ndim, &shape);
    size = calc_size(ndim, shape);

    view->buf = self->data();
    view->itemsize = sizeof(T);
    view->len = size * view->itemsize;
    view->readonly = 1;
    if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
        view->format = (char*)Array<T>::pyformat;
    else
        view->format = 0;
    if ((flags & PyBUF_ND) == PyBUF_ND) {
        view->ndim = ndim;
        view->shape = (Py_ssize_t*)shape;
        // From the documentation it's not clear whether it is allowed not to
        // set strides to NULL (for C continuous arrays), but it works, so we
        // do it.  However, there is a bug in current numpy
        // (http://projects.scipy.org/numpy/ticket/2197) which requires strides
        // if view->len == 0.  Because we don't have proper strides, we just
        // set strides to shape.  This dirty trick seems to work well -- no one
        // looks at strides when len == 0.
        if (size != 0)
            view->strides = 0;
        else
            view->strides = (Py_ssize_t*)shape;
    } else {
        view->ndim = 0;
        view->shape = 0;
        view->strides = 0;
    }
    view->internal = 0;
    view->suboffsets = 0;

    // Success.
    Py_INCREF(self);
    view->obj = (PyObject*)self;

    return 0;

fail:
    view->obj = 0;
    return -1;
}

// Given the same input, these hash functions return the same result as those
// in Python.  As tinyarrays compare equal to equivalent tuples it is important
// for the hashes to agree.  If not, there will be problems with dictionaries.

813
#if PY_MAJOR_VERSION >= 3
814
815

// the only documentation for this is in the Python sourcecode
816
const Py_hash_t HASH_IMAG = _PyHASH_IMAG;
817

Stefano Rivera's avatar
Stefano Rivera committed
818
Py_hash_t hash(void *inst, long x)
819
{
820
821
822
823
824
825
    // For integers the hash is just the integer itself modulo _PyHASH_MODULUS
    // except for the singular case of -1.
    // define 'sign' of the correct width to avoid overflow
    Py_hash_t sign = x < 0 ? -1 : 1;
    Py_hash_t result = sign * ((sign * x) % _PyHASH_MODULUS);
    return result == -1 ? -2 : result;
826
827
}

828
829
#else

830
831
832
833
834
835
/* In Python 2 hashes were long integers, as indicated by
   https://github.com/python/cpython/blob/2.7/Include/object.h#L314
*/
typedef long Py_hash_t;
typedef unsigned long Py_uhash_t;
const Py_hash_t HASH_IMAG = 1000003L;
836

Stefano Rivera's avatar
Stefano Rivera committed
837
Py_hash_t hash(void *inst, long x)
Christoph Groth's avatar
Christoph Groth committed
838
{
839
    return x != -1 ? x : -2;
Christoph Groth's avatar
Christoph Groth committed
840
841
}

842
843
#endif

844
845
846
// We used to have our own implementation of this, but the extra function
// call is quite negligible compared to the execution time of the function.
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 10
Stefano Rivera's avatar
Stefano Rivera committed
847
Py_hash_t hash(void *inst, double x)
Christoph Groth's avatar
Christoph Groth committed
848
{
Stefano Rivera's avatar
Stefano Rivera committed
849
850
    return _Py_HashDouble((PyObject *)inst, x);
#else
851
852
Py_hash_t hash(void *, double x)
{
Christoph Groth's avatar
Christoph Groth committed
853
    return _Py_HashDouble(x);
Stefano Rivera's avatar
Stefano Rivera committed
854
#endif
Christoph Groth's avatar
Christoph Groth committed
855
856
}

Stefano Rivera's avatar
Stefano Rivera committed
857
Py_hash_t hash(void *inst, Complex x)
Christoph Groth's avatar
Christoph Groth committed
858
859
{
    // x.imag == 0  =>  hash(x.imag) == 0  =>  hash(x) == hash(x.real)
Stefano Rivera's avatar
Stefano Rivera committed
860
    return hash(inst, x.real()) + HASH_IMAG * hash(inst, x.imag());
Christoph Groth's avatar
Christoph Groth committed
861
862
}

863
864
865
866
867
868
869
870
871
872
873
874
875
// The following routine calculates the hash of a multi-dimensional array.  The
// hash is equal to that of an arrangement of nested tuples equivalent to the
// array.
//
// It exists in two versions because Python's tuplehash has changed in Python
// 3.8 with the following motivation: "The hash function for tuples is now
// based on xxHash which gives better collision results on (formerly)
// pathological cases. Additionally, on 64-bit systems it improves tuple hashes
// in general."

#if (PY_MAJOR_VERSION < 3 || PY_MINOR_VERSION < 8) && PY_MAJOR_VERSION < 4

// Version for Python < 3.8
Christoph Groth's avatar
Christoph Groth committed
876
template <typename T>
877
Py_hash_t hash(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
878
879
880
{
    int ndim;
    size_t *shape;
Michael Wimmer's avatar
Michael Wimmer committed
881
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
882
883
    self->ndim_shape(&ndim, &shape);
    T *p = self->data();
Stefano Rivera's avatar
Stefano Rivera committed
884
    if (ndim == 0) return hash(p, *p);
Christoph Groth's avatar
Christoph Groth committed
885

886
887
    const Py_uhash_t mult_init = 1000003, r_init = 0x345678;
    const Py_uhash_t mul_addend = 82520, r_addend = 97531;
Christoph Groth's avatar
Christoph Groth committed
888
    Py_ssize_t i[max_ndim];
889
    Py_uhash_t mult[max_ndim], r[max_ndim];
Christoph Groth's avatar
Christoph Groth committed
890
891
892
893
894
895
896
897
898
    --ndim;                     // For convenience.
    int d = 0;
    i[0] = shape[0];
    mult[0] = mult_init;
    r[0] = r_init;
    while (true) {
        if (i[d]) {
            --i[d];
            if (d == ndim) {
899
                // Innermost loop body.
Stefano Rivera's avatar
Stefano Rivera committed
900
901
                r[d] = (r[d] ^ hash(p, *p)) * mult[d];
                p++;
Christoph Groth's avatar
Christoph Groth committed
902
903
                mult[d] += mul_addend + 2 * i[d];
            } else {
904
                // Entering a loop.
Christoph Groth's avatar
Christoph Groth committed
905
906
907
908
909
910
                ++d;
                i[d] = shape[d];
                mult[d] = mult_init;
                r[d] = r_init;
            }
        } else {
911
            // Exiting a loop.
912
            if (d == 0) {
913
                // Exiting the outermost loop.
914
915
916
                Py_uhash_t r_next = r[0] + r_addend;
                return r_next == Py_uhash_t(-1) ? -2 : r_next;
            }
Christoph Groth's avatar
Christoph Groth committed
917
            --d;
918
919
920
            Py_uhash_t r_next = r[d+1] + r_addend;
            r_next = r_next == Py_uhash_t(-1) ? -2 : r_next;
            r[d] = (r[d] ^ r_next) * mult[d];
Christoph Groth's avatar
Christoph Groth committed
921
922
923
924
925
            mult[d] += mul_addend + 2 * i[d];
        }
    }
}

926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
#else

#if SIZEOF_PY_UHASH_T > 4

const Py_uhash_t _hash_init = 2870177450012600261U;

inline void _hash_inner_loop(Py_uhash_t &acc, Py_uhash_t lane)
{
    acc += lane * 14029467366897019727U;
    acc = ((acc << 31) | (acc >> 33)); // Rotate left 31 bits.
    acc *= 11400714785074694791U;
}

#else

const Py_uhash_t _hash_init = 374761393U;

inline void _hash_inner_loop(Py_uhash_t &acc, Py_uhash_t lane)
{
    acc += lane * 2246822519U;
    acc = ((acc << 13) | (acc >> 19)); // Rotate left 13 bits.
    acc *= 2654435761U;
}

#endif

inline Py_uhash_t _hash_loop_end(Py_uhash_t acc, Py_uhash_t len)
{
    acc += len ^ (_hash_init ^ 3527539UL);
    if (acc == Py_uhash_t(-1)) return 1546275796;
    return acc;
}

// Version for Python >= 3.8
template <typename T>
Py_hash_t hash(PyObject *obj)
{
    int ndim;
    size_t *shape;
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
    self->ndim_shape(&ndim, &shape);
    T *p = self->data();
Stefano Rivera's avatar
Stefano Rivera committed
968
    if (ndim == 0) return hash(p, *p);
969
970
971
972
973
974
975
976
977
978
979
980

    Py_ssize_t i[max_ndim];
    Py_uhash_t acc[max_ndim];
    --ndim;                     // For convenience.
    int d = 0;
    i[0] = shape[0];
    acc[0] = _hash_init;
    // The following is equivalent to 'ndim' (the original value) nested loops.
    while (true) {
        if (i[d]) {
            --i[d];
            if (d == ndim) {
Stefano Rivera's avatar
Stefano Rivera committed
981
982
                _hash_inner_loop(acc[d], hash(p, *p));
                p++;
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
            } else {
                ++d;
                i[d] = shape[d];
                acc[d] = _hash_init;
            }
        } else {
            if (d == 0) return _hash_loop_end(acc[0], shape[0]);
            --d;
            _hash_inner_loop(acc[d], _hash_loop_end(acc[d+1], shape[d+1]));
        }
    }
}

#endif

Christoph Groth's avatar
Christoph Groth committed
998
template <typename T>
999
1000
bool compare_scalar(const int op, const T a, const T b) {
    switch(op){
For faster browsing, not all history is shown. View entire blame