-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmethods.c
More file actions
1755 lines (1565 loc) · 56.3 KB
/
Copy pathmethods.c
File metadata and controls
1755 lines (1565 loc) · 56.3 KB
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
# include "Python.h"
# define NO_IMPORT_ARRAY
# define PY_ARRAY_UNIQUE_SYMBOL AK_ARRAY_API
# define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
# include "numpy/arrayobject.h"
# include "numpy/arrayscalars.h"
# include "numpy/halffloat.h"
# include <string.h>
# ifdef _WIN32
# include <io.h>
# else
# include <unistd.h>
# endif
# include "methods.h"
# include "utilities.h"
PyObject *
count_iteration(PyObject *Py_UNUSED(m), PyObject *iterable)
{
PyObject *iter = PyObject_GetIter(iterable);
if (iter == NULL) return NULL;
int count = 0;
PyObject *v;
while ((v = PyIter_Next(iter))) {
count++;
Py_DECREF(v);
}
Py_DECREF(iter);
if (PyErr_Occurred()) {
return NULL;
}
PyObject* result = PyLong_FromLong(count);
if (result == NULL) return NULL;
return result;
}
PyObject *
row_1d_filter(PyObject *Py_UNUSED(m), PyObject *a)
{
AK_CHECK_NUMPY_ARRAY_1D_2D(a);
PyArrayObject *array = (PyArrayObject *)a;
if (PyArray_NDIM(array) == 2) {
npy_intp dim[1] = {PyArray_DIM(array, 1)};
PyArray_Dims shape = {dim, 1};
// NOTE: this will set PyErr if shape is not compatible
return PyArray_Newshape(array, &shape, NPY_ANYORDER);
}
Py_INCREF(a);
return a;
}
PyObject *
slice_to_ascending_slice(PyObject *Py_UNUSED(m), PyObject *args) {
PyObject* slice;
PyObject* size;
if (!PyArg_ParseTuple(args,
"O!O!:slice_to_ascending_slice",
&PySlice_Type, &slice,
&PyLong_Type, &size)) {
return NULL;
}
// will delegate NULL on error
return AK_slice_to_ascending_slice(slice, PyLong_AsSsize_t(size));
}
PyObject *
slice_to_unit(PyObject *Py_UNUSED(m), PyObject *a)
{
if (!PySlice_Check(a)) {
return PyErr_Format(PyExc_TypeError,
"Expected a slice, not %s",
Py_TYPE(a)->tp_name);
}
PyObject* py_start = ((PySliceObject*)a)->start;
PyObject* py_stop = ((PySliceObject*)a)->stop;
PyObject* py_step = ((PySliceObject*)a)->step;
if (py_stop == Py_None) {
return PyLong_FromLong(-1);
}
Py_ssize_t step = 1;
if (py_step != Py_None) {
step = PyNumber_AsSsize_t(py_step, NULL);
if (step == -1 && PyErr_Occurred()) {
return NULL;
}
}
if (step != 1) {
return PyLong_FromLong(-1);
}
Py_ssize_t start = 0;
if (py_start != Py_None) {
start = PyNumber_AsSsize_t(py_start, NULL);
if (start == -1 && PyErr_Occurred()) {
return NULL;
}
}
Py_ssize_t stop = PyNumber_AsSsize_t(py_stop, NULL);
if (stop == -1 && PyErr_Occurred()) {
return NULL;
}
if (start < 0 || stop < 0 || stop - start != 1) {
return PyLong_FromLong(-1);
}
return PyLong_FromSsize_t(start);
}
PyObject *
column_2d_filter(PyObject *Py_UNUSED(m), PyObject *a)
{
AK_CHECK_NUMPY_ARRAY_1D_2D(a);
PyArrayObject *array = (PyArrayObject *)a;
if (PyArray_NDIM(array) == 1) {
// https://numpy.org/doc/stable/reference/c-api/types-and-structures.html#c.PyArray_Dims
npy_intp dim[2] = {PyArray_DIM(array, 0), 1};
PyArray_Dims shape = {dim, 2};
// PyArray_Newshape might return NULL and set PyErr, so no handling to do here
return PyArray_Newshape(array, &shape, NPY_ANYORDER); // already a PyObject*
}
Py_INCREF(a); // returning borrowed ref, must increment
return a;
}
PyObject *
column_1d_filter(PyObject *Py_UNUSED(m), PyObject *a)
{
AK_CHECK_NUMPY_ARRAY_1D_2D(a);
PyArrayObject *array = (PyArrayObject *)a;
if (PyArray_NDIM(array) == 2) {
npy_intp dim[1] = {PyArray_DIM(array, 0)};
PyArray_Dims shape = {dim, 1};
// NOTE: this will set PyErr if shape is not compatible
return PyArray_Newshape(array, &shape, NPY_ANYORDER);
}
Py_INCREF(a);
return a;
}
PyObject *
shape_filter(PyObject *Py_UNUSED(m), PyObject *a) {
AK_CHECK_NUMPY_ARRAY_1D_2D(a);
PyArrayObject *array = (PyArrayObject *)a;
npy_intp rows = PyArray_DIM(array, 0);
// If 1D array, set size for axis 1 at 1, else use 2D array to get the size of axis 1
npy_intp cols = PyArray_NDIM(array) == 1 ? 1 : PyArray_DIM(array, 1);
return AK_build_pair_ssize_t(rows, cols);
}
PyObject *
name_filter(PyObject *Py_UNUSED(m), PyObject *n) {
if (AK_UNLIKELY(PyObject_Hash(n) == -1)) {
return PyErr_Format(PyExc_TypeError,
"unhashable name (type '%s')",
Py_TYPE(n)->tp_name);
}
Py_INCREF(n);
return n;
}
PyObject *
mloc(PyObject *Py_UNUSED(m), PyObject *a)
{
AK_CHECK_NUMPY_ARRAY(a);
return PyLong_FromVoidPtr(PyArray_DATA((PyArrayObject *)a));
}
PyObject *
immutable_filter(PyObject *Py_UNUSED(m), PyObject *a) {
AK_CHECK_NUMPY_ARRAY(a);
return (PyObject *)AK_immutable_filter((PyArrayObject *)a);
}
PyObject *
resolve_dtype(PyObject *Py_UNUSED(m), PyObject *args)
{
PyArray_Descr *d1, *d2;
if (!PyArg_ParseTuple(args,
"O!O!:resolve_dtype",
&PyArrayDescr_Type, &d1,
&PyArrayDescr_Type, &d2)) {
return NULL;
}
return (PyObject *)AK_resolve_dtype(d1, d2);
}
PyObject *
resolve_dtype_iter(PyObject *Py_UNUSED(m), PyObject *arg) {
PyObject *iterator = PyObject_GetIter(arg);
if (iterator == NULL) {
// No need to set exception here. GetIter already sets TypeError
return NULL;
}
PyArray_Descr *resolved = NULL;
PyArray_Descr *dtype;
while ((dtype = (PyArray_Descr*) PyIter_Next(iterator))) {
if (!PyArray_DescrCheck(dtype)) {
PyErr_Format(
PyExc_TypeError, "argument must be an iterable over %s, not %s",
((PyTypeObject *) &PyArrayDescr_Type)->tp_name,
Py_TYPE(dtype)->tp_name
);
Py_DECREF(iterator);
Py_DECREF(dtype);
Py_XDECREF(resolved);
return NULL;
}
if (!resolved) {
resolved = dtype;
continue;
}
Py_SETREF(resolved, AK_resolve_dtype(resolved, dtype));
Py_DECREF(dtype);
if (!resolved || PyDataType_ISOBJECT(resolved)) {
break;
}
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
return NULL;
}
if (!resolved) {
// this could happen if this function gets an empty tuple
PyErr_SetString(PyExc_ValueError, "iterable passed to resolve dtypes is empty");
}
return (PyObject *)resolved;
}
PyObject *
nonzero_1d(PyObject *Py_UNUSED(m), PyObject *a) {
AK_CHECK_NUMPY_ARRAY(a);
PyArrayObject* array = (PyArrayObject*)a;
if (PyArray_NDIM(array) != 1) {
PyErr_SetString(PyExc_ValueError, "Array must be 1-dimensional");
return NULL;
}
if (PyArray_TYPE(array) != NPY_BOOL) {
PyErr_SetString(PyExc_ValueError, "Array must be of type bool");
return NULL;
}
return AK_nonzero_1d(array);
}
static inline int
AK_append_transition_slice(PyObject* slices, npy_intp start, npy_intp stop)
{
PyObject* py_start = PyLong_FromSsize_t(start);
if (!py_start) {
return -1;
}
PyObject* py_stop = NULL;
if (stop == -1) {
py_stop = Py_None;
Py_INCREF(py_stop);
}
else {
py_stop = PyLong_FromSsize_t(stop);
}
if (!py_stop) {
Py_DECREF(py_start);
return -1;
}
PyObject* slc = PySlice_New(py_start, py_stop, Py_None);
Py_DECREF(py_start);
Py_DECREF(py_stop);
if (!slc) {
return -1;
}
int append_result = PyList_Append(slices, slc);
Py_DECREF(slc);
return append_result;
}
// Return 1 if the two elements are not equal (a transition), 0 if equal, -1 on
// error. Equality matches numpy's elementwise `!=`: byte-exact for integral,
// string, and void dtypes; IEEE-aware for floats (NaN != NaN, +0.0 == -0.0);
// and NaT-aware for datetime64/timedelta64 (NaT != everything, including NaT).
// Uncommon dtypes (complex, float16, longdouble, object) fall back to a boxed
// Python comparison, which is correct though slower.
static inline int
AK_values_not_equal_1d(PyArrayObject* array, npy_intp left, npy_intp right)
{
npy_intp stride = PyArray_STRIDE(array, 0);
char* p_left = PyArray_BYTES(array) + (left * stride);
char* p_right = PyArray_BYTES(array) + (right * stride);
switch (PyArray_TYPE(array)) {
// For these dtypes numpy `!=` is exactly a byte comparison, so memcmp
// is both correct and the fastest option (no Python objects created).
case NPY_BOOL:
case NPY_BYTE: case NPY_UBYTE:
case NPY_SHORT: case NPY_USHORT:
case NPY_INT: case NPY_UINT:
case NPY_LONG: case NPY_ULONG:
case NPY_LONGLONG: case NPY_ULONGLONG:
case NPY_STRING: case NPY_UNICODE: case NPY_VOID:
return memcmp(p_left, p_right, (size_t)PyArray_ITEMSIZE(array)) != 0;
// Floats need IEEE semantics, which a byte compare would get wrong for
// NaN (distinct bits compare equal under ==) and signed zero.
case NPY_FLOAT: {
float a, b;
memcpy(&a, p_left, sizeof a);
memcpy(&b, p_right, sizeof b);
return a != b;
}
case NPY_DOUBLE: {
double a, b;
memcpy(&a, p_left, sizeof a);
memcpy(&b, p_right, sizeof b);
return a != b;
}
// datetime64/timedelta64 are int64 with NaT == INT64_MIN;
case NPY_DATETIME:
case NPY_TIMEDELTA: {
npy_int64 a, b;
memcpy(&a, p_left, sizeof a);
memcpy(&b, p_right, sizeof b);
if (a == NPY_DATETIME_NAT || b == NPY_DATETIME_NAT) {
return 1;
}
return a != b;
}
}
// Object dtype and any unhandled type: compare via Python objects.
PyObject* left_value = PyArray_GETITEM(array, p_left);
if (!left_value) {
return -1;
}
PyObject* right_value = PyArray_GETITEM(array, p_right);
if (!right_value) {
Py_DECREF(left_value);
return -1;
}
int is_not_equal = PyObject_RichCompareBool(left_value, right_value, Py_NE);
Py_DECREF(left_value);
Py_DECREF(right_value);
return is_not_equal;
}
// Compare two rows of a 2d array. Object arrays are compared cell-by-cell with
// rich equality, consistent with the 1d object path (AK_values_not_equal_1d);
// all other dtypes are compared bytewise, matching numpy's void-view equality.
static inline int
AK_rows_equal_2d(PyArrayObject* array, npy_intp left, npy_intp right)
{
if (PyArray_TYPE(array) == NPY_OBJECT) {
npy_intp cols = PyArray_DIM(array, 1);
for (npy_intp col = 0; col < cols; ++col) {
PyObject* left_value = *(PyObject**)PyArray_GETPTR2(array, left, col);
PyObject* right_value = *(PyObject**)PyArray_GETPTR2(array, right, col);
int is_equal = PyObject_RichCompareBool(left_value, right_value, Py_EQ);
if (is_equal <= 0) {
return is_equal; // 0 (not equal) or -1 (error)
}
}
return 1;
}
npy_intp stride_0 = PyArray_STRIDE(array, 0);
npy_intp stride_1 = PyArray_STRIDE(array, 1);
npy_intp cols = PyArray_DIM(array, 1);
npy_intp itemsize = PyArray_ITEMSIZE(array);
char* p_left = PyArray_BYTES(array) + (left * stride_0);
char* p_right = PyArray_BYTES(array) + (right * stride_0);
if (stride_1 == itemsize) {
return memcmp(p_left, p_right, (size_t)(cols * itemsize)) == 0;
}
for (npy_intp col = 0; col < cols; ++col) {
npy_intp offset = col * stride_1;
if (memcmp(p_left + offset, p_right + offset, (size_t)itemsize) != 0) {
return 0;
}
}
return 1;
}
// Scan a contiguous, monomorphic 1d buffer for transitions. EQ tests whether
// element i equals element i-1; the inner loop runs over equal runs with no
// function call so the compiler can keep it tight (and vectorize the compare).
// On a transition, emit the run [start, i) and continue. `goto finalize` after.
#define AK_SCAN_TRANSITIONS(EQ) \
do { \
npy_intp i = 1; \
while (i < size) { \
while (i < size && (EQ)) { ++i; } \
if (i >= size) { break; } \
if (AK_append_transition_slice(slices, start, i)) { return -1; } \
start = i; \
++i; \
} \
} while (0)
// Append transition slices for a 1d array to `slices`. Returns 0 on success,
// -1 on error. Common contiguous dtypes use a hoisted, typed scan; everything
// else (non-contiguous, strings, void, complex, half, longdouble, object, or
// unusual widths) falls back to the per-element comparison.
static int
AK_fill_transition_slices_1d(PyArrayObject* working, npy_intp size, PyObject* slices)
{
npy_intp start = 0;
const char* base = PyArray_BYTES(working);
npy_intp stride = PyArray_STRIDE(working, 0);
npy_intp itemsize = PyArray_ITEMSIZE(working);
if (stride == itemsize) {
switch (PyArray_TYPE(working)) {
case NPY_DOUBLE: {
// == honors IEEE semantics: NaN != NaN, +0.0 == -0.0
const double* v = (const double*)base;
AK_SCAN_TRANSITIONS(v[i] == v[i - 1]);
goto finalize;
}
case NPY_FLOAT: {
const float* v = (const float*)base;
AK_SCAN_TRANSITIONS(v[i] == v[i - 1]);
goto finalize;
}
case NPY_DATETIME:
case NPY_TIMEDELTA: {
// NaT (INT64_MIN) is unequal to everything, including itself
const npy_int64* v = (const npy_int64*)base;
AK_SCAN_TRANSITIONS(v[i - 1] != NPY_DATETIME_NAT
&& v[i] != NPY_DATETIME_NAT
&& v[i] == v[i - 1]);
goto finalize;
}
case NPY_BOOL:
case NPY_BYTE: case NPY_UBYTE:
case NPY_SHORT: case NPY_USHORT:
case NPY_INT: case NPY_UINT:
case NPY_LONG: case NPY_ULONG:
case NPY_LONGLONG: case NPY_ULONGLONG: {
// Integral dtypes: `!=` is raw-bit inequality, so compare by width.
switch (itemsize) {
case 1: { const npy_uint8* v = (const npy_uint8*)base; AK_SCAN_TRANSITIONS(v[i] == v[i - 1]); goto finalize; }
case 2: { const npy_uint16* v = (const npy_uint16*)base; AK_SCAN_TRANSITIONS(v[i] == v[i - 1]); goto finalize; }
case 4: { const npy_uint32* v = (const npy_uint32*)base; AK_SCAN_TRANSITIONS(v[i] == v[i - 1]); goto finalize; }
case 8: { const npy_uint64* v = (const npy_uint64*)base; AK_SCAN_TRANSITIONS(v[i] == v[i - 1]); goto finalize; }
default: break;
}
break;
}
case NPY_OBJECT: {
// Read the stored PyObject* directly (borrowed, GIL held) and
// rich-compare, skipping PyArray_GETITEM dispatch and refcount
// churn. The compare can error, so this can't use the macro.
PyObject** v = (PyObject**)base;
npy_intp i = 1;
while (i < size) {
while (i < size) {
int eq = PyObject_RichCompareBool(v[i], v[i - 1], Py_EQ);
if (eq < 0) {
return -1;
}
if (!eq) {
break;
}
++i;
}
if (i >= size) {
break;
}
if (AK_append_transition_slice(slices, start, i)) {
return -1;
}
start = i;
++i;
}
goto finalize;
}
default:
break;
}
}
// Generic fallback.
for (npy_intp i = 1; i < size; ++i) {
int is_transition = AK_values_not_equal_1d(working, i - 1, i);
if (is_transition < 0) {
return -1;
}
if (is_transition) {
if (AK_append_transition_slice(slices, start, i)) {
return -1;
}
start = i;
}
}
finalize:
if (start < size) {
if (AK_append_transition_slice(slices, start, -1)) {
return -1;
}
}
return 0;
}
#undef AK_SCAN_TRANSITIONS
PyObject *
transition_slices_from_group(PyObject *Py_UNUSED(m), PyObject *a)
{
AK_CHECK_NUMPY_ARRAY_1D_2D(a);
PyArrayObject* group = (PyArrayObject*)a;
bool group_to_tuple = PyArray_NDIM(group) == 2;
npy_intp size = PyArray_DIM(group, 0);
PyArrayObject* working = group;
Py_INCREF(working);
PyObject* slices = PyList_New(0);
if (!slices) {
Py_DECREF(working);
return NULL;
}
if (!group_to_tuple) {
if (AK_fill_transition_slices_1d(working, size, slices)) {
Py_DECREF(working);
Py_DECREF(slices);
return NULL;
}
}
else {
npy_intp start = 0;
for (npy_intp i = 1; i < size; ++i) {
int is_equal = AK_rows_equal_2d(working, i - 1, i);
if (is_equal < 0) {
Py_DECREF(working);
Py_DECREF(slices);
return NULL;
}
if (!is_equal) {
if (AK_append_transition_slice(slices, start, i)) {
Py_DECREF(working);
Py_DECREF(slices);
return NULL;
}
start = i;
}
}
if (start < size) {
if (AK_append_transition_slice(slices, start, -1)) {
Py_DECREF(working);
Py_DECREF(slices);
return NULL;
}
}
}
Py_DECREF(working);
PyObject* slices_iter = PyObject_GetIter(slices);
Py_DECREF(slices);
if (!slices_iter) {
return NULL;
}
PyObject* result = PyTuple_Pack(2, slices_iter, group_to_tuple ? Py_True : Py_False);
Py_DECREF(slices_iter);
return result;
}
PyObject*
is_objectable_dt64(PyObject *m, PyObject *a) {
AK_CHECK_NUMPY_ARRAY(a);
PyArrayObject* array = (PyArrayObject*)a;
// this returns a new reference
PyObject* dt_year = PyObject_GetAttrString(m, "dt_year");
int is_objectable = AK_is_objectable_dt64(array, dt_year);
Py_DECREF(dt_year);
switch (is_objectable) {
case -1:
return NULL;
case 0:
Py_RETURN_FALSE;
case 1:
Py_RETURN_TRUE;
}
return NULL;
}
PyObject*
is_objectable(PyObject *m, PyObject *a) {
AK_CHECK_NUMPY_ARRAY(a);
PyArrayObject* array = (PyArrayObject*)a;
char kind = PyArray_DESCR(array)->kind;
if ((kind == 'M' || kind == 'm')) {
// this returns a new reference
PyObject* dt_year = PyObject_GetAttrString(m, "dt_year");
int is_objectable = AK_is_objectable_dt64(array, dt_year);
Py_DECREF(dt_year);
switch (is_objectable) {
case -1:
return NULL;
case 0:
Py_RETURN_FALSE;
case 1:
Py_RETURN_TRUE;
}
}
Py_RETURN_TRUE;
}
// Convert array to the dtype provided. NOTE: mutable arrays will be returned unless the input array is immutable and no dtype change is needed
PyObject*
astype_array(PyObject* m, PyObject* args) {
PyObject* a = NULL;
PyObject* dtype_spec = Py_None;
if (!PyArg_ParseTuple(args, "O!|O:astype_array",
&PyArray_Type, &a,
&dtype_spec)) {
return NULL;
}
PyArrayObject* array = (PyArrayObject*)a;
PyArray_Descr* dtype = NULL;
if (dtype_spec == Py_None) {
dtype = PyArray_DescrFromType(NPY_DEFAULT_TYPE);
} else {
if (!PyArray_DescrConverter(dtype_spec, &dtype)) {
return NULL;
}
}
if (PyArray_EquivTypes(PyArray_DESCR(array), dtype)) {
Py_DECREF(dtype);
if (PyArray_ISWRITEABLE(array)) {
PyObject* result = PyArray_NewCopy(array, NPY_ANYORDER);
if (!result) {
return NULL;
}
return result;
}
else { // already immutable
Py_INCREF(a);
return a;
}
}
// if converting to an object
if (dtype->type_num == NPY_OBJECT) {
char kind = PyArray_DESCR(array)->kind;
if ((kind == 'M' || kind == 'm')) {
PyObject* dt_year = PyObject_GetAttrString(m, "dt_year");
int is_objectable = AK_is_objectable_dt64(array, dt_year);
Py_DECREF(dt_year);
if (!is_objectable) {
PyObject* result = PyArray_NewLikeArray(array, NPY_ANYORDER, dtype, 0);
if (!result) {
Py_DECREF(dtype);
return NULL;
}
PyObject** data = (PyObject**)PyArray_DATA((PyArrayObject*)result);
PyArrayIterObject* it = (PyArrayIterObject*)PyArray_IterNew(a);
if (!it) {
Py_DECREF(result);
return NULL;
}
npy_intp i = 0;
while (it->index < it->size) {
PyObject* item = PyArray_ToScalar(it->dataptr, array);
if (!item) {
Py_DECREF(result);
Py_DECREF(it);
return NULL;
}
data[i++] = item;
PyArray_ITER_NEXT(it);
}
Py_DECREF(it);
return result;
}
}
}
// all other cases: do a standard cast conversion
PyObject* result = PyArray_CastToType(array, dtype, 0);
if (!result) {
Py_DECREF(dtype);
return NULL;
}
return result;
}
static char *first_true_1d_kwarg_names[] = {
"array",
"forward",
NULL
};
PyObject *
first_true_1d(PyObject *Py_UNUSED(m), PyObject *args, PyObject *kwargs)
{
PyArrayObject *array = NULL;
int forward = 1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"O!|$p:first_true_1d",
first_true_1d_kwarg_names,
&PyArray_Type, &array,
&forward
)) {
return NULL;
}
if (PyArray_NDIM(array) != 1) {
PyErr_SetString(PyExc_ValueError, "Array must be 1-dimensional");
return NULL;
}
if (PyArray_TYPE(array) != NPY_BOOL) {
PyErr_SetString(PyExc_ValueError, "Array must be of type bool");
return NULL;
}
if (!PyArray_IS_C_CONTIGUOUS(array)) {
PyErr_SetString(PyExc_ValueError, "Array must be contiguous");
return NULL;
}
npy_intp lookahead = sizeof(npy_uint64);
npy_intp size = PyArray_SIZE(array);
lldiv_t size_div = lldiv((long long)size, lookahead); // quot, rem
npy_bool *array_buffer = (npy_bool*)PyArray_DATA(array);
NPY_BEGIN_THREADS_DEF;
NPY_BEGIN_THREADS;
Py_ssize_t position = -1;
npy_bool *p;
npy_bool *p_end;
npy_bool *p_end_roll;
if (forward) {
p = array_buffer;
p_end = p + size;
p_end_roll = p_end - size_div.rem;
while (p < p_end_roll) {
if (*(npy_uint64*)p != 0) {
break; // found a true within lookahead
}
p += lookahead;
}
while (p < p_end) {
if (*p) break;
p++;
}
}
else {
p = array_buffer + size - 1;
p_end = array_buffer - 1;
p_end_roll = p_end + size_div.rem;
while (p > p_end_roll) {
if (*(npy_uint64*)(p - lookahead + 1) != 0) {
break; // found a true within lookahead
}
p -= lookahead;
}
while (p > p_end) {
if (*p) break;
p--;
}
}
if (p != p_end) { // else, return -1
position = p - array_buffer;
}
NPY_END_THREADS;
PyObject* post = PyLong_FromSsize_t(position);
return post;
}
static char *first_true_2d_kwarg_names[] = {
"array",
"forward",
"axis",
NULL
};
PyObject *
first_true_2d(PyObject *Py_UNUSED(m), PyObject *args, PyObject *kwargs)
{
PyArrayObject *array = NULL;
int forward = 1;
int axis = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"O!|$pi:first_true_2d",
first_true_2d_kwarg_names,
&PyArray_Type,
&array,
&forward,
&axis
)) {
return NULL;
}
if (PyArray_NDIM(array) != 2) {
PyErr_SetString(PyExc_ValueError, "Array must be 2-dimensional");
return NULL;
}
if (PyArray_TYPE(array) != NPY_BOOL) {
PyErr_SetString(PyExc_ValueError, "Array must be of type bool");
return NULL;
}
if (axis < 0 || axis > 1) {
PyErr_SetString(PyExc_ValueError, "Axis must be 0 or 1");
return NULL;
}
// NOTE: we copy the entire array into contiguous memory when necessary.
// axis = 0 returns the pos per col
// axis = 1 returns the pos per row (as contiguous bytes)
// if c contiguous:
// axis == 0: transpose, copy to C
// axis == 1: keep
// if f contiguous:
// axis == 0: transpose, keep
// axis == 1: copy to C
// else
// axis == 0: transpose, copy to C
// axis == 1: copy to C
bool transpose = !axis; // if 1, false
bool corder = true;
if ((PyArray_IS_C_CONTIGUOUS(array) && axis == 1) ||
(PyArray_IS_F_CONTIGUOUS(array) && axis == 0)) {
corder = false;
}
// create pointer to "indicator" array; if newly allocated, it will need to be decrefed before function termination
PyArrayObject *array_ind = NULL;
bool decref_array_ind = false;
if (transpose && !corder) {
array_ind = (PyArrayObject *)PyArray_Transpose(array, NULL);
if (array_ind == NULL) return NULL;
decref_array_ind = true;
}
else if (!transpose && corder) {
array_ind = (PyArrayObject *)PyArray_NewCopy(array, NPY_CORDER);
if (array_ind == NULL) return NULL;
decref_array_ind = true;
}
else if (transpose && corder) {
PyArrayObject *tmp = (PyArrayObject *)PyArray_Transpose(array, NULL);
if (tmp == NULL) return NULL;
array_ind = (PyArrayObject *)PyArray_NewCopy(tmp, NPY_CORDER);
Py_DECREF((PyObject*)tmp);
if (array_ind == NULL) return NULL;
decref_array_ind = true;
}
else {
array_ind = array; // can use array, no decref needed
}
npy_intp lookahead = sizeof(npy_uint64);
// buffer of indicators
npy_bool *buffer_ind = (npy_bool*)PyArray_DATA(array_ind);
npy_intp count_row = PyArray_DIM(array_ind, 0);
npy_intp count_col = PyArray_DIM(array_ind, 1);
lldiv_t div_col = lldiv((long long)count_col, lookahead); // quot, rem
npy_intp dims_post = {count_row};
PyArrayObject *array_pos = (PyArrayObject*)PyArray_EMPTY(
1, // ndim
&dims_post,// shape
NPY_INT64, // dtype
0 // fortran
);
if (array_pos == NULL) {
return NULL;
}
npy_int64 *buffer_pos = (npy_int64*)PyArray_DATA(array_pos);
NPY_BEGIN_THREADS_DEF;
NPY_BEGIN_THREADS;
npy_intp position;
npy_bool *p;
npy_bool *p_start;
npy_bool *p_end;
// iterate one row at a time; short-circult when found
// for axis 1 rows are rows; for axis 0, rows are (post transpose) columns
for (npy_intp r = 0; r < count_row; r++) {
position = -1; // update for each row
if (forward) {
// get start of each row
p_start = buffer_ind + (count_col * r);
p = p_start;
p_end = p + count_col; // end of each row
// scan each row from the front and terminate when True
// remove from the end the remainder
while (p < p_end - div_col.rem) {
if (*(npy_uint64*)p != 0) {
break; // found a true
}
p += lookahead;
}
while (p < p_end) {
if (*p) {break;}
p++;
}
if (p != p_end) {
position = p - p_start;
}
}
else { // reverse
// start at the next row, then subtract one for last elem in previous row
p_start = buffer_ind + (count_col * (r + 1)) - 1;
p = p_start;
// end is 1 less than start of each row
p_end = buffer_ind + (count_col * r) - 1;
while (p > p_end + div_col.rem) {
// must go to start of lookahead
if (*(npy_uint64*)(p - lookahead + 1) != 0) {
break; // found a true
}
p -= lookahead;
}
while (p > p_end) {
if (*p) {break;}
p--;
}
if (p != p_end) {
position = p - (p_end + 1);
}
}
*buffer_pos++ = position;
}
NPY_END_THREADS;
if (decref_array_ind) {
Py_DECREF(array_ind); // created in this function
}
return (PyObject *)array_pos;
}
PyObject *
dtype_from_element(PyObject *Py_UNUSED(m), PyObject *arg)
{
// -------------------------------------------------------------------------
// 1. Handle fast, exact type checks first.
if (arg == Py_None) {
return (PyObject*)PyArray_DescrFromType(NPY_OBJECT);
}
if (PyFloat_CheckExact(arg)) {
return (PyObject*)PyArray_DescrFromType(NPY_FLOAT64);
}
if (PyLong_CheckExact(arg)) {
return (PyObject*)PyArray_DescrFromType(NPY_INT64);
}
if (PyBool_Check(arg)) {
return (PyObject*)PyArray_DescrFromType(NPY_BOOL);
}
PyObject* dtype = NULL;
// String
if (PyUnicode_CheckExact(arg)) {
PyArray_Descr* descr = PyArray_DescrFromType(NPY_UNICODE);
if (descr == NULL) return NULL;
dtype = (PyObject*)PyArray_DescrFromObject(arg, descr);
Py_DECREF(descr);