-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathmapping.c
3400 lines (3014 loc) · 110 KB
/
mapping.c
1
2
3
4
5
6
7
8
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
291
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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
431
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
736
737
738
739
740
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
804
805
806
807
808
809
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
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
904
905
906
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
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
/*#include <stdio.h>*/
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include "numpy/arrayobject.h"
#include "arrayobject.h"
#include "npy_config.h"
#include "npy_pycompat.h"
#include "npy_import.h"
#include "common.h"
#include "ctors.h"
#include "descriptor.h"
#include "iterators.h"
#include "mapping.h"
#include "lowlevel_strided_loops.h"
#include "item_selection.h"
#include "mem_overlap.h"
#include "array_assign.h"
#define HAS_INTEGER 1
#define HAS_NEWAXIS 2
#define HAS_SLICE 4
#define HAS_ELLIPSIS 8
/* HAS_FANCY can be mixed with HAS_0D_BOOL, be careful when to use & or == */
#define HAS_FANCY 16
#define HAS_BOOL 32
/* NOTE: Only set if it is neither fancy nor purely integer index! */
#define HAS_SCALAR_ARRAY 64
/*
* Indicate that this is a fancy index that comes from a 0d boolean.
* This means that the index does not operate along a real axis. The
* corresponding index type is just HAS_FANCY.
*/
#define HAS_0D_BOOL (HAS_FANCY | 128)
static int
_nonzero_indices(PyObject *myBool, PyArrayObject **arrays);
/******************************************************************************
*** IMPLEMENT MAPPING PROTOCOL ***
*****************************************************************************/
NPY_NO_EXPORT Py_ssize_t
array_length(PyArrayObject *self)
{
if (PyArray_NDIM(self) != 0) {
return PyArray_DIMS(self)[0];
} else {
PyErr_SetString(PyExc_TypeError, "len() of unsized object");
return -1;
}
}
/* -------------------------------------------------------------- */
/*NUMPY_API
*
*/
NPY_NO_EXPORT void
PyArray_MapIterSwapAxes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getmap)
{
PyObject *new;
int n1, n2, n3, val, bnd;
int i;
PyArray_Dims permute;
npy_intp d[NPY_MAXDIMS];
PyArrayObject *arr;
permute.ptr = d;
permute.len = mit->nd;
/*
* arr might not have the right number of dimensions
* and need to be reshaped first by pre-pending ones
*/
arr = *ret;
if (PyArray_NDIM(arr) != mit->nd) {
for (i = 1; i <= PyArray_NDIM(arr); i++) {
permute.ptr[mit->nd-i] = PyArray_DIMS(arr)[PyArray_NDIM(arr)-i];
}
for (i = 0; i < mit->nd-PyArray_NDIM(arr); i++) {
permute.ptr[i] = 1;
}
new = PyArray_Newshape(arr, &permute, NPY_ANYORDER);
Py_DECREF(arr);
*ret = (PyArrayObject *)new;
if (new == NULL) {
return;
}
}
/*
* Setting and getting need to have different permutations.
* On the get we are permuting the returned object, but on
* setting we are permuting the object-to-be-set.
* The set permutation is the inverse of the get permutation.
*/
/*
* For getting the array the tuple for transpose is
* (n1,...,n1+n2-1,0,...,n1-1,n1+n2,...,n3-1)
* n1 is the number of dimensions of the broadcast index array
* n2 is the number of dimensions skipped at the start
* n3 is the number of dimensions of the result
*/
/*
* For setting the array the tuple for transpose is
* (n2,...,n1+n2-1,0,...,n2-1,n1+n2,...n3-1)
*/
n1 = mit->nd_fancy;
n2 = mit->consec; /* axes to insert at */
n3 = mit->nd;
/* use n1 as the boundary if getting but n2 if setting */
bnd = getmap ? n1 : n2;
val = bnd;
i = 0;
while (val < n1 + n2) {
permute.ptr[i++] = val++;
}
val = 0;
while (val < bnd) {
permute.ptr[i++] = val++;
}
val = n1 + n2;
while (val < n3) {
permute.ptr[i++] = val++;
}
new = PyArray_Transpose(*ret, &permute);
Py_DECREF(*ret);
*ret = (PyArrayObject *)new;
}
static NPY_INLINE void
multi_DECREF(PyObject **objects, npy_intp n)
{
npy_intp i;
for (i = 0; i < n; i++) {
Py_DECREF(objects[i]);
}
}
/**
* Unpack a tuple into an array of new references. Returns the number of objects
* unpacked.
*
* Useful if a tuple is being iterated over multiple times, or for a code path
* that doesn't always want the overhead of allocating a tuple.
*/
static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
npy_intp n, i;
n = PyTuple_GET_SIZE(index);
if (n > result_n) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
return -1;
}
for (i = 0; i < n; i++) {
result[i] = PyTuple_GET_ITEM(index, i);
Py_INCREF(result[i]);
}
return n;
}
/* Unpack a single scalar index, taking a new reference to match unpack_tuple */
static NPY_INLINE npy_intp
unpack_scalar(PyObject *index, PyObject **result, npy_intp NPY_UNUSED(result_n))
{
Py_INCREF(index);
result[0] = index;
return 1;
}
/**
* Turn an index argument into a c-array of `PyObject *`s, one for each index.
*
* When a scalar is passed, this is written directly to the buffer. When a
* tuple is passed, the tuple elements are unpacked into the buffer.
*
* When some other sequence is passed, this implements the following section
* from the advanced indexing docs to decide whether to unpack or just write
* one element:
*
* > In order to remain backward compatible with a common usage in Numeric,
* > basic slicing is also initiated if the selection object is any non-ndarray
* > sequence (such as a list) containing slice objects, the Ellipsis object,
* > or the newaxis object, but not for integer arrays or other embedded
* > sequences.
*
* It might be worth deprecating this behaviour (gh-4434), in which case the
* entire function should become a simple check of PyTuple_Check.
*
* @param index The index object, which may or may not be a tuple. This is
* a borrowed reference.
* @param result An empty buffer of PyObject* to write each index component
* to. The references written are new.
* @param result_n The length of the result buffer
*
* @returns The number of items in `result`, or -1 if an error occurred.
* The entries in `result` at and beyond this index should be
* assumed to contain garbage, even if they were initialized
* to NULL, so are not safe to Py_XDECREF. Use multi_DECREF to
* dispose of them.
*/
NPY_NO_EXPORT npy_intp
unpack_indices(PyObject *index, PyObject **result, npy_intp result_n)
{
npy_intp n, i;
npy_bool commit_to_unpack;
/* Fast route for passing a tuple */
if (PyTuple_CheckExact(index)) {
return unpack_tuple((PyTupleObject *)index, result, result_n);
}
/* Obvious single-entry cases */
if (0 /* to aid macros below */
#if !defined(NPY_PY3K)
|| PyInt_CheckExact(index)
#else
|| PyLong_CheckExact(index)
#endif
|| index == Py_None
|| PySlice_Check(index)
|| PyArray_Check(index)
|| !PySequence_Check(index)
|| PyBaseString_Check(index)) {
return unpack_scalar(index, result, result_n);
}
/*
* Passing a tuple subclass - coerce to the base type. This incurs an
* allocation, but doesn't need to be a fast path anyway
*/
if (PyTuple_Check(index)) {
PyTupleObject *tup = (PyTupleObject *) PySequence_Tuple(index);
if (tup == NULL) {
return -1;
}
n = unpack_tuple(tup, result, result_n);
Py_DECREF(tup);
return n;
}
/*
* At this point, we're left with a non-tuple, non-array, sequence:
* typically, a list. We use some somewhat-arbitrary heuristics from here
* onwards to decided whether to treat that list as a single index, or a
* list of indices.
*/
/* if len fails, treat like a scalar */
n = PySequence_Size(index);
if (n < 0) {
PyErr_Clear();
return unpack_scalar(index, result, result_n);
}
/*
* Backwards compatibility only takes effect for short sequences - otherwise
* we treat it like any other scalar.
*
* Sequences < NPY_MAXDIMS with any slice objects
* or newaxis, Ellipsis or other arrays or sequences
* embedded, are considered equivalent to an indexing
* tuple. (`a[[[1,2], [3,4]]] == a[[1,2], [3,4]]`)
*/
if (n >= NPY_MAXDIMS) {
return unpack_scalar(index, result, result_n);
}
/* In case we change result_n elsewhere */
assert(n <= result_n);
/*
* Some other type of short sequence - assume we should unpack it like a
* tuple, and then decide whether that was actually necessary.
*/
commit_to_unpack = 0;
for (i = 0; i < n; i++) {
PyObject *tmp_obj = result[i] = PySequence_GetItem(index, i);
if (commit_to_unpack) {
/* propagate errors */
if (tmp_obj == NULL) {
goto fail;
}
}
else {
/*
* if getitem fails (unusual) before we've committed, then stop
* unpacking
*/
if (tmp_obj == NULL) {
PyErr_Clear();
break;
}
/* decide if we should treat this sequence like a tuple */
if (PyArray_Check(tmp_obj)
|| PySequence_Check(tmp_obj)
|| PySlice_Check(tmp_obj)
|| tmp_obj == Py_Ellipsis
|| tmp_obj == Py_None) {
if (DEPRECATE_FUTUREWARNING(
"Using a non-tuple sequence for multidimensional "
"indexing is deprecated; use `arr[tuple(seq)]` "
"instead of `arr[seq]`. In the future this will be "
"interpreted as an array index, `arr[np.array(seq)]`, "
"which will result either in an error or a different "
"result.") < 0) {
i++; /* since loop update doesn't run */
goto fail;
}
commit_to_unpack = 1;
}
}
}
/* unpacking was the right thing to do, and we already did it */
if (commit_to_unpack) {
return n;
}
/* got to the end, never found an indication that we should have unpacked */
else {
/* we partially filled result, so empty it first */
multi_DECREF(result, i);
return unpack_scalar(index, result, result_n);
}
fail:
multi_DECREF(result, i);
return -1;
}
/**
* Prepare an npy_index_object from the python slicing object.
*
* This function handles all index preparations with the exception
* of field access. It fills the array of index_info structs correctly.
* It already handles the boolean array special case for fancy indexing,
* i.e. if the index type is boolean, it is exactly one matching boolean
* array. If the index type is fancy, the boolean array is already
* converted to integer arrays. There is (as before) no checking of the
* boolean dimension.
*
* Checks everything but the bounds.
*
* @param the array being indexed
* @param the index object
* @param index info struct being filled (size of NPY_MAXDIMS * 2 + 1)
* @param number of indices found
* @param dimension of the indexing result
* @param dimension of the fancy/advanced indices part
* @param whether to allow the boolean special case
*
* @returns the index_type or -1 on failure and fills the number of indices.
*/
NPY_NO_EXPORT int
prepare_index(PyArrayObject *self, PyObject *index,
npy_index_info *indices,
int *num, int *ndim, int *out_fancy_ndim, int allow_boolean)
{
int new_ndim, fancy_ndim, used_ndim, index_ndim;
int curr_idx, get_idx;
int i;
npy_intp n;
PyObject *obj = NULL;
PyArrayObject *arr;
int index_type = 0;
int ellipsis_pos = -1;
/*
* The choice of only unpacking `2*NPY_MAXDIMS` items is historic.
* The longest "reasonable" index that produces a result of <= 32 dimensions
* is `(0,)*np.MAXDIMS + (None,)*np.MAXDIMS`. Longer indices can exist, but
* are uncommon.
*/
PyObject *raw_indices[NPY_MAXDIMS*2];
index_ndim = unpack_indices(index, raw_indices, NPY_MAXDIMS*2);
if (index_ndim == -1) {
return -1;
}
/*
* Parse all indices into the `indices` array of index_info structs
*/
used_ndim = 0;
new_ndim = 0;
fancy_ndim = 0;
get_idx = 0;
curr_idx = 0;
while (get_idx < index_ndim) {
if (curr_idx > NPY_MAXDIMS * 2) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
goto failed_building_indices;
}
obj = raw_indices[get_idx++];
/**** Try the cascade of possible indices ****/
/* Index is an ellipsis (`...`) */
if (obj == Py_Ellipsis) {
/* At most one ellipsis in an index */
if (index_type & HAS_ELLIPSIS) {
PyErr_Format(PyExc_IndexError,
"an index can only have a single ellipsis ('...')");
goto failed_building_indices;
}
index_type |= HAS_ELLIPSIS;
indices[curr_idx].type = HAS_ELLIPSIS;
indices[curr_idx].object = NULL;
/* number of slices it is worth, won't update if it is 0: */
indices[curr_idx].value = 0;
ellipsis_pos = curr_idx;
/* the used and new ndim will be found later */
used_ndim += 0;
new_ndim += 0;
curr_idx += 1;
continue;
}
/* Index is np.newaxis/None */
else if (obj == Py_None) {
index_type |= HAS_NEWAXIS;
indices[curr_idx].type = HAS_NEWAXIS;
indices[curr_idx].object = NULL;
used_ndim += 0;
new_ndim += 1;
curr_idx += 1;
continue;
}
/* Index is a slice object. */
else if (PySlice_Check(obj)) {
index_type |= HAS_SLICE;
Py_INCREF(obj);
indices[curr_idx].object = obj;
indices[curr_idx].type = HAS_SLICE;
used_ndim += 1;
new_ndim += 1;
curr_idx += 1;
continue;
}
/*
* Special case to allow 0-d boolean indexing with scalars.
* Should be removed after boolean as integer deprecation.
* Since this is always an error if it was not a boolean, we can
* allow the 0-d special case before the rest.
*/
else if (PyArray_NDIM(self) != 0) {
/*
* Single integer index, there are two cases here.
* It could be an array, a 0-d array is handled
* a bit weird however, so need to special case it.
*
* Check for integers first, purely for performance
*/
#if !defined(NPY_PY3K)
if (PyInt_CheckExact(obj) || !PyArray_Check(obj)) {
#else
if (PyLong_CheckExact(obj) || !PyArray_Check(obj)) {
#endif
npy_intp ind = PyArray_PyIntAsIntp(obj);
if (error_converting(ind)) {
PyErr_Clear();
}
else {
index_type |= HAS_INTEGER;
indices[curr_idx].object = NULL;
indices[curr_idx].value = ind;
indices[curr_idx].type = HAS_INTEGER;
used_ndim += 1;
new_ndim += 0;
curr_idx += 1;
continue;
}
}
}
/*
* At this point, we must have an index array (or array-like).
* It might still be a (purely) bool special case, a 0-d integer
* array (an array scalar) or something invalid.
*/
if (!PyArray_Check(obj)) {
PyArrayObject *tmp_arr;
tmp_arr = (PyArrayObject *)PyArray_FROM_O(obj);
if (tmp_arr == NULL) {
/* TODO: Should maybe replace the error here? */
goto failed_building_indices;
}
/*
* For example an empty list can be cast to an integer array,
* however it will default to a float one.
*/
if (PyArray_SIZE(tmp_arr) == 0) {
PyArray_Descr *indtype = PyArray_DescrFromType(NPY_INTP);
arr = (PyArrayObject *)PyArray_FromArray(tmp_arr, indtype,
NPY_ARRAY_FORCECAST);
Py_DECREF(tmp_arr);
if (arr == NULL) {
goto failed_building_indices;
}
}
else {
arr = tmp_arr;
}
}
else {
Py_INCREF(obj);
arr = (PyArrayObject *)obj;
}
/* Check if the array is valid and fill the information */
if (PyArray_ISBOOL(arr)) {
/*
* There are two types of boolean indices (which are equivalent,
* for the most part though). A single boolean index of matching
* dimensionality and size is a boolean index.
* If this is not the case, it is instead expanded into (multiple)
* integer array indices.
*/
PyArrayObject *nonzero_result[NPY_MAXDIMS];
if ((index_ndim == 1) && allow_boolean) {
/*
* If ndim and size match, this can be optimized as a single
* boolean index. The size check is necessary only to support
* old non-matching sizes by using fancy indexing instead.
* The reason for that is that fancy indexing uses nonzero,
* and only the result of nonzero is checked for legality.
*/
if ((PyArray_NDIM(arr) == PyArray_NDIM(self))
&& PyArray_SIZE(arr) == PyArray_SIZE(self)) {
index_type = HAS_BOOL;
indices[curr_idx].type = HAS_BOOL;
indices[curr_idx].object = (PyObject *)arr;
/* keep track anyway, just to be complete */
used_ndim = PyArray_NDIM(self);
fancy_ndim = PyArray_NDIM(self);
curr_idx += 1;
break;
}
}
if (PyArray_NDIM(arr) == 0) {
/*
* This can actually be well defined. A new axis is added,
* but at the same time no axis is "used". So if we have True,
* we add a new axis (a bit like with np.newaxis). If it is
* False, we add a new axis, but this axis has 0 entries.
*/
index_type |= HAS_FANCY;
indices[curr_idx].type = HAS_0D_BOOL;
/* TODO: This can't fail, right? Is there a faster way? */
if (PyObject_IsTrue((PyObject *)arr)) {
n = 1;
}
else {
n = 0;
}
indices[curr_idx].value = n;
indices[curr_idx].object = PyArray_Zeros(1, &n,
PyArray_DescrFromType(NPY_INTP), 0);
Py_DECREF(arr);
if (indices[curr_idx].object == NULL) {
goto failed_building_indices;
}
used_ndim += 0;
if (fancy_ndim < 1) {
fancy_ndim = 1;
}
curr_idx += 1;
continue;
}
/* Convert the boolean array into multiple integer ones */
n = _nonzero_indices((PyObject *)arr, nonzero_result);
if (n < 0) {
Py_DECREF(arr);
goto failed_building_indices;
}
/* Check that we will not run out of indices to store new ones */
if (curr_idx + n >= NPY_MAXDIMS * 2) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
for (i=0; i < n; i++) {
Py_DECREF(nonzero_result[i]);
}
Py_DECREF(arr);
goto failed_building_indices;
}
/* Add the arrays from the nonzero result to the index */
index_type |= HAS_FANCY;
for (i=0; i < n; i++) {
indices[curr_idx].type = HAS_FANCY;
indices[curr_idx].value = PyArray_DIM(arr, i);
indices[curr_idx].object = (PyObject *)nonzero_result[i];
used_ndim += 1;
curr_idx += 1;
}
Py_DECREF(arr);
/* All added indices have 1 dimension */
if (fancy_ndim < 1) {
fancy_ndim = 1;
}
continue;
}
/* Normal case of an integer array */
else if (PyArray_ISINTEGER(arr)) {
if (PyArray_NDIM(arr) == 0) {
/*
* A 0-d integer array is an array scalar and can
* be dealt with the HAS_SCALAR_ARRAY flag.
* We could handle 0-d arrays early on, but this makes
* sure that array-likes or odder arrays are always
* handled right.
*/
npy_intp ind = PyArray_PyIntAsIntp((PyObject *)arr);
Py_DECREF(arr);
if (error_converting(ind)) {
goto failed_building_indices;
}
else {
index_type |= (HAS_INTEGER | HAS_SCALAR_ARRAY);
indices[curr_idx].object = NULL;
indices[curr_idx].value = ind;
indices[curr_idx].type = HAS_INTEGER;
used_ndim += 1;
new_ndim += 0;
curr_idx += 1;
continue;
}
}
index_type |= HAS_FANCY;
indices[curr_idx].type = HAS_FANCY;
indices[curr_idx].value = -1;
indices[curr_idx].object = (PyObject *)arr;
used_ndim += 1;
if (fancy_ndim < PyArray_NDIM(arr)) {
fancy_ndim = PyArray_NDIM(arr);
}
curr_idx += 1;
continue;
}
/*
* The array does not have a valid type.
*/
if ((PyObject *)arr == obj) {
/* The input was an array already */
PyErr_SetString(PyExc_IndexError,
"arrays used as indices must be of integer (or boolean) type");
}
else {
/* The input was not an array, so give a general error message */
PyErr_SetString(PyExc_IndexError,
"only integers, slices (`:`), ellipsis (`...`), "
"numpy.newaxis (`None`) and integer or boolean "
"arrays are valid indices");
}
Py_DECREF(arr);
goto failed_building_indices;
}
/*
* Compare dimension of the index to the real ndim. this is
* to find the ellipsis value or append an ellipsis if necessary.
*/
if (used_ndim < PyArray_NDIM(self)) {
if (index_type & HAS_ELLIPSIS) {
indices[ellipsis_pos].value = PyArray_NDIM(self) - used_ndim;
used_ndim = PyArray_NDIM(self);
new_ndim += indices[ellipsis_pos].value;
}
else {
/*
* There is no ellipsis yet, but it is not a full index
* so we append an ellipsis to the end.
*/
index_type |= HAS_ELLIPSIS;
indices[curr_idx].object = NULL;
indices[curr_idx].type = HAS_ELLIPSIS;
indices[curr_idx].value = PyArray_NDIM(self) - used_ndim;
ellipsis_pos = curr_idx;
used_ndim = PyArray_NDIM(self);
new_ndim += indices[curr_idx].value;
curr_idx += 1;
}
}
else if (used_ndim > PyArray_NDIM(self)) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
goto failed_building_indices;
}
else if (index_ndim == 0) {
/*
* 0-d index into 0-d array, i.e. array[()]
* We consider this an integer index. Which means it will return
* the scalar.
* This makes sense, because then array[...] gives
* an array and array[()] gives the scalar.
*/
used_ndim = 0;
index_type = HAS_INTEGER;
}
/* HAS_SCALAR_ARRAY requires cleaning up the index_type */
if (index_type & HAS_SCALAR_ARRAY) {
/* clear as info is unnecessary and makes life harder later */
if (index_type & HAS_FANCY) {
index_type -= HAS_SCALAR_ARRAY;
}
/* A full integer index sees array scalars as part of itself */
else if (index_type == (HAS_INTEGER | HAS_SCALAR_ARRAY)) {
index_type -= HAS_SCALAR_ARRAY;
}
}
/*
* At this point indices are all set correctly, no bounds checking
* has been made and the new array may still have more dimensions
* than is possible and boolean indexing arrays may have an incorrect shape.
*
* Check this now so we do not have to worry about it later.
* It can happen for fancy indexing or with newaxis.
* This means broadcasting errors in the case of too many dimensions
* take less priority.
*/
if (index_type & (HAS_NEWAXIS | HAS_FANCY)) {
if (new_ndim + fancy_ndim > NPY_MAXDIMS) {
PyErr_Format(PyExc_IndexError,
"number of dimensions must be within [0, %d], "
"indexing result would have %d",
NPY_MAXDIMS, (new_ndim + fancy_ndim));
goto failed_building_indices;
}
/*
* If we had a fancy index, we may have had a boolean array index.
* So check if this had the correct shape now that we can find out
* which axes it acts on.
*/
used_ndim = 0;
for (i = 0; i < curr_idx; i++) {
if ((indices[i].type == HAS_FANCY) && indices[i].value > 0) {
if (indices[i].value != PyArray_DIM(self, used_ndim)) {
char err_msg[174];
PyOS_snprintf(err_msg, sizeof(err_msg),
"boolean index did not match indexed array along "
"dimension %d; dimension is %" NPY_INTP_FMT
" but corresponding boolean dimension is %" NPY_INTP_FMT,
used_ndim, PyArray_DIM(self, used_ndim),
indices[i].value);
PyErr_SetString(PyExc_IndexError, err_msg);
goto failed_building_indices;
}
}
if (indices[i].type == HAS_ELLIPSIS) {
used_ndim += indices[i].value;
}
else if ((indices[i].type == HAS_NEWAXIS) ||
(indices[i].type == HAS_0D_BOOL)) {
used_ndim += 0;
}
else {
used_ndim += 1;
}
}
}
*num = curr_idx;
*ndim = new_ndim + fancy_ndim;
*out_fancy_ndim = fancy_ndim;
multi_DECREF(raw_indices, index_ndim);
return index_type;
failed_building_indices:
for (i=0; i < curr_idx; i++) {
Py_XDECREF(indices[i].object);
}
multi_DECREF(raw_indices, index_ndim);
return -1;
}
/**
* Check if self has memory overlap with one of the index arrays, or with extra_op.
*
* @returns 1 if memory overlap found, 0 if not.
*/
NPY_NO_EXPORT int
index_has_memory_overlap(PyArrayObject *self,
int index_type, npy_index_info *indices, int num,
PyObject *extra_op)
{
int i;
if (index_type & (HAS_FANCY | HAS_BOOL)) {
for (i = 0; i < num; ++i) {
if (indices[i].object != NULL &&
PyArray_Check(indices[i].object) &&
solve_may_share_memory(self,
(PyArrayObject *)indices[i].object,
1) != 0) {
return 1;
}
}
}
if (extra_op != NULL && PyArray_Check(extra_op) &&
solve_may_share_memory(self, (PyArrayObject *)extra_op, 1) != 0) {
return 1;
}
return 0;
}
/**
* Get pointer for an integer index.
*
* For a purely integer index, set ptr to the memory address.
* Returns 0 on success, -1 on failure.
* The caller must ensure that the index is a full integer
* one.
*
* @param Array being indexed
* @param result pointer
* @param parsed index information
* @param number of indices
*
* @return 0 on success -1 on failure
*/
static int
get_item_pointer(PyArrayObject *self, char **ptr,
npy_index_info *indices, int index_num) {
int i;
*ptr = PyArray_BYTES(self);
for (i=0; i < index_num; i++) {
if ((check_and_adjust_index(&(indices[i].value),
PyArray_DIMS(self)[i], i, NULL)) < 0) {
return -1;
}
*ptr += PyArray_STRIDE(self, i) * indices[i].value;
}
return 0;
}
/**
* Get view into an array using all non-array indices.
*
* For any index, get a view of the subspace into the original
* array. If there are no fancy indices, this is the result of
* the indexing operation.
* Ensure_array allows to fetch a safe subspace view for advanced
* indexing.
*
* @param Array being indexed
* @param resulting array (new reference)
* @param parsed index information
* @param number of indices
* @param Whether result should inherit the type from self
*
* @return 0 on success -1 on failure
*/
static int
get_view_from_index(PyArrayObject *self, PyArrayObject **view,
npy_index_info *indices, int index_num, int ensure_array) {
npy_intp new_strides[NPY_MAXDIMS];
npy_intp new_shape[NPY_MAXDIMS];
int i, j;
int new_dim = 0;
int orig_dim = 0;
char *data_ptr = PyArray_BYTES(self);
/* for slice parsing */
npy_intp start, stop, step, n_steps;
for (i=0; i < index_num; i++) {
switch (indices[i].type) {
case HAS_INTEGER:
if ((check_and_adjust_index(&indices[i].value,
PyArray_DIMS(self)[orig_dim], orig_dim,
NULL)) < 0) {
return -1;
}
data_ptr += PyArray_STRIDE(self, orig_dim) * indices[i].value;
new_dim += 0;
orig_dim += 1;
break;
case HAS_ELLIPSIS:
for (j=0; j < indices[i].value; j++) {
new_strides[new_dim] = PyArray_STRIDE(self, orig_dim);
new_shape[new_dim] = PyArray_DIMS(self)[orig_dim];
new_dim += 1;
orig_dim += 1;
}
break;
case HAS_SLICE:
if (NpySlice_GetIndicesEx(indices[i].object,
PyArray_DIMS(self)[orig_dim],
&start, &stop, &step, &n_steps) < 0) {
return -1;
}
if (n_steps <= 0) {
/* TODO: Always points to start then, could change that */
n_steps = 0;
step = 1;
start = 0;
}
data_ptr += PyArray_STRIDE(self, orig_dim) * start;
new_strides[new_dim] = PyArray_STRIDE(self, orig_dim) * step;
new_shape[new_dim] = n_steps;
new_dim += 1;
orig_dim += 1;
break;
case HAS_NEWAXIS:
new_strides[new_dim] = 0;
new_shape[new_dim] = 1;
new_dim += 1;
break;
/* Fancy and 0-d boolean indices are ignored here */
case HAS_0D_BOOL:
break;
default:
new_dim += 0;
orig_dim += 1;
break;
}
}
/* Create the new view and set the base array */
Py_INCREF(PyArray_DESCR(self));
*view = (PyArrayObject *)PyArray_NewFromDescrAndBase(
ensure_array ? &PyArray_Type : Py_TYPE(self),
PyArray_DESCR(self),
new_dim, new_shape, new_strides, data_ptr,
PyArray_FLAGS(self),
ensure_array ? NULL : (PyObject *)self,
(PyObject *)self);
if (*view == NULL) {
return -1;
}
return 0;
}