/
compiled_base.c
1975 lines (1771 loc) · 57.9 KB
/
compiled_base.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 NPY_NO_DEPRECATED_API NPY_API_VERSION
#include <Python.h>
#include <structmember.h>
#include <string.h>
#define _MULTIARRAYMODULE
#include "numpy/arrayobject.h"
#include "numpy/npy_3kcompat.h"
#include "numpy/npy_math.h"
#include "npy_config.h"
#include "templ_common.h" /* for npy_mul_with_overflow_intp */
#include "lowlevel_strided_loops.h" /* for npy_bswap8 */
#include "alloc.h"
#include "ctors.h"
#include "common.h"
#include "simd/simd.h"
typedef enum {
PACK_ORDER_LITTLE = 0,
PACK_ORDER_BIG
} PACK_ORDER;
/*
* Returns -1 if the array is monotonic decreasing,
* +1 if the array is monotonic increasing,
* and 0 if the array is not monotonic.
*/
static int
check_array_monotonic(const double *a, npy_intp lena)
{
npy_intp i;
double next;
double last;
if (lena == 0) {
/* all bin edges hold the same value */
return 1;
}
last = a[0];
/* Skip repeated values at the beginning of the array */
for (i = 1; (i < lena) && (a[i] == last); i++);
if (i == lena) {
/* all bin edges hold the same value */
return 1;
}
next = a[i];
if (last < next) {
/* Possibly monotonic increasing */
for (i += 1; i < lena; i++) {
last = next;
next = a[i];
if (last > next) {
return 0;
}
}
return 1;
}
else {
/* last > next, possibly monotonic decreasing */
for (i += 1; i < lena; i++) {
last = next;
next = a[i];
if (last < next) {
return 0;
}
}
return -1;
}
}
/* Find the minimum and maximum of an integer array */
static void
minmax(const npy_intp *data, npy_intp data_len, npy_intp *mn, npy_intp *mx)
{
npy_intp min = *data;
npy_intp max = *data;
while (--data_len) {
const npy_intp val = *(++data);
if (val < min) {
min = val;
}
else if (val > max) {
max = val;
}
}
*mn = min;
*mx = max;
}
/*
* arr_bincount is registered as bincount.
*
* bincount accepts one, two or three arguments. The first is an array of
* non-negative integers The second, if present, is an array of weights,
* which must be promotable to double. Call these arguments list and
* weight. Both must be one-dimensional with len(weight) == len(list). If
* weight is not present then bincount(list)[i] is the number of occurrences
* of i in list. If weight is present then bincount(self,list, weight)[i]
* is the sum of all weight[j] where list [j] == i. Self is not used.
* The third argument, if present, is a minimum length desired for the
* output array.
*/
NPY_NO_EXPORT PyObject *
arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds)
{
PyObject *list = NULL, *weight = Py_None, *mlength = NULL;
PyArrayObject *lst = NULL, *ans = NULL, *wts = NULL;
npy_intp *numbers, *ians, len, mx, mn, ans_size;
npy_intp minlength = 0;
npy_intp i;
double *weights , *dans;
static char *kwlist[] = {"list", "weights", "minlength", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO:bincount",
kwlist, &list, &weight, &mlength)) {
goto fail;
}
lst = (PyArrayObject *)PyArray_ContiguousFromAny(list, NPY_INTP, 1, 1);
if (lst == NULL) {
goto fail;
}
len = PyArray_SIZE(lst);
/*
* This if/else if can be removed by changing the argspec to O|On above,
* once we retire the deprecation
*/
if (mlength == Py_None) {
/* NumPy 1.14, 2017-06-01 */
if (DEPRECATE("0 should be passed as minlength instead of None; "
"this will error in future.") < 0) {
goto fail;
}
}
else if (mlength != NULL) {
minlength = PyArray_PyIntAsIntp(mlength);
if (error_converting(minlength)) {
goto fail;
}
}
if (minlength < 0) {
PyErr_SetString(PyExc_ValueError,
"'minlength' must not be negative");
goto fail;
}
/* handle empty list */
if (len == 0) {
ans = (PyArrayObject *)PyArray_ZEROS(1, &minlength, NPY_INTP, 0);
if (ans == NULL){
goto fail;
}
Py_DECREF(lst);
return (PyObject *)ans;
}
numbers = (npy_intp *)PyArray_DATA(lst);
minmax(numbers, len, &mn, &mx);
if (mn < 0) {
PyErr_SetString(PyExc_ValueError,
"'list' argument must have no negative elements");
goto fail;
}
ans_size = mx + 1;
if (mlength != Py_None) {
if (ans_size < minlength) {
ans_size = minlength;
}
}
if (weight == Py_None) {
ans = (PyArrayObject *)PyArray_ZEROS(1, &ans_size, NPY_INTP, 0);
if (ans == NULL) {
goto fail;
}
ians = (npy_intp *)PyArray_DATA(ans);
NPY_BEGIN_ALLOW_THREADS;
for (i = 0; i < len; i++)
ians[numbers[i]] += 1;
NPY_END_ALLOW_THREADS;
Py_DECREF(lst);
}
else {
wts = (PyArrayObject *)PyArray_ContiguousFromAny(
weight, NPY_DOUBLE, 1, 1);
if (wts == NULL) {
goto fail;
}
weights = (double *)PyArray_DATA(wts);
if (PyArray_SIZE(wts) != len) {
PyErr_SetString(PyExc_ValueError,
"The weights and list don't have the same length.");
goto fail;
}
ans = (PyArrayObject *)PyArray_ZEROS(1, &ans_size, NPY_DOUBLE, 0);
if (ans == NULL) {
goto fail;
}
dans = (double *)PyArray_DATA(ans);
NPY_BEGIN_ALLOW_THREADS;
for (i = 0; i < len; i++) {
dans[numbers[i]] += weights[i];
}
NPY_END_ALLOW_THREADS;
Py_DECREF(lst);
Py_DECREF(wts);
}
return (PyObject *)ans;
fail:
Py_XDECREF(lst);
Py_XDECREF(wts);
Py_XDECREF(ans);
return NULL;
}
/* Internal function to expose check_array_monotonic to python */
NPY_NO_EXPORT PyObject *
arr__monotonicity(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"x", NULL};
PyObject *obj_x = NULL;
PyArrayObject *arr_x = NULL;
long monotonic;
npy_intp len_x;
NPY_BEGIN_THREADS_DEF;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|_monotonicity", kwlist,
&obj_x)) {
return NULL;
}
/*
* TODO:
* `x` could be strided, needs change to check_array_monotonic
* `x` is forced to double for this check
*/
arr_x = (PyArrayObject *)PyArray_FROMANY(
obj_x, NPY_DOUBLE, 1, 1, NPY_ARRAY_CARRAY_RO);
if (arr_x == NULL) {
return NULL;
}
len_x = PyArray_SIZE(arr_x);
NPY_BEGIN_THREADS_THRESHOLDED(len_x)
monotonic = check_array_monotonic(
(const double *)PyArray_DATA(arr_x), len_x);
NPY_END_THREADS
Py_DECREF(arr_x);
return PyLong_FromLong(monotonic);
}
/*
* Returns input array with values inserted sequentially into places
* indicated by the mask
*/
NPY_NO_EXPORT PyObject *
arr_insert(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
{
char *src, *dest;
npy_bool *mask_data;
PyArray_Descr *dtype;
PyArray_CopySwapFunc *copyswap;
PyObject *array0, *mask0, *values0;
PyArrayObject *array, *mask, *values;
npy_intp i, j, chunk, nm, ni, nv;
static char *kwlist[] = {"input", "mask", "vals", NULL};
NPY_BEGIN_THREADS_DEF;
values = mask = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O!OO:place", kwlist,
&PyArray_Type, &array0, &mask0, &values0)) {
return NULL;
}
array = (PyArrayObject *)PyArray_FromArray((PyArrayObject *)array0, NULL,
NPY_ARRAY_CARRAY | NPY_ARRAY_WRITEBACKIFCOPY);
if (array == NULL) {
goto fail;
}
ni = PyArray_SIZE(array);
dest = PyArray_DATA(array);
chunk = PyArray_DESCR(array)->elsize;
mask = (PyArrayObject *)PyArray_FROM_OTF(mask0, NPY_BOOL,
NPY_ARRAY_CARRAY | NPY_ARRAY_FORCECAST);
if (mask == NULL) {
goto fail;
}
nm = PyArray_SIZE(mask);
if (nm != ni) {
PyErr_SetString(PyExc_ValueError,
"place: mask and data must be "
"the same size");
goto fail;
}
mask_data = PyArray_DATA(mask);
dtype = PyArray_DESCR(array);
Py_INCREF(dtype);
values = (PyArrayObject *)PyArray_FromAny(values0, dtype,
0, 0, NPY_ARRAY_CARRAY, NULL);
if (values == NULL) {
goto fail;
}
nv = PyArray_SIZE(values); /* zero if null array */
if (nv <= 0) {
npy_bool allFalse = 1;
i = 0;
while (allFalse && i < ni) {
if (mask_data[i]) {
allFalse = 0;
} else {
i++;
}
}
if (!allFalse) {
PyErr_SetString(PyExc_ValueError,
"Cannot insert from an empty array!");
goto fail;
} else {
Py_XDECREF(values);
Py_XDECREF(mask);
PyArray_ResolveWritebackIfCopy(array);
Py_XDECREF(array);
Py_RETURN_NONE;
}
}
src = PyArray_DATA(values);
j = 0;
copyswap = PyArray_DESCR(array)->f->copyswap;
NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(array));
for (i = 0; i < ni; i++) {
if (mask_data[i]) {
if (j >= nv) {
j = 0;
}
copyswap(dest + i*chunk, src + j*chunk, 0, array);
j++;
}
}
NPY_END_THREADS;
Py_XDECREF(values);
Py_XDECREF(mask);
PyArray_ResolveWritebackIfCopy(array);
Py_DECREF(array);
Py_RETURN_NONE;
fail:
Py_XDECREF(mask);
PyArray_ResolveWritebackIfCopy(array);
Py_XDECREF(array);
Py_XDECREF(values);
return NULL;
}
#define LIKELY_IN_CACHE_SIZE 8
#ifdef __INTEL_COMPILER
#pragma intel optimization_level 0
#endif
static NPY_INLINE npy_intp
_linear_search(const npy_double key, const npy_double *arr, const npy_intp len, const npy_intp i0)
{
npy_intp i;
for (i = i0; i < len && key >= arr[i]; i++);
return i - 1;
}
/** @brief find index of a sorted array such that arr[i] <= key < arr[i + 1].
*
* If an starting index guess is in-range, the array values around this
* index are first checked. This allows for repeated calls for well-ordered
* keys (a very common case) to use the previous index as a very good guess.
*
* If the guess value is not useful, bisection of the array is used to
* find the index. If there is no such index, the return values are:
* key < arr[0] -- -1
* key == arr[len - 1] -- len - 1
* key > arr[len - 1] -- len
* The array is assumed contiguous and sorted in ascending order.
*
* @param key key value.
* @param arr contiguous sorted array to be searched.
* @param len length of the array.
* @param guess initial guess of index
* @return index
*/
static npy_intp
binary_search_with_guess(const npy_double key, const npy_double *arr,
npy_intp len, npy_intp guess)
{
npy_intp imin = 0;
npy_intp imax = len;
/* Handle keys outside of the arr range first */
if (key > arr[len - 1]) {
return len;
}
else if (key < arr[0]) {
return -1;
}
/*
* If len <= 4 use linear search.
* From above we know key >= arr[0] when we start.
*/
if (len <= 4) {
return _linear_search(key, arr, len, 1);
}
if (guess > len - 3) {
guess = len - 3;
}
if (guess < 1) {
guess = 1;
}
/* check most likely values: guess - 1, guess, guess + 1 */
if (key < arr[guess]) {
if (key < arr[guess - 1]) {
imax = guess - 1;
/* last attempt to restrict search to items in cache */
if (guess > LIKELY_IN_CACHE_SIZE &&
key >= arr[guess - LIKELY_IN_CACHE_SIZE]) {
imin = guess - LIKELY_IN_CACHE_SIZE;
}
}
else {
/* key >= arr[guess - 1] */
return guess - 1;
}
}
else {
/* key >= arr[guess] */
if (key < arr[guess + 1]) {
return guess;
}
else {
/* key >= arr[guess + 1] */
if (key < arr[guess + 2]) {
return guess + 1;
}
else {
/* key >= arr[guess + 2] */
imin = guess + 2;
/* last attempt to restrict search to items in cache */
if (guess < len - LIKELY_IN_CACHE_SIZE - 1 &&
key < arr[guess + LIKELY_IN_CACHE_SIZE]) {
imax = guess + LIKELY_IN_CACHE_SIZE;
}
}
}
}
/* finally, find index by bisection */
while (imin < imax) {
const npy_intp imid = imin + ((imax - imin) >> 1);
if (key >= arr[imid]) {
imin = imid + 1;
}
else {
imax = imid;
}
}
return imin - 1;
}
#undef LIKELY_IN_CACHE_SIZE
NPY_NO_EXPORT PyObject *
arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
{
PyObject *fp, *xp, *x;
PyObject *left = NULL, *right = NULL;
PyArrayObject *afp = NULL, *axp = NULL, *ax = NULL, *af = NULL;
npy_intp i, lenx, lenxp;
npy_double lval, rval;
const npy_double *dy, *dx, *dz;
npy_double *dres, *slopes = NULL;
static char *kwlist[] = {"x", "xp", "fp", "left", "right", NULL};
NPY_BEGIN_THREADS_DEF;
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OO:interp", kwlist,
&x, &xp, &fp, &left, &right)) {
return NULL;
}
afp = (PyArrayObject *)PyArray_ContiguousFromAny(fp, NPY_DOUBLE, 1, 1);
if (afp == NULL) {
return NULL;
}
axp = (PyArrayObject *)PyArray_ContiguousFromAny(xp, NPY_DOUBLE, 1, 1);
if (axp == NULL) {
goto fail;
}
ax = (PyArrayObject *)PyArray_ContiguousFromAny(x, NPY_DOUBLE, 0, 0);
if (ax == NULL) {
goto fail;
}
lenxp = PyArray_SIZE(axp);
if (lenxp == 0) {
PyErr_SetString(PyExc_ValueError,
"array of sample points is empty");
goto fail;
}
if (PyArray_SIZE(afp) != lenxp) {
PyErr_SetString(PyExc_ValueError,
"fp and xp are not of the same length.");
goto fail;
}
af = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ax),
PyArray_DIMS(ax), NPY_DOUBLE);
if (af == NULL) {
goto fail;
}
lenx = PyArray_SIZE(ax);
dy = (const npy_double *)PyArray_DATA(afp);
dx = (const npy_double *)PyArray_DATA(axp);
dz = (const npy_double *)PyArray_DATA(ax);
dres = (npy_double *)PyArray_DATA(af);
/* Get left and right fill values. */
if ((left == NULL) || (left == Py_None)) {
lval = dy[0];
}
else {
lval = PyFloat_AsDouble(left);
if (error_converting(lval)) {
goto fail;
}
}
if ((right == NULL) || (right == Py_None)) {
rval = dy[lenxp - 1];
}
else {
rval = PyFloat_AsDouble(right);
if (error_converting(rval)) {
goto fail;
}
}
/* binary_search_with_guess needs at least a 3 item long array */
if (lenxp == 1) {
const npy_double xp_val = dx[0];
const npy_double fp_val = dy[0];
NPY_BEGIN_THREADS_THRESHOLDED(lenx);
for (i = 0; i < lenx; ++i) {
const npy_double x_val = dz[i];
dres[i] = (x_val < xp_val) ? lval :
((x_val > xp_val) ? rval : fp_val);
}
NPY_END_THREADS;
}
else {
npy_intp j = 0;
/* only pre-calculate slopes if there are relatively few of them. */
if (lenxp <= lenx) {
slopes = PyArray_malloc((lenxp - 1) * sizeof(npy_double));
if (slopes == NULL) {
PyErr_NoMemory();
goto fail;
}
}
NPY_BEGIN_THREADS;
if (slopes != NULL) {
for (i = 0; i < lenxp - 1; ++i) {
slopes[i] = (dy[i+1] - dy[i]) / (dx[i+1] - dx[i]);
}
}
for (i = 0; i < lenx; ++i) {
const npy_double x_val = dz[i];
if (npy_isnan(x_val)) {
dres[i] = x_val;
continue;
}
j = binary_search_with_guess(x_val, dx, lenxp, j);
if (j == -1) {
dres[i] = lval;
}
else if (j == lenxp) {
dres[i] = rval;
}
else if (j == lenxp - 1) {
dres[i] = dy[j];
}
else if (dx[j] == x_val) {
/* Avoid potential non-finite interpolation */
dres[i] = dy[j];
}
else {
const npy_double slope =
(slopes != NULL) ? slopes[j] :
(dy[j+1] - dy[j]) / (dx[j+1] - dx[j]);
/* If we get nan in one direction, try the other */
dres[i] = slope*(x_val - dx[j]) + dy[j];
if (NPY_UNLIKELY(npy_isnan(dres[i]))) {
dres[i] = slope*(x_val - dx[j+1]) + dy[j+1];
if (NPY_UNLIKELY(npy_isnan(dres[i])) && dy[j] == dy[j+1]) {
dres[i] = dy[j];
}
}
}
}
NPY_END_THREADS;
}
PyArray_free(slopes);
Py_DECREF(afp);
Py_DECREF(axp);
Py_DECREF(ax);
return PyArray_Return(af);
fail:
Py_XDECREF(afp);
Py_XDECREF(axp);
Py_XDECREF(ax);
Py_XDECREF(af);
return NULL;
}
/* As for arr_interp but for complex fp values */
NPY_NO_EXPORT PyObject *
arr_interp_complex(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
{
PyObject *fp, *xp, *x;
PyObject *left = NULL, *right = NULL;
PyArrayObject *afp = NULL, *axp = NULL, *ax = NULL, *af = NULL;
npy_intp i, lenx, lenxp;
const npy_double *dx, *dz;
const npy_cdouble *dy;
npy_cdouble lval, rval;
npy_cdouble *dres, *slopes = NULL;
static char *kwlist[] = {"x", "xp", "fp", "left", "right", NULL};
NPY_BEGIN_THREADS_DEF;
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OO:interp_complex",
kwlist, &x, &xp, &fp, &left, &right)) {
return NULL;
}
afp = (PyArrayObject *)PyArray_ContiguousFromAny(fp, NPY_CDOUBLE, 1, 1);
if (afp == NULL) {
return NULL;
}
axp = (PyArrayObject *)PyArray_ContiguousFromAny(xp, NPY_DOUBLE, 1, 1);
if (axp == NULL) {
goto fail;
}
ax = (PyArrayObject *)PyArray_ContiguousFromAny(x, NPY_DOUBLE, 0, 0);
if (ax == NULL) {
goto fail;
}
lenxp = PyArray_SIZE(axp);
if (lenxp == 0) {
PyErr_SetString(PyExc_ValueError,
"array of sample points is empty");
goto fail;
}
if (PyArray_SIZE(afp) != lenxp) {
PyErr_SetString(PyExc_ValueError,
"fp and xp are not of the same length.");
goto fail;
}
lenx = PyArray_SIZE(ax);
dx = (const npy_double *)PyArray_DATA(axp);
dz = (const npy_double *)PyArray_DATA(ax);
af = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ax),
PyArray_DIMS(ax), NPY_CDOUBLE);
if (af == NULL) {
goto fail;
}
dy = (const npy_cdouble *)PyArray_DATA(afp);
dres = (npy_cdouble *)PyArray_DATA(af);
/* Get left and right fill values. */
if ((left == NULL) || (left == Py_None)) {
lval = dy[0];
}
else {
lval.real = PyComplex_RealAsDouble(left);
if (error_converting(lval.real)) {
goto fail;
}
lval.imag = PyComplex_ImagAsDouble(left);
if (error_converting(lval.imag)) {
goto fail;
}
}
if ((right == NULL) || (right == Py_None)) {
rval = dy[lenxp - 1];
}
else {
rval.real = PyComplex_RealAsDouble(right);
if (error_converting(rval.real)) {
goto fail;
}
rval.imag = PyComplex_ImagAsDouble(right);
if (error_converting(rval.imag)) {
goto fail;
}
}
/* binary_search_with_guess needs at least a 3 item long array */
if (lenxp == 1) {
const npy_double xp_val = dx[0];
const npy_cdouble fp_val = dy[0];
NPY_BEGIN_THREADS_THRESHOLDED(lenx);
for (i = 0; i < lenx; ++i) {
const npy_double x_val = dz[i];
dres[i] = (x_val < xp_val) ? lval :
((x_val > xp_val) ? rval : fp_val);
}
NPY_END_THREADS;
}
else {
npy_intp j = 0;
/* only pre-calculate slopes if there are relatively few of them. */
if (lenxp <= lenx) {
slopes = PyArray_malloc((lenxp - 1) * sizeof(npy_cdouble));
if (slopes == NULL) {
PyErr_NoMemory();
goto fail;
}
}
NPY_BEGIN_THREADS;
if (slopes != NULL) {
for (i = 0; i < lenxp - 1; ++i) {
const double inv_dx = 1.0 / (dx[i+1] - dx[i]);
slopes[i].real = (dy[i+1].real - dy[i].real) * inv_dx;
slopes[i].imag = (dy[i+1].imag - dy[i].imag) * inv_dx;
}
}
for (i = 0; i < lenx; ++i) {
const npy_double x_val = dz[i];
if (npy_isnan(x_val)) {
dres[i].real = x_val;
dres[i].imag = 0.0;
continue;
}
j = binary_search_with_guess(x_val, dx, lenxp, j);
if (j == -1) {
dres[i] = lval;
}
else if (j == lenxp) {
dres[i] = rval;
}
else if (j == lenxp - 1) {
dres[i] = dy[j];
}
else if (dx[j] == x_val) {
/* Avoid potential non-finite interpolation */
dres[i] = dy[j];
}
else {
npy_cdouble slope;
if (slopes != NULL) {
slope = slopes[j];
}
else {
const npy_double inv_dx = 1.0 / (dx[j+1] - dx[j]);
slope.real = (dy[j+1].real - dy[j].real) * inv_dx;
slope.imag = (dy[j+1].imag - dy[j].imag) * inv_dx;
}
/* If we get nan in one direction, try the other */
dres[i].real = slope.real*(x_val - dx[j]) + dy[j].real;
if (NPY_UNLIKELY(npy_isnan(dres[i].real))) {
dres[i].real = slope.real*(x_val - dx[j+1]) + dy[j+1].real;
if (NPY_UNLIKELY(npy_isnan(dres[i].real)) &&
dy[j].real == dy[j+1].real) {
dres[i].real = dy[j].real;
}
}
dres[i].imag = slope.imag*(x_val - dx[j]) + dy[j].imag;
if (NPY_UNLIKELY(npy_isnan(dres[i].imag))) {
dres[i].imag = slope.imag*(x_val - dx[j+1]) + dy[j+1].imag;
if (NPY_UNLIKELY(npy_isnan(dres[i].imag)) &&
dy[j].imag == dy[j+1].imag) {
dres[i].imag = dy[j].imag;
}
}
}
}
NPY_END_THREADS;
}
PyArray_free(slopes);
Py_DECREF(afp);
Py_DECREF(axp);
Py_DECREF(ax);
return PyArray_Return(af);
fail:
Py_XDECREF(afp);
Py_XDECREF(axp);
Py_XDECREF(ax);
Py_XDECREF(af);
return NULL;
}
static const char *EMPTY_SEQUENCE_ERR_MSG = "indices must be integral: the provided " \
"empty sequence was inferred as float. Wrap it with " \
"'np.array(indices, dtype=np.intp)'";
static const char *NON_INTEGRAL_ERROR_MSG = "only int indices permitted";
/* Convert obj to an ndarray with integer dtype or fail */
static PyArrayObject *
astype_anyint(PyObject *obj) {
PyArrayObject *ret;
if (!PyArray_Check(obj)) {
/* prefer int dtype */
PyArray_Descr *dtype_guess = NULL;
if (PyArray_DTypeFromObject(obj, NPY_MAXDIMS, &dtype_guess) < 0) {
return NULL;
}
if (dtype_guess == NULL) {
if (PySequence_Check(obj) && PySequence_Size(obj) == 0) {
PyErr_SetString(PyExc_TypeError, EMPTY_SEQUENCE_ERR_MSG);
}
return NULL;
}
ret = (PyArrayObject*)PyArray_FromAny(obj, dtype_guess, 0, 0, 0, NULL);
if (ret == NULL) {
return NULL;
}
}
else {
ret = (PyArrayObject *)obj;
Py_INCREF(ret);
}
if (!(PyArray_ISINTEGER(ret) || PyArray_ISBOOL(ret))) {
/* ensure dtype is int-based */
PyErr_SetString(PyExc_TypeError, NON_INTEGRAL_ERROR_MSG);
Py_DECREF(ret);
return NULL;
}
return ret;
}
/*
* Converts a Python sequence into 'count' PyArrayObjects
*
* seq - Input Python object, usually a tuple but any sequence works.
* Must have integral content.
* paramname - The name of the parameter that produced 'seq'.
* count - How many arrays there should be (errors if it doesn't match).
* op - Where the arrays are placed.
*/
static int int_sequence_to_arrays(PyObject *seq,
char *paramname,
int count,
PyArrayObject **op
)
{
int i;
if (!PySequence_Check(seq) || PySequence_Size(seq) != count) {
PyErr_Format(PyExc_ValueError,
"parameter %s must be a sequence of length %d",
paramname, count);
return -1;
}
for (i = 0; i < count; ++i) {
PyObject *item = PySequence_GetItem(seq, i);
if (item == NULL) {
goto fail;
}
op[i] = astype_anyint(item);
Py_DECREF(item);
if (op[i] == NULL) {
goto fail;
}
}
return 0;
fail:
while (--i >= 0) {
Py_XDECREF(op[i]);
op[i] = NULL;
}
return -1;
}
/* Inner loop for ravel_multi_index */
static int
ravel_multi_index_loop(int ravel_ndim, npy_intp *ravel_dims,
npy_intp *ravel_strides,
npy_intp count,
NPY_CLIPMODE *modes,
char **coords, npy_intp *coords_strides)
{
int i;
char invalid;
npy_intp j, m;
/*
* Check for 0-dimensional axes unless there is nothing to do.
* An empty array/shape cannot be indexed at all.
*/
if (count != 0) {
for (i = 0; i < ravel_ndim; ++i) {
if (ravel_dims[i] == 0) {
PyErr_SetString(PyExc_ValueError,
"cannot unravel if shape has zero entries (is empty).");
return NPY_FAIL;
}
}
}
NPY_BEGIN_ALLOW_THREADS;
invalid = 0;
while (count--) {
npy_intp raveled = 0;
for (i = 0; i < ravel_ndim; ++i) {
m = ravel_dims[i];
j = *(npy_intp *)coords[i];
switch (modes[i]) {
case NPY_RAISE:
if (j < 0 || j >= m) {
invalid = 1;
goto end_while;
}
break;
case NPY_WRAP:
if (j < 0) {
j += m;
if (j < 0) {
j = j % m;
if (j != 0) {
j += m;
}
}
}
else if (j >= m) {
j -= m;
if (j >= m) {
j = j % m;
}
}
break;
case NPY_CLIP:
if (j < 0) {
j = 0;
}
else if (j >= m) {
j = m - 1;