array.cc 53.5 KB
Newer Older
1
// Copyright 2012-2015 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
14
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

#include <Python.h>
#include <cstddef>
#include <sstream>
#include <limits>
#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
82
83
Dtype dtype_of_buffer(Py_buffer *view)
{
Joseph Weston's avatar
Joseph Weston committed
84
    const char *fmt = view->format;
Christoph Groth's avatar
Christoph Groth committed
85
    Dtype dtype = NONE;
Michael Wimmer's avatar
Michael Wimmer committed
86

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

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

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

    return dtype;
}

Christoph Groth's avatar
Christoph Groth committed
111
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
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.";

168
169
170
// 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
171
172
173
174
175
176
//
// 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.
177
178
int examine_sequence(PyObject *arraylike, int *ndim, size_t *shape,
                     PyObject **seqs, Dtype *dtype_guess)
Christoph Groth's avatar
Christoph Groth committed
179
180
181
{
    PyObject *p = arraylike;
    int d = -1;
182
183
184
    assert(PySequence_Check(p));
    for (bool is_sequence = true; ; is_sequence = PySequence_Check(p)) {
        if (is_sequence) {
Christoph Groth's avatar
Christoph Groth committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
            ++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
209
        // See https://github.com/numpy/numpy/issues/652.
Christoph Groth's avatar
Christoph Groth committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
        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;
}

229
// This function is designed to be run after examine_sequence.  It takes care
Christoph Groth's avatar
Christoph Groth committed
230
231
// of releasing the references passed to it in seqs.
template <typename T>
232
233
int readin_seqs(PyObject **seqs, T *dest, int ndim, const size_t *shape,
                bool exact)
Christoph Groth's avatar
Christoph Groth committed
234
{
235
    assert(ndim > 0);
Christoph Groth's avatar
Christoph Groth committed
236
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

    // 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
291
        // See https://github.com/numpy/numpy/issues/652.
Christoph Groth's avatar
Christoph Groth committed
292
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
        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>
318
319
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
320
321
322
323
324
325
326
327
{
    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;
328
329
    if (readin_seqs<T>(seqs, result->data(), ndim_in,
                       shape_out + ndim_out - ndim_in, exact)
Christoph Groth's avatar
Christoph Groth committed
330
331
332
333
334
335
336
        == -1) {
        Py_DECREF(result);
        return 0;
    }
    return (PyObject*)result;
}

337
338
339
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
340

341
template <typename T>
342
PyObject *readin_scalar_into_new(PyObject *in, bool exact, int ndim = 0)
343
344
345
346
347
348
349
350
351
{
    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;

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

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

359
360
361
    return (PyObject*)result;
}

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

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

    // 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
387
388
389
390
391
392
}

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

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

    return 0;
}

template<>
Christoph Groth's avatar
Christoph Groth committed
402
double (*get_buffer_converter_complex(const char *))(const void *)
Michael Wimmer's avatar
Michael Wimmer committed
403
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
{
    // 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
431
    if (*fmt == '@') {
Michael Wimmer's avatar
Michael Wimmer committed
432
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
461
462
463
464
465
466
467
468
469
470
471
472
473
        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>;
    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
474
int readin_buffer(T *dest, Py_buffer *view)
Michael Wimmer's avatar
Michael Wimmer committed
475
476
{
    T (*number_from_ptr)(const void *) = get_buffer_converter<T>(view);
Christoph Groth's avatar
Christoph Groth committed
477
    if (!number_from_ptr) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
478

Christoph Groth's avatar
Christoph Groth committed
479
    if (view->ndim == 0) {
Michael Wimmer's avatar
Michael Wimmer committed
480
        *dest = (*number_from_ptr)(view->buf);
Christoph Groth's avatar
Christoph Groth committed
481
        if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
482
483
484
        else return 0;
    }

Christoph Groth's avatar
Christoph Groth committed
485
486
    Py_ssize_t indices[max_ndim];
    for (int i = 0; i < view->ndim; i++) {
Michael Wimmer's avatar
Michael Wimmer committed
487
488
489
        indices[i] = 0;
    }

Christoph Groth's avatar
Christoph Groth committed
490
    if (view->suboffsets) {
Michael Wimmer's avatar
Michael Wimmer committed
491
492
493
494
495
496
497
498
499
500
        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
501
            if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
502
503
504

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

Christoph Groth's avatar
Christoph Groth committed
505
506
            for (int i = view->ndim - 1; i > 0; i--) {
                if (indices[i] < view->shape[i]) break;
Michael Wimmer's avatar
Michael Wimmer committed
507
508
509
510
                indices[i-1]++;
                indices[i] = 0;
            }
        }
Christoph Groth's avatar
Christoph Groth committed
511
    } else if (view->strides) {
Michael Wimmer's avatar
Michael Wimmer committed
512
513
514
515
        char *ptr = (char *)view->buf;

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

            indices[view->ndim-1] ++;
            ptr += view->strides[view->ndim-1];

Christoph Groth's avatar
Christoph Groth committed
521
522
            for (int i = view->ndim - 1; i > 0; i--) {
                if (indices[i] < view->shape[i]) break;
Michael Wimmer's avatar
Michael Wimmer committed
523
524
525
526
527
528
                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
529
530
    } else {
        // Must be C-contiguous.
Michael Wimmer's avatar
Michael Wimmer committed
531
532
533
534
        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
535
            if (PyErr_Occurred()) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
536
537
538
539
540
541
542
543
544
545

            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
546
                                 const size_t *shape_out)
Michael Wimmer's avatar
Michael Wimmer committed
547
548
{
    Array<T> *result = Array<T>::make(ndim_out, shape_out);
Christoph Groth's avatar
Christoph Groth committed
549
    assert(ndim_out >= view->ndim);
Michael Wimmer's avatar
Michael Wimmer committed
550
551
552
553
554
#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
555
    if (readin_buffer<T>(result->data(), view) == -1) {
Michael Wimmer's avatar
Michael Wimmer committed
556
557
558
559
560
561
562
        Py_DECREF(result);
        return 0;
    }
    return (PyObject*)result;
}

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

Christoph Groth's avatar
Christoph Groth committed
565
566
567
568
569
570
571
572
573
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
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
622
PyObject *repr(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
623
{
Michael Wimmer's avatar
Michael Wimmer committed
624
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
625
626
627
628
    return to_pystring(self, PyObject_Repr, "array(", ")", "      ", ",");
}

template <typename T>
Michael Wimmer's avatar
Michael Wimmer committed
629
PyObject *str(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
630
{
Michael Wimmer's avatar
Michael Wimmer committed
631
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
    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
650
    int res = load_index_seq_as_long(key, indices, max_ndim);
Christoph Groth's avatar
Christoph Groth committed
651
652
653
654
    if (res == -1) {
        PyErr_SetString(PyExc_IndexError, "Invalid index.");
        return -1;
    }
Michael Wimmer's avatar
Michael Wimmer committed
655
    if (res != ndim) {
Christoph Groth's avatar
Christoph Groth committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        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
684
PyObject *getitem(PyObject *obj, PyObject *key)
Christoph Groth's avatar
Christoph Groth committed
685
{
Michael Wimmer's avatar
Michael Wimmer committed
686
687
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);

Christoph Groth's avatar
Christoph Groth committed
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
    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
704
PyObject *seq_getitem(PyObject *obj, Py_ssize_t index)
Christoph Groth's avatar
Christoph Groth committed
705
706
707
{
    int ndim;
    size_t *shape;
Michael Wimmer's avatar
Michael Wimmer committed
708
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
    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
736
int getbuffer(PyObject *obj, Py_buffer *view, int flags)
Christoph Groth's avatar
Christoph Groth committed
737
738
739
{
    int ndim;
    size_t *shape, size;
Michael Wimmer's avatar
Michael Wimmer committed
740
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
741
742
743
744
745
746
747
748
749
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

    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.

804
805
806
807
808
long old_hash(long x)
{
    return x != -1 ? x : -2;
}

809
#if PY_MAJOR_VERSION >= 3
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844

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

Hash hash(long x_)
{
    int negative = x_ < 0;
    unsigned long x = (negative ? -x_ : x_);
    // x is the absolute value of x_.

    if (x < PyLong_BASE) {
        if (negative)
            return x == 1 ? -2 : -long(x);
        else
            return x;
    }

    // PyLong_SHIFT is 15 for 32-bit architectures and 30 for 64-bit.  So a
    // long contains at most 3 digits.  Therefore, a starting value of n = 2 is
    // sufficient.
    Py_uhash_t r = 0;
    for (int n = 2; n >= 0; --n) {
        unsigned dig = (x >> (n * PyLong_SHIFT)) & PyLong_MASK;
        if (r == 0 && dig == 0) continue;
        r = ((r << PyLong_SHIFT) & _PyHASH_MODULUS) |
            (r >> (_PyHASH_BITS - PyLong_SHIFT));
        r += dig;
        if (r >= _PyHASH_MODULUS) r -= _PyHASH_MODULUS;
    }
    if (negative) r = -r;
    if (r == Py_uhash_t(-1)) r = Py_uhash_t(-2);
    return r;
}

845
846
#else

847
848
849
850
typedef long Hash;
const Hash HASH_IMAG = 1000003L;

Hash hash(long x)
Christoph Groth's avatar
Christoph Groth committed
851
{
852
    return old_hash(x);
Christoph Groth's avatar
Christoph Groth committed
853
854
}

855
856
857
#endif

Hash hash(double x)
Christoph Groth's avatar
Christoph Groth committed
858
{
Christoph Groth's avatar
Christoph Groth committed
859
860
861
    // 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.
    return _Py_HashDouble(x);
Christoph Groth's avatar
Christoph Groth committed
862
863
}

864
Hash hash(Complex x)
Christoph Groth's avatar
Christoph Groth committed
865
866
{
    // x.imag == 0  =>  hash(x.imag) == 0  =>  hash(x) == hash(x.real)
867
    return hash(x.real()) + HASH_IMAG * hash(x.imag());
Christoph Groth's avatar
Christoph Groth committed
868
869
870
871
872
}

// This 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.
template <typename T>
873
Hash hash(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
874
875
876
{
    int ndim;
    size_t *shape;
Michael Wimmer's avatar
Michael Wimmer committed
877
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    self->ndim_shape(&ndim, &shape);
    T *p = self->data();
    if (ndim == 0) return hash(*p);

    const long mult_init = 1000003, r_init = 0x345678;
    const long mul_addend = 82520, r_addend = 97531;
    Py_ssize_t i[max_ndim];
    long mult[max_ndim], r[max_ndim];
    --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) {
                r[d] = (r[d] ^ hash(*p++)) * mult[d];
                mult[d] += mul_addend + 2 * i[d];
            } else {
                ++d;
                i[d] = shape[d];
                mult[d] = mult_init;
                r[d] = r_init;
            }
        } else {
904
            if (d == 0) return old_hash(r[0] + r_addend);
Christoph Groth's avatar
Christoph Groth committed
905
            --d;
906
            r[d] = (r[d] ^ old_hash(r[d+1] + r_addend)) * mult[d];
Christoph Groth's avatar
Christoph Groth committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
            mult[d] += mul_addend + 2 * i[d];
        }
    }
}

template <typename T>
bool is_equal_data(PyObject *a_, PyObject *b_, size_t size)
{
    assert(Array<T>::check_exact(a_)); Array<T> *a = (Array<T>*)a_;
    assert(Array<T>::check_exact(b_)); Array<T> *b = (Array<T>*)b_;
    T *data_a = a->data();
    T *data_b = b->data();
    for (size_t i = 0; i < size; ++i)
        if (data_a[i] != data_b[i]) return false;
    return true;
}

bool (*is_equal_data_dtable[])(PyObject*, PyObject*, size_t) =
    DTYPE_DISPATCH(is_equal_data);

PyObject *richcompare(PyObject *a, PyObject *b, int op)
{
    if (op != Py_EQ && op != Py_NE) {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    bool equal = (a == b);
    if (equal) goto done;

    Dtype dtype;
    if (coerce_to_arrays(&a, &b, &dtype) < 0) return 0;

    int ndim_a, ndim_b;
    size_t *shape_a, *shape_b;
    reinterpret_cast<Array_base*>(a)->ndim_shape(&ndim_a, &shape_a);
    reinterpret_cast<Array_base*>(b)->ndim_shape(&ndim_b, &shape_b);
    if (ndim_a != ndim_b) goto decref_then_done;
    for (int d = 0; d < ndim_a; ++d)
        if (shape_a[d] != shape_b[d]) goto decref_then_done;
    equal = is_equal_data_dtable[int(dtype)](a, b, calc_size(ndim_a, shape_a));

decref_then_done:
    Py_DECREF(a);
    Py_DECREF(b);

done:
    PyObject *result = ((op == Py_EQ) == equal) ? Py_True : Py_False;
    Py_INCREF(result);
    return result;
}

PyObject *get_dtype_py(PyObject *self, void *)
{
    static PyObject *dtypes[] = {
        (PyObject*)&PyInt_Type,
        (PyObject*)&PyFloat_Type,
        (PyObject*)&PyComplex_Type
    };
    int dtype = int(get_dtype(self));
    assert(dtype < int(NONE));
    return dtypes[dtype];
}

PyObject *get_ndim(Array_base *self, void *)
{
    int ndim;
    self->ndim_shape(&ndim, 0);
    return PyLong_FromLong(ndim);
}

PyObject *get_size(Array_base *self, void *)
{
    int ndim;
    size_t *shape;
    self->ndim_shape(&ndim, &shape);
    return PyLong_FromSize_t(calc_size(ndim, shape));
}

PyObject *get_shape(Array_base *self, void *)
{
    int ndim;
    size_t *shape;
    self->ndim_shape(&ndim, &shape);
    size_t result_shape = ndim;
    Array<long> *result = Array<long>::make(1, &result_shape);
    if (!result) return 0;
    long *data = result->data();
    for (int d = 0; d < ndim; ++d) data[d] = shape[d];
    return (PyObject*)result;
}

PyGetSetDef getset[] = {
    {(char*)"dtype", get_dtype_py, 0, 0, 0},
For faster browsing, not all history is shown. View entire blame