array.cc 57.5 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

Christoph Groth's avatar
Christoph Groth committed
91
92
    if (strchr("cbB?hHiIlL", *fmt)) {
        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
106
107
    // 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
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
    Dtype dt = NONE;
Michael Wimmer's avatar
Michael Wimmer committed
369
    memset(view, 0, sizeof(Py_buffer));
Christoph Groth's avatar
Christoph Groth committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
        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
475
int readin_buffer(T *dest, Py_buffer *view)
Michael Wimmer's avatar
Michael Wimmer committed
476
{
477
478
    if (view->len == 0) return 0;

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

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

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

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

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

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

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

522
            indices[view->ndim-1]++;
Michael Wimmer's avatar
Michael Wimmer committed
523
524
            ptr += view->strides[view->ndim-1];

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

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

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

Christoph Groth's avatar
Christoph Groth committed
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
622
623
624
625
626
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
627
PyObject *repr(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
628
{
Michael Wimmer's avatar
Michael Wimmer committed
629
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
630
631
632
633
    return to_pystring(self, PyObject_Repr, "array(", ")", "      ", ",");
}

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

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

    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.

809
#if PY_MAJOR_VERSION >= 3
810
811

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

814
Py_hash_t hash(long x)
815
{
816
817
818
819
820
821
    // 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;
822
823
}

824
825
#else

826
827
828
829
830
831
/* 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;
832

833
Py_hash_t hash(long x)
Christoph Groth's avatar
Christoph Groth committed
834
{
835
    return x != -1 ? x : -2;
Christoph Groth's avatar
Christoph Groth committed
836
837
}

838
839
#endif

840
Py_hash_t hash(double x)
Christoph Groth's avatar
Christoph Groth committed
841
{
Christoph Groth's avatar
Christoph Groth committed
842
843
844
    // 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
845
846
}

847
Py_hash_t hash(Complex x)
Christoph Groth's avatar
Christoph Groth committed
848
849
{
    // x.imag == 0  =>  hash(x.imag) == 0  =>  hash(x) == hash(x.real)
850
    return hash(x.real()) + HASH_IMAG * hash(x.imag());
Christoph Groth's avatar
Christoph Groth committed
851
852
853
854
855
}

// 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>
856
Py_hash_t hash(PyObject *obj)
Christoph Groth's avatar
Christoph Groth committed
857
858
859
{
    int ndim;
    size_t *shape;
Michael Wimmer's avatar
Michael Wimmer committed
860
    Array<T> *self = reinterpret_cast<Array<T> *>(obj);
Christoph Groth's avatar
Christoph Groth committed
861
862
863
864
    self->ndim_shape(&ndim, &shape);
    T *p = self->data();
    if (ndim == 0) return hash(*p);

865
866
    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
867
    Py_ssize_t i[max_ndim];
868
    Py_uhash_t mult[max_ndim], r[max_ndim];
Christoph Groth's avatar
Christoph Groth committed
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
    --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 {
887
888
889
890
            if (d == 0) {
                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
891
            --d;
892
893
894
            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
895
896
897
898
899
900
            mult[d] += mul_addend + 2 * i[d];
        }
    }
}

template <typename T>
901
902
903
904
905
906
907
908
909
bool compare_scalar(const int op, const T a, const T b) {
    switch(op){
        case Py_EQ: return a == b;
        case Py_NE: return a != b;
        case Py_LE: return a <= b;
        case Py_GE: return a >= b;
        case Py_LT: return a < b;
        case Py_GT: return a > b;
        default:
Christoph Groth's avatar
Christoph Groth committed
910
911
           assert(false);  // If we get here something is very wrong.
           return false;   // Stop the compiler complaining.
912
913
914
915
916
917
918
919
920
    }
}


template <>
bool compare_scalar<Complex>(const int op, const Complex a, const Complex b) {
    switch(op){
        case Py_EQ: return a == b;
        case Py_NE: return a != b;
Christoph Groth's avatar
Christoph Groth committed
921
922
        // This function is never called in a context where
        // the following code path is run -- fall through.
923
924
925
926
927
928
        case Py_LE:
        case Py_GT:
        case Py_LT:
        case Py_GE:
        default:
           assert(false);
Christoph Groth's avatar
Christoph Groth committed
929
           return false;   // Stop the compiler complaining.
930
931
932
933
934
935
    }
}


template <typename T>
bool compare_data(int op, PyObject *a_, PyObject *b_, size_t size)
Christoph Groth's avatar
Christoph Groth committed
936
937
938
{
    assert(Array<T>::check_exact(a_)); Array<T> *a = (Array<T>*)a_;
    assert(Array<T>::check_exact(b_)); Array<T> *b = (Array<T>*)b_;
939
940
    const T *data_a = a->data();
    const T *data_b = b->data();
Christoph Groth's avatar
Christoph Groth committed
941
    // Sequences are ordered the same as their first differing elements, see:
Christoph Groth's avatar
Christoph Groth committed
942
    // https://docs.python.org/3/reference/expressions.html#value-comparisons
943
    // comparison for "multidimensional" sequences is identical to comparing
Christoph Groth's avatar
Christoph Groth committed
944
    // the flattened sequences when they have the same shape (the present case).
945
946
947
    size_t i = 0;
    for (; i < size; ++i)
        if (data_a[i] != data_b[i]) break;
Christoph Groth's avatar
Christoph Groth committed
948
    // Any of these operations should return true when objects are equal.
949
950
951
    if (i == size) return ((op == Py_EQ) || (op == Py_LE) || (op == Py_GE));
    // encapsulate this into a function to handle the COMPLEX case
    return compare_scalar<T>(op, data_a[i], data_b[i]);
Christoph Groth's avatar
Christoph Groth committed
952
953
}

954
955
bool (*compare_data_dtable[])(int, PyObject*, PyObject*, size_t) =
    DTYPE_DISPATCH(compare_data);
Christoph Groth's avatar
Christoph Groth committed
956

957
958
959
960
961
962
963
964
#if PY_MAJOR_VERSION < 3
    #define PY2_RAISE_TYPEERROR(msg)\
        PyErr_SetString(PyExc_TypeError, msg);\
        return 0
#else
    #define PY2_RAISE_TYPEERROR(msg)
#endif  // PY_MAJOR_VERSION < 3

Christoph Groth's avatar
Christoph Groth committed
965
966
PyObject *richcompare(PyObject *a, PyObject *b, int op)
{
967
968
    PyObject *result;
    const bool equality_comparison = (op == Py_EQ || op == Py_NE);
Christoph Groth's avatar
Christoph Groth committed
969

Christoph Groth's avatar
Christoph Groth committed
970
    // Short circuit when we are comparing the same object.
Christoph Groth's avatar
Christoph Groth committed
971
    bool equal = (a == b);
972
    if (equal) {
Christoph Groth's avatar
Christoph Groth committed
973
        // Any of these operations should return true when objects are equal
974
975
976
977
        equal = (op == Py_EQ) || (op == Py_GE) || (op == Py_LE);
        result = equal ? Py_True : Py_False;
        goto done;
    }
Christoph Groth's avatar
Christoph Groth committed
978
979
980
981

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

Christoph Groth's avatar
Christoph Groth committed
982
983
    // Obviate the need for `compare_scalar<Complex` to
    // handle the case of an undefined comparison.
984
    if (dtype == COMPLEX && !equality_comparison) {
985
        PY2_RAISE_TYPEERROR("unorderable type: complex()");
986
987
988
989
        result = Py_NotImplemented;
        goto decref_then_done;
    }

Christoph Groth's avatar
Christoph Groth committed
990
991
992
993
994
    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);

Christoph Groth's avatar
Christoph Groth committed
995
    // TODO: Enable array comparisons between arrays of differing dimensions.
996
997
998
999
    if (ndim_a != ndim_b) {
        if (equality_comparison) {
            goto equality_then_done;
        } else {
Christoph Groth's avatar
Christoph Groth committed
1000
1001
            PY2_RAISE_TYPEERROR("Unorderable type: only arrays with"
                                "the same shape can be ordered.");
1002
1003
1004
1005
1006
1007
1008
1009
1010
            result = Py_NotImplemented;
            goto decref_then_done;
        }
    }
    for (int d = 0; d < ndim_a; ++d) {
        if (shape_a[d] != shape_b[d]) {
            if (equality_comparison) {
                goto equality_then_done;
            } else {
Christoph Groth's avatar
Christoph Groth committed
1011
1012
                PY2_RAISE_TYPEERROR("Unorderable type: only arrays with"
                                    "the same shape can be ordered.");
1013
1014
1015
1016
1017
1018
                result = Py_NotImplemented;
                goto decref_then_done;
            }
        }
    }

Christoph Groth's avatar
Christoph Groth committed
1019
    // Actually compare the data.
1020
1021
1022
1023
    equal = compare_data_dtable[int(dtype)](op, a, b, calc_size(ndim_a, shape_a));
    result = equal ? Py_True : Py_False;
    goto decref_then_done;

Christoph Groth's avatar
Christoph Groth committed
1024
// Non error-path exit points from this function
1025
1026
equality_then_done:
    result = ((op == Py_EQ) == equal) ? Py_True : Py_False;
Christoph Groth's avatar
Christoph Groth committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
decref_then_done:
    Py_DECREF(a);
    Py_DECREF(b);
done:
    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));
1044
    Py_INCREF(dtypes[dtype]);
Christoph Groth's avatar
Christoph Groth committed
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
    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},
    {(char*)"ndim", (getter)get_ndim, 0, 0, 0},
    {(char*)"size", (getter)get_size, 0, 0, 0},
    {(char*)"shape", (getter)get_shape, 0, 0, 0},
    {0, 0, 0, 0, 0}               // Sentinel
};

// **************** Iterator ****************

template <typename T>
class Array_iter {
public:
    static Array_iter *make(Array<T> *array);
    static void dealloc(Array_iter<T> *self);
    static PyObject *next(Array_iter<T> *self);
    static PyObject *len(Array_iter<T> *self);
private:
    static PyMethodDef methods[];
    static PyTypeObject pytype;
    static const char *pyname;
    PyObject ob_base;
    size_t index;
    Array<T> *array;            // Set to 0 when iterator is exhausted.
};

template <>
const char *Array_iter<long>::pyname = "tinyarray.ndarrayiter_int";
template <>
const char *Array_iter<double>::pyname = "tinyarray.ndarrayiter_float";
template <>
const char *Array_iter<Complex>::pyname = "tinyarray.ndarrayiter_complex";

template <typename T>
Array_iter<T> *Array_iter<T>::make(Array<T> *array)
{
    int ndim;
    assert(Array<T>::check_exact((PyObject*)array));
    array->ndim_shape(&ndim, 0);
    if (ndim == 0) {
        PyErr_SetString(PyExc_TypeError, "Iteration over a 0-d array.");
        return 0;
    }
    Array_iter<T> *ret = PyObject_New(Array_iter<T>, &Array_iter<T>::pytype);
    if (ret == 0) return 0;
    ret->index = 0;
    Py_INCREF(array);
    ret->array = array;
    return ret;
}

template <typename T>
void Array_iter<T>::dealloc(Array_iter<T> *self)
{
    // We use Py_XDECREF as array is already decref'ed when the iterator gets
    // exhausted.
    Py_XDECREF(self->array);
    PyObject_Del(self);
}

template <typename T>
PyObject *Array_iter<T>::next(Array_iter<T> *self)
{
    Array<T> *array = self->array;
    if (array == 0) return 0;
    int ndim;
    size_t *shape;
    array->ndim_shape(&ndim, &shape);
    assert(ndim != 0);

    if (self->index == shape[0]) {
        // End of iteration.
        Py_DECREF(array);
        self->array = 0;
        return 0;
    }

    T *src = array->data();

    if (ndim == 1) {
        assert(size_t(self->index) < shape[0]);
        return pyobject_from_number(src[self->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 += item_size * self->index++;
    T *dest = result->data();
    for (size_t i = 0; i < item_size; ++i) dest[i] = src[i];
    return (PyObject*)result;
}

template <typename T>
PyObject *Array_iter<T>::len(Array_iter<T> *self)
{
    Py_ssize_t len = 0;
    if (self->array) {
#ifndef NDEBUG
        int ndim;
        self->array->ndim_shape(&ndim, 0);
        assert(ndim != 0);
#endif
        size_t *shape;
        self->array->ndim_shape(0, &shape);
        len = shape[0] - self->index;
    }
    return PyInt_FromSsize_t(len);
}

template <typename T>
PyMethodDef Array_iter<T>::methods[] = {
    {"__length_hint__", (PyCFunction)Array_iter<T>::len, METH_NOARGS,
     "Private method returning an estimate of len(list(it))."},
    {0, 0}                      // Sentinel
};

template <typename T>
PyTypeObject Array_iter<T>::pytype = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    pyname,                             // tp_name
    sizeof(Array_iter<T>),              // tp_basicsize
    0,                                  // tp_itemsize
    // methods
    (destructor)Array_iter<T>::dealloc, // tp_dealloc
    0,                                  // tp_print
    0,                                  // tp_getattr
    0,                                  // tp_setattr
    0,                                  // tp_compare
    0,                                  // tp_repr
    0,                                  // tp_as_number
    0,                                  // tp_as_sequence
    0,                                  // tp_as_mapping
    0,                                  // tp_hash
    0,                                  // tp_call
    0,                                  // tp_str
    PyObject_GenericGetAttr,            // tp_getattro
    0,                                  // tp_setattro
    0,                                  // tp_as_buffer
    Py_TPFLAGS_DEFAULT,                 // tp_flags
    0,                                  // tp_doc
    0,                                  // tp_traverse
    0,                                  // tp_clear
    0,                                  // tp_richcompare
    0,                                  // tp_weaklistoffset
    PyObject_SelfIter,                  // tp_iter
    (iternextfunc)Array_iter<T>::next,  // tp_iternext
    Array_iter<T>::methods              // tp_methods
};

// The following explicit instantiations are necessary for GCC 4.6 but not for
// GCC 4.7.  I don't know why.

Michael Wimmer's avatar
Michael Wimmer committed
1230
1231
1232
template PyObject *repr<long>(PyObject*);
template PyObject *repr<double>(PyObject*);
template PyObject *repr<Complex>(PyObject*);
Christoph Groth's avatar
Christoph Groth committed
1233

Michael Wimmer's avatar
Michael Wimmer committed
1234
1235
1236
template PyObject *str<long>(PyObject*);
template PyObject *str<double>(PyObject*);
template PyObject *str<Complex>(PyObject*);
Christoph Groth's avatar
Christoph Groth committed
1237

1238
1239
1240
template Py_hash_t hash<long>(PyObject*);
template Py_hash_t hash<double>(PyObject*);
template Py_hash_t hash<Complex>(PyObject*);
Christoph Groth's avatar
Christoph Groth committed
1241

Michael Wimmer's avatar
Michael Wimmer committed
1242
1243
1244
template int getbuffer<long>(PyObject*, Py_buffer*, int);
template int getbuffer<double>(PyObject*, Py_buffer*, int);
template int getbuffer<Complex>(PyObject*, Py_buffer*, int);
Christoph Groth's avatar
Christoph Groth committed
1245

Michael Wimmer's avatar
Michael Wimmer committed
1246
1247
1248
template PyObject *getitem<long>(PyObject*, PyObject*);
template PyObject *getitem<double>(PyObject*, PyObject*);
template PyObject *getitem<Complex>(PyObject*, PyObject*);
Christoph Groth's avatar
Christoph Groth committed
1249

Michael Wimmer's avatar
Michael Wimmer committed
1250
1251
1252
template PyObject *seq_getitem<long>(PyObject*, Py_ssize_t);
template PyObject *seq_getitem<double>(PyObject*, Py_ssize_t);
template PyObject *seq_getitem<Complex>(PyObject*, Py_ssize_t);
Christoph Groth's avatar
Christoph Groth committed
1253
1254
1255
1256
1257

} // Anonymous namespace

// **************** Public interface ****************

1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
PyDoc_STRVAR(tinyarray_doc,
"Arrays of numbers for Python, optimized for small sizes\n\n\
\n\
The tinyarray module provides multi-dimensional arrays of numbers, similar to\n\
NumPy, but with the following differences:\n\
\n\
* Optimized for small sizes: Compared to NumPy, common operations on small\n\
  arrays (e.g. length 3) are up to 35 times faster, and 3 times less memory is\n\
  used to store them.\n\
\n\
* Arrays are immutable and hashable, and can be thus used as dictionary keys.\n\
\n\
* The tinyarray module provides only the functionality that is deemed essential\n\
  with small arrays.  For example, there exists a fast tinyarray.dot function,\n\
  but there is no fancy indexing or slicing.\n\
\n\
The module's interface is a basic subset of that of NumPy and hence should be\n\
familiar to many Python programmers.  All functions are simplified versions of\n\
their NumPy counterparts.\n\
\n\
For example, arrays can be created with:\n\
\n\
    tinyarray.array(arraylike, [dtype])\n\
\n\
where arraylike can be a number, a sequence (of sequences, ...) of numbers,\n\
a NumPy or tinyarray array, or another object supporting the buffer protocol.\n\
The dtype parameter is optional and can only take the values int, float, and\n\
complex.  Note that dtype is a positional argument and cannot be used as a\n\
keyword argument.  Arrays can be also created with the functions identity,\n\
zeros, and ones.\n\
\n\
Tinyarrays support iteration and indexing (currently without slicing), as well\n\
as vectorized elementwise arithmetics.  A small number of operations like dot,\n\
floor, and transpose are provided.  Printing works as well as pickling.\n\
Whenever an operation is missing from Tinyarray, NumPy can be used directly,\n\
e.g.: numpy.linalg.det(my_tinyarray).");

Christoph Groth's avatar
Christoph Groth committed
1295
extern "C"
Joseph Weston's avatar
Joseph Weston committed
1296
MOD_INIT_FUNC(tinyarray)
Christoph Groth's avatar
Christoph Groth committed
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
{
    // Determine storage formats.
    bool be = is_big_endian();
    if (std::numeric_limits<double>::is_iec559 &&
        sizeof(double) == 8) {
        format_by_dtype[int(DOUBLE)] = Format(FLOAT64_LE + be);
        format_by_dtype[int(COMPLEX)] = Format(COMPLEX128_LE + be);
    } else {
        format_by_dtype[int(DOUBLE)] = UNKNOWN;
        format_by_dtype[int(COMPLEX)] = UNKNOWN;
    }
    if (sizeof(long) == 8)
        format_by_dtype[int(LONG)] = Format(INT64_LE + be);
    else if (sizeof(long) == 4)
        format_by_dtype[int(LONG)] = Format(INT32_LE + be);
    else
        format_by_dtype[int(LONG)] = UNKNOWN;

Joseph Weston's avatar
Joseph Weston committed
1315
1316
1317
    if (PyType_Ready(&Array<long>::pytype) < 0) return MOD_ERROR_VAL;
    if (PyType_Ready(&Array<double>::pytype) < 0) return MOD_ERROR_VAL;
    if (PyType_Ready(&Array<Complex>::pytype) < 0) return MOD_ERROR_VAL;
Christoph Groth's avatar
Christoph Groth committed
1318

Joseph Weston's avatar
Joseph Weston committed
1319
1320
    PyObject *m;
    MOD_DEF(m, "tinyarray", functions, tinyarray_doc);
Christoph Groth's avatar
Christoph Groth committed
1321
1322
1323
1324
1325
1326
1327
1328
1329

    reconstruct = PyObject_GetAttrString(m, "_reconstruct");

    Py_INCREF(&Array<long>::pytype);
    Py_INCREF(&Array<double>::pytype);
    Py_INCREF(&Array<Complex>::pytype);

    PyModule_AddObject(m, "__version__", PyString_FromString(VERSION));

1330
1331
1332
1333
1334
1335
1336
1337
1338
    PyObject *all = PyList_New(0);
    for (const PyMethodDef *f = functions; f->ml_name; ++f) {
        if (f->ml_name[0] == '_') continue;
        PyObject *f_py = PyObject_GetAttrString(m, f->ml_name);
        PyList_Append(all, PyObject_GetAttrString(f_py, "__name__"));
        Py_DECREF(f_py);
    }
    PyModule_AddObject(m, "__all__", all);

Christoph Groth's avatar
Christoph Groth committed
1339
1340
1341
1342
1343
1344
1345
    PyModule_AddObject(m, "ndarray_int",
                       (PyObject *)&Array<long>::pytype);
    PyModule_AddObject(m, "ndarray_float",
                       (PyObject *)&Array<double>::pytype);
    PyModule_AddObject(m, "ndarray_complex",
                       (PyObject *)&Array<Complex>::pytype);

1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
    // export information on the sizes of different dtypes in bytes
    PyObject *dtype_size = PyDict_New();
    PyDict_SetItem(dtype_size,
                   (PyObject*)&PyInt_Type,
                   PyInt_FromSize_t(sizeof(long)));
    PyDict_SetItem(dtype_size,
                   (PyObject*)&PyFloat_Type,
                   PyInt_FromSize_t(sizeof(double)));
    PyDict_SetItem(dtype_size,
                   (PyObject*)&PyComplex_Type,
                   PyInt_FromSize_t(sizeof(Complex)));
    PyModule_AddObject(m, "dtype_size", dtype_size);

Christoph Groth's avatar
Christoph Groth committed
1359
1360
1361
1362
    // We never release these references but this is not a problem.  The Python
    // interpreter does the same, see try_complex_special_method in
    // complexobject.c
    int_str = PyString_InternFromString("__int__");
Joseph Weston's avatar
Joseph Weston committed
1363
    if (int_str == 0) return MOD_ERROR_VAL;
Christoph Groth's avatar
Christoph Groth committed
1364
    long_str = PyString_InternFromString("__long__");
Joseph Weston's avatar
Joseph Weston committed
1365
    if (long_str == 0) return MOD_ERROR_VAL;
Christoph Groth's avatar
Christoph Groth committed
1366
    float_str = PyString_InternFromString("__float__");
Joseph Weston's avatar
Joseph Weston committed
1367
    if (float_str == 0) return MOD_ERROR_VAL;
Christoph Groth's avatar
Christoph Groth committed
1368
    complex_str = PyString_InternFromString("__complex__");
Joseph Weston's avatar
Joseph Weston committed
1369
    if (complex_str == 0) return MOD_ERROR_VAL;
Christoph Groth's avatar
Christoph Groth committed
1370
    index_str = PyString_InternFromString("__index__");
Joseph Weston's avatar
Joseph Weston committed
1371
1372
1373
    if (complex_str == 0) return MOD_ERROR_VAL;

    return MOD_SUCCESS_VAL(m);
Christoph Groth's avatar
Christoph Groth committed
1374
1375
}

Michael Wimmer's avatar
Michael Wimmer committed
1376
int load_index_seq_as_long(PyObject *obj, long *out, int maxlen)
Christoph Groth's avatar
Christoph Groth committed
1377
1378
{
    assert(maxlen >= 1);
Michael Wimmer's avatar
Michael Wimmer committed
1379
    int len;
Christoph Groth's avatar
Christoph Groth committed
1380
    if (PySequence_Check(obj)) {
1381
        // get a new reference -- don't forget to DECREF on all codepaths
Christoph Groth's avatar
Christoph Groth committed
1382
1383
        obj = PySequence_Fast(obj, "Bug in tinyarray, load_index_seq_as_long");
        if (!obj) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
1384
1385
        Py_ssize_t long_len = PySequence_Fast_GET_SIZE(obj);
        if (long_len > maxlen) {
Christoph Groth's avatar
Christoph Groth committed
1386
            PyErr_Format(PyExc_ValueError, "Sequence too long."
Michael Wimmer's avatar
Michael Wimmer committed
1387
                         " Maximum length is %d.", maxlen);
Christoph Groth's avatar
Christoph Groth committed
1388
1389
            goto fail;
        }
Michael Wimmer's avatar
Michael Wimmer committed
1390
        len = static_cast<int>(long_len);
Christoph Groth's avatar
Christoph Groth committed
1391
1392
1393
1394
1395
1396
1397
1398
        for (PyObject **p = PySequence_Fast_ITEMS(obj), **e = p + len; p < e;
             ++p, ++out) {
            PyObject *index = PyNumber_Index(*p);
            if (index == 0) goto fail;
            *out = PyInt_AsLong(index);
            Py_DECREF(index);
            if (*out == -1 && PyErr_Occurred()) goto fail;
        }
1399
        Py_DECREF(obj);
Christoph Groth's avatar
Christoph Groth committed
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
    } else {
        len = 1;
        *out = PyInt_AsLong(obj);
        if (*out == -1 && PyErr_Occurred()) return -1;
    }
    return len;

fail:
    Py_DECREF(obj);
    return -1;
}

Michael Wimmer's avatar
Michael Wimmer committed
1412
1413
int load_index_seq_as_ulong(PyObject *obj, unsigned long *uout,
                            int maxlen, const char *errmsg)
Christoph Groth's avatar
Christoph Groth committed
1414
1415
{
    long *out = reinterpret_cast<long*>(uout);
Michael Wimmer's avatar
Michael Wimmer committed
1416
    int len = load_index_seq_as_long(obj, out, maxlen);
Christoph Groth's avatar
Christoph Groth committed
1417
    if (len == -1) return -1;
Michael Wimmer's avatar
Michael Wimmer committed
1418
    for (int i = 0; i < len; ++i)
Christoph Groth's avatar
Christoph Groth committed
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
        if (out[i] < 0) {
            if (errmsg == 0)
                errmsg = "Sequence may not contain negative values.";
            PyErr_SetString(PyExc_ValueError, errmsg);
            return -1;
        }
    return len;
}

// If *dtype == NONE the simplest fitting dtype (at least dtype_min)
// will be used and written back to *dtype.  Any other value of *dtype requests
// an array of the given dtype.
1431
1432
PyObject *array_from_arraylike(PyObject *in, Dtype *dtype, Dtype dtype_min,
                               bool as_matrix)
Christoph Groth's avatar
Christoph Groth committed
1433
1434
1435
1436
1437
1438
1439
1440
1441
{
    Dtype dtype_in = get_dtype(in), dt = *dtype;
    int ndim;
    size_t shape[max_ndim];
    PyObject *seqs[max_ndim], *result;
    if (dtype_in != NONE) {
        // `in` is already an array.
        if (dt == NONE)
            dt = Dtype(std::max(int(dtype_in), int(dtype_min)));
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
        if (as_matrix) {
            size_t *in_shape;
            reinterpret_cast<Array_base*>(in)->ndim_shape(&ndim, &in_shape);
            if (ndim == 2) {
                if (dt == dtype_in)
                    Py_INCREF(result = in);
                else
                    result = convert_array(dt, in, dtype_in);
            } else if (ndim < 2) {
                shape[1] = (ndim == 0) ? 1 : in_shape[0];
                shape[0] = 1;
                result = convert_array(dt, in, dtype_in, 2, shape);
Michael Wimmer's avatar
Michael Wimmer committed
1454
            } else {
1455
1456
1457
                PyErr_SetString(PyExc_ValueError,
                                "Matrix must be 2-dimensional.");
                result = 0;
Christoph Groth's avatar
Christoph Groth committed
1458
            }
1459
        } else {
Christoph Groth's avatar
Christoph Groth committed
1460
1461
1462
1463
1464
            if (dt == dtype_in)
                Py_INCREF(result = in);
            else
                result = convert_array(dt, in, dtype_in);
        }
Michael Wimmer's avatar
Michael Wimmer committed
1465
1466
1467

        *dtype = dt;
        return result;
1468
    } else if(PySequence_Check(in)) {
1469
        // `in` is not an array, but is a sequence.
Michael Wimmer's avatar
Michael Wimmer committed
1470

1471
        bool find_type = (dt == NONE);
Michael Wimmer's avatar
Michael Wimmer committed
1472

1473
        // Try if buffer interface is supported.
Michael Wimmer's avatar
Michael Wimmer committed
1474
        Py_buffer view;
Christoph Groth's avatar
Christoph Groth committed
1475
        if (examine_buffer(in, &view, find_type ? &dt : 0) == 0) {
1476
            if (find_type && int(dt) < int(dtype_min)) dt = dtype_min;
Christoph Groth's avatar
Christoph Groth committed
1477
            for (int i = 0; i < view.ndim; i++)
Michael Wimmer's avatar
Michael Wimmer committed
1478
                shape[i] = view.shape[i];
1479
            if (as_matrix && view.ndim != 2) {
Michael Wimmer's avatar
Michael Wimmer committed
1480
1481
1482
1483
1484
1485
1486
1487
                if (view.ndim > 2) {
                    PyErr_SetString(PyExc_ValueError,
                                    "Matrix must be 2-dimensional.");
                    return 0;
                }
                shape[1] = (view.ndim == 0) ? 1 : shape[0];
                shape[0] = 1;
            }
1488
1489
            result = make_and_readin_buffer_dtable[int(dt)](
                &view, (as_matrix ? 2 : view.ndim), shape);
Michael Wimmer's avatar
Michael Wimmer committed
1490
1491
1492
1493
            PyBuffer_Release(&view);

            *dtype = dt;
            return result;
Christoph Groth's avatar
Christoph Groth committed
1494
        }
Michael Wimmer's avatar
Michael Wimmer committed
1495

1496
1497
        if (examine_sequence(in, &ndim, shape, seqs,
                             find_type ? &dt : 0) == 0) {
1498
            if (as_matrix && ndim != 2) {
Michael Wimmer's avatar
Michael Wimmer committed
1499
                if (ndim > 2) {
1500
                    for (int d = 0; d < ndim; ++d) Py_DECREF(seqs[d]);
Michael Wimmer's avatar
Michael Wimmer committed
1501
1502
1503
1504
1505
1506
                    PyErr_SetString(PyExc_ValueError,
                                    "Matrix must be 2-dimensional.");
                    return 0;
                }
                shape[1] = (ndim == 0) ? 1 : shape[0];
                shape[0] = 1;
Christoph Groth's avatar
Christoph Groth committed
1507
            }
Michael Wimmer's avatar
Michael Wimmer committed
1508
1509
1510
1511
            if (find_type) {
                PyObject *seqs_copy[max_ndim];
                for (int d = 0; d < ndim; ++d)
                    Py_INCREF(seqs_copy[d] = seqs[d]);
Christoph Groth's avatar
Christoph Groth committed
1512
                if (dt == NONE) {
1513
                    assert(shape[(as_matrix ? 2 : ndim) - 1] == 0);
Michael Wimmer's avatar
Michael Wimmer committed
1514
                    dt = default_dtype;
Christoph Groth's avatar
Christoph Groth committed
1515
                }
Michael Wimmer's avatar
Michael Wimmer committed
1516
1517
                if (int(dt) < int(dtype_min)) dt = dtype_min;
                while (true) {
1518
1519
                    result = readin_seqs_into_new_dtable[int(dt)](
                        seqs, ndim, (as_matrix ? 2 : ndim), shape, true);
Michael Wimmer's avatar
Michael Wimmer committed
1520
1521
                    if (result) break;
                    dt = Dtype(int(dt) + 1);
Christoph Groth's avatar
Christoph Groth committed
1522
                    if (dt == NONE) {
Michael Wimmer's avatar
Michael Wimmer committed
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
                        result = 0;
                        break;
                    }
                    PyErr_Clear();
                    for (int d = 0; d < ndim; ++d)
                        Py_INCREF(seqs[d] = seqs_copy[d]);
                }
                for (int d = 0; d < ndim; ++d) Py_DECREF(seqs_copy[d]);
            } else {
                // A specific dtype has been requested.
1533
1534
                result = readin_seqs_into_new_dtable[int(dt)](
                    seqs, ndim, (as_matrix ? 2 : ndim), shape, false);
Christoph Groth's avatar
Christoph Groth committed
1535
            }
Michael Wimmer's avatar
Michael Wimmer committed
1536
1537
1538

            *dtype = dt;
            return result;