-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathalgos.pyx
2306 lines (1886 loc) · 63.7 KB
/
algos.pyx
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
from numpy cimport *
cimport numpy as np
import numpy as np
cimport cython
import_array()
cdef float64_t FP_ERR = 1e-13
cimport util
from libc.stdlib cimport malloc, free
from numpy cimport NPY_INT8 as NPY_int8
from numpy cimport NPY_INT16 as NPY_int16
from numpy cimport NPY_INT32 as NPY_int32
from numpy cimport NPY_INT64 as NPY_int64
from numpy cimport NPY_FLOAT16 as NPY_float16
from numpy cimport NPY_FLOAT32 as NPY_float32
from numpy cimport NPY_FLOAT64 as NPY_float64
from numpy cimport (int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float16_t, float32_t, float64_t)
int8 = np.dtype(np.int8)
int16 = np.dtype(np.int16)
int32 = np.dtype(np.int32)
int64 = np.dtype(np.int64)
float16 = np.dtype(np.float16)
float32 = np.dtype(np.float32)
float64 = np.dtype(np.float64)
cdef np.int8_t MINint8 = np.iinfo(np.int8).min
cdef np.int16_t MINint16 = np.iinfo(np.int16).min
cdef np.int32_t MINint32 = np.iinfo(np.int32).min
cdef np.int64_t MINint64 = np.iinfo(np.int64).min
cdef np.float16_t MINfloat16 = np.NINF
cdef np.float32_t MINfloat32 = np.NINF
cdef np.float64_t MINfloat64 = np.NINF
cdef np.int8_t MAXint8 = np.iinfo(np.int8).max
cdef np.int16_t MAXint16 = np.iinfo(np.int16).max
cdef np.int32_t MAXint32 = np.iinfo(np.int32).max
cdef np.int64_t MAXint64 = np.iinfo(np.int64).max
cdef np.float16_t MAXfloat16 = np.inf
cdef np.float32_t MAXfloat32 = np.inf
cdef np.float64_t MAXfloat64 = np.inf
cdef double NaN = <double> np.NaN
cdef double nan = NaN
cdef inline int int_max(int a, int b): return a if a >= b else b
cdef inline int int_min(int a, int b): return a if a <= b else b
cdef extern from "src/headers/math.h":
double sqrt(double x) nogil
double fabs(double) nogil
int signbit(double) nogil
from pandas import lib
include "skiplist.pyx"
cdef:
int TIEBREAK_AVERAGE = 0
int TIEBREAK_MIN = 1
int TIEBREAK_MAX = 2
int TIEBREAK_FIRST = 3
int TIEBREAK_FIRST_DESCENDING = 4
int TIEBREAK_DENSE = 5
tiebreakers = {
'average' : TIEBREAK_AVERAGE,
'min' : TIEBREAK_MIN,
'max' : TIEBREAK_MAX,
'first' : TIEBREAK_FIRST,
'dense' : TIEBREAK_DENSE,
}
# ctypedef fused pvalue_t:
# float64_t
# int64_t
# object
# from cython cimport floating, integral
cdef _take_2d_float64(ndarray[float64_t, ndim=2] values,
object idx):
cdef:
Py_ssize_t i, j, N, K
ndarray[Py_ssize_t, ndim=2, cast=True] indexer = idx
ndarray[float64_t, ndim=2] result
object val
N, K = (<object> values).shape
result = np.empty_like(values)
for i in range(N):
for j in range(K):
result[i, j] = values[i, indexer[i, j]]
return result
cdef _take_2d_int64(ndarray[int64_t, ndim=2] values,
object idx):
cdef:
Py_ssize_t i, j, N, K
ndarray[Py_ssize_t, ndim=2, cast=True] indexer = idx
ndarray[int64_t, ndim=2] result
object val
N, K = (<object> values).shape
result = np.empty_like(values)
for i in range(N):
for j in range(K):
result[i, j] = values[i, indexer[i, j]]
return result
cdef _take_2d_object(ndarray[object, ndim=2] values,
object idx):
cdef:
Py_ssize_t i, j, N, K
ndarray[Py_ssize_t, ndim=2, cast=True] indexer = idx
ndarray[object, ndim=2] result
object val
N, K = (<object> values).shape
result = values.copy()
for i in range(N):
for j in range(K):
result[i, j] = values[i, indexer[i, j]]
return result
def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
cdef:
Py_ssize_t i, j, n, dups = 0, total_tie_count = 0
ndarray[float64_t] sorted_data, ranks, values
ndarray[int64_t] argsorted
float64_t val, nan_value
float64_t sum_ranks = 0
int tiebreak = 0
bint keep_na = 0
float count = 0.0
tiebreak = tiebreakers[ties_method]
values = np.asarray(in_arr).copy()
keep_na = na_option == 'keep'
if ascending ^ (na_option == 'top'):
nan_value = np.inf
else:
nan_value = -np.inf
mask = np.isnan(values)
np.putmask(values, mask, nan_value)
n = len(values)
ranks = np.empty(n, dtype='f8')
# py2.5/win32 hack, can't pass i8
if tiebreak == TIEBREAK_FIRST:
# need to use a stable sort here
_as = values.argsort(kind='mergesort')
if not ascending:
tiebreak = TIEBREAK_FIRST_DESCENDING
else:
_as = values.argsort()
if not ascending:
_as = _as[::-1]
sorted_data = values.take(_as)
argsorted = _as.astype('i8')
for i in range(n):
sum_ranks += i + 1
dups += 1
val = sorted_data[i]
if (val == nan_value) and keep_na:
ranks[argsorted[i]] = nan
continue
count += 1.0
if i == n - 1 or sorted_data[i + 1] != val:
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = sum_ranks / dups
elif tiebreak == TIEBREAK_MIN:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = i - dups + 2
elif tiebreak == TIEBREAK_MAX:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = i + 1
elif tiebreak == TIEBREAK_FIRST:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = j + 1
elif tiebreak == TIEBREAK_FIRST_DESCENDING:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = 2 * i - j - dups + 2
elif tiebreak == TIEBREAK_DENSE:
total_tie_count += 1
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = total_tie_count
sum_ranks = dups = 0
if pct:
return ranks / count
else:
return ranks
def rank_1d_int64(object in_arr, ties_method='average', ascending=True,
na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
cdef:
Py_ssize_t i, j, n, dups = 0, total_tie_count = 0
ndarray[int64_t] sorted_data, values
ndarray[float64_t] ranks
ndarray[int64_t] argsorted
int64_t val
float64_t sum_ranks = 0
int tiebreak = 0
float count = 0.0
tiebreak = tiebreakers[ties_method]
values = np.asarray(in_arr)
n = len(values)
ranks = np.empty(n, dtype='f8')
# py2.5/win32 hack, can't pass i8
if tiebreak == TIEBREAK_FIRST:
# need to use a stable sort here
_as = values.argsort(kind='mergesort')
if not ascending:
tiebreak = TIEBREAK_FIRST_DESCENDING
else:
_as = values.argsort()
if not ascending:
_as = _as[::-1]
sorted_data = values.take(_as)
argsorted = _as.astype('i8')
for i in range(n):
sum_ranks += i + 1
dups += 1
val = sorted_data[i]
count += 1.0
if i == n - 1 or fabs(sorted_data[i + 1] - val) > 0:
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = sum_ranks / dups
elif tiebreak == TIEBREAK_MIN:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = i - dups + 2
elif tiebreak == TIEBREAK_MAX:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = i + 1
elif tiebreak == TIEBREAK_FIRST:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = j + 1
elif tiebreak == TIEBREAK_FIRST_DESCENDING:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = 2 * i - j - dups + 2
elif tiebreak == TIEBREAK_DENSE:
total_tie_count += 1
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = total_tie_count
sum_ranks = dups = 0
if pct:
return ranks / count
else:
return ranks
def rank_2d_float64(object in_arr, axis=0, ties_method='average',
ascending=True, na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
cdef:
Py_ssize_t i, j, z, k, n, dups = 0, total_tie_count = 0
ndarray[float64_t, ndim=2] ranks, values
ndarray[int64_t, ndim=2] argsorted
float64_t val, nan_value
float64_t sum_ranks = 0
int tiebreak = 0
bint keep_na = 0
float count = 0.0
tiebreak = tiebreakers[ties_method]
keep_na = na_option == 'keep'
in_arr = np.asarray(in_arr)
if axis == 0:
values = in_arr.T.copy()
else:
values = in_arr.copy()
if ascending ^ (na_option == 'top'):
nan_value = np.inf
else:
nan_value = -np.inf
np.putmask(values, np.isnan(values), nan_value)
n, k = (<object> values).shape
ranks = np.empty((n, k), dtype='f8')
if tiebreak == TIEBREAK_FIRST:
# need to use a stable sort here
_as = values.argsort(axis=1, kind='mergesort')
if not ascending:
tiebreak = TIEBREAK_FIRST_DESCENDING
else:
_as = values.argsort(1)
if not ascending:
_as = _as[:, ::-1]
values = _take_2d_float64(values, _as)
argsorted = _as.astype('i8')
for i in range(n):
dups = sum_ranks = 0
total_tie_count = 0
count = 0.0
for j in range(k):
sum_ranks += j + 1
dups += 1
val = values[i, j]
if val == nan_value and keep_na:
ranks[i, argsorted[i, j]] = nan
continue
count += 1.0
if j == k - 1 or values[i, j + 1] != val:
if tiebreak == TIEBREAK_AVERAGE:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = sum_ranks / dups
elif tiebreak == TIEBREAK_MIN:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = j - dups + 2
elif tiebreak == TIEBREAK_MAX:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = j + 1
elif tiebreak == TIEBREAK_FIRST:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = z + 1
elif tiebreak == TIEBREAK_FIRST_DESCENDING:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = 2 * j - z - dups + 2
elif tiebreak == TIEBREAK_DENSE:
total_tie_count += 1
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = total_tie_count
sum_ranks = dups = 0
if pct:
ranks[i, :] /= count
if axis == 0:
return ranks.T
else:
return ranks
def rank_2d_int64(object in_arr, axis=0, ties_method='average',
ascending=True, na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
cdef:
Py_ssize_t i, j, z, k, n, dups = 0, total_tie_count = 0
ndarray[float64_t, ndim=2] ranks
ndarray[int64_t, ndim=2] argsorted
ndarray[int64_t, ndim=2, cast=True] values
int64_t val
float64_t sum_ranks = 0
int tiebreak = 0
float count = 0.0
tiebreak = tiebreakers[ties_method]
if axis == 0:
values = np.asarray(in_arr).T
else:
values = np.asarray(in_arr)
n, k = (<object> values).shape
ranks = np.empty((n, k), dtype='f8')
if tiebreak == TIEBREAK_FIRST:
# need to use a stable sort here
_as = values.argsort(axis=1, kind='mergesort')
if not ascending:
tiebreak = TIEBREAK_FIRST_DESCENDING
else:
_as = values.argsort(1)
if not ascending:
_as = _as[:, ::-1]
values = _take_2d_int64(values, _as)
argsorted = _as.astype('i8')
for i in range(n):
dups = sum_ranks = 0
total_tie_count = 0
count = 0.0
for j in range(k):
sum_ranks += j + 1
dups += 1
val = values[i, j]
count += 1.0
if j == k - 1 or fabs(values[i, j + 1] - val) > FP_ERR:
if tiebreak == TIEBREAK_AVERAGE:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = sum_ranks / dups
elif tiebreak == TIEBREAK_MIN:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = j - dups + 2
elif tiebreak == TIEBREAK_MAX:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = j + 1
elif tiebreak == TIEBREAK_FIRST:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = z + 1
elif tiebreak == TIEBREAK_FIRST_DESCENDING:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = 2 * j - z - dups + 2
elif tiebreak == TIEBREAK_DENSE:
total_tie_count += 1
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = total_tie_count
sum_ranks = dups = 0
if pct:
ranks[i, :] /= count
if axis == 0:
return ranks.T
else:
return ranks
def rank_1d_generic(object in_arr, bint retry=1, ties_method='average',
ascending=True, na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
cdef:
Py_ssize_t i, j, n, dups = 0, total_tie_count = 0
ndarray[float64_t] ranks
ndarray sorted_data, values
ndarray[int64_t] argsorted
object val, nan_value
float64_t sum_ranks = 0
int tiebreak = 0
bint keep_na = 0
float count = 0.0
tiebreak = tiebreakers[ties_method]
keep_na = na_option == 'keep'
values = np.array(in_arr, copy=True)
if values.dtype != np.object_:
values = values.astype('O')
if ascending ^ (na_option == 'top'):
# always greater than everything
nan_value = Infinity()
else:
nan_value = NegInfinity()
mask = lib.isnullobj(values)
np.putmask(values, mask, nan_value)
n = len(values)
ranks = np.empty(n, dtype='f8')
# py2.5/win32 hack, can't pass i8
try:
_as = values.argsort()
except TypeError:
if not retry:
raise
valid_locs = (~mask).nonzero()[0]
ranks.put(valid_locs, rank_1d_generic(values.take(valid_locs), 0,
ties_method=ties_method,
ascending=ascending))
np.putmask(ranks, mask, np.nan)
return ranks
if not ascending:
_as = _as[::-1]
sorted_data = values.take(_as)
argsorted = _as.astype('i8')
for i in range(n):
sum_ranks += i + 1
dups += 1
val = util.get_value_at(sorted_data, i)
if val is nan_value and keep_na:
ranks[argsorted[i]] = nan
continue
if (i == n - 1 or
are_diff(util.get_value_at(sorted_data, i + 1), val)):
count += 1.0
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = sum_ranks / dups
elif tiebreak == TIEBREAK_MIN:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = i - dups + 2
elif tiebreak == TIEBREAK_MAX:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = i + 1
elif tiebreak == TIEBREAK_FIRST:
raise ValueError('first not supported for non-numeric data')
elif tiebreak == TIEBREAK_DENSE:
total_tie_count += 1
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = total_tie_count
sum_ranks = dups = 0
if pct:
return ranks / count
else:
return ranks
cdef inline are_diff(object left, object right):
try:
return fabs(left - right) > FP_ERR
except TypeError:
return left != right
_return_false = lambda self, other: False
_return_true = lambda self, other: True
class Infinity(object):
__lt__ = _return_false
__le__ = _return_false
__eq__ = _return_false
__ne__ = _return_true
__gt__ = _return_true
__ge__ = _return_true
__cmp__ = _return_false
class NegInfinity(object):
__lt__ = _return_true
__le__ = _return_true
__eq__ = _return_false
__ne__ = _return_true
__gt__ = _return_false
__ge__ = _return_false
__cmp__ = _return_true
def rank_2d_generic(object in_arr, axis=0, ties_method='average',
ascending=True, na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
cdef:
Py_ssize_t i, j, z, k, n, infs, dups = 0
Py_ssize_t total_tie_count = 0
ndarray[float64_t, ndim=2] ranks
ndarray[object, ndim=2] values
ndarray[int64_t, ndim=2] argsorted
object val, nan_value
float64_t sum_ranks = 0
int tiebreak = 0
bint keep_na = 0
float count = 0.0
tiebreak = tiebreakers[ties_method]
keep_na = na_option == 'keep'
in_arr = np.asarray(in_arr)
if axis == 0:
values = in_arr.T.copy()
else:
values = in_arr.copy()
if values.dtype != np.object_:
values = values.astype('O')
if ascending ^ (na_option == 'top'):
# always greater than everything
nan_value = Infinity()
else:
nan_value = NegInfinity()
mask = lib.isnullobj2d(values)
np.putmask(values, mask, nan_value)
n, k = (<object> values).shape
ranks = np.empty((n, k), dtype='f8')
try:
_as = values.argsort(1)
except TypeError:
values = in_arr
for i in range(len(values)):
ranks[i] = rank_1d_generic(in_arr[i],
ties_method=ties_method,
ascending=ascending,
pct=pct)
if axis == 0:
return ranks.T
else:
return ranks
if not ascending:
_as = _as[:, ::-1]
values = _take_2d_object(values, _as)
argsorted = _as.astype('i8')
for i in range(n):
dups = sum_ranks = infs = 0
total_tie_count = 0
count = 0.0
for j in range(k):
val = values[i, j]
if val is nan_value and keep_na:
ranks[i, argsorted[i, j]] = nan
infs += 1
continue
count += 1.0
sum_ranks += (j - infs) + 1
dups += 1
if j == k - 1 or are_diff(values[i, j + 1], val):
if tiebreak == TIEBREAK_AVERAGE:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = sum_ranks / dups
elif tiebreak == TIEBREAK_MIN:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = j - dups + 2
elif tiebreak == TIEBREAK_MAX:
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = j + 1
elif tiebreak == TIEBREAK_FIRST:
raise ValueError('first not supported for '
'non-numeric data')
elif tiebreak == TIEBREAK_DENSE:
total_tie_count += 1
for z in range(j - dups + 1, j + 1):
ranks[i, argsorted[i, z]] = total_tie_count
sum_ranks = dups = 0
if pct:
ranks[i, :] /= count
if axis == 0:
return ranks.T
else:
return ranks
# def _take_indexer_2d(ndarray[float64_t, ndim=2] values,
# ndarray[Py_ssize_t, ndim=2, cast=True] indexer):
# cdef:
# Py_ssize_t i, j, N, K
# ndarray[float64_t, ndim=2] result
# N, K = (<object> values).shape
# result = np.empty_like(values)
# for i in range(N):
# for j in range(K):
# result[i, j] = values[i, indexer[i, j]]
# return result
# Cython implementations of rolling sum, mean, variance, skewness,
# other statistical moment functions
#
# Misc implementation notes
# -------------------------
#
# - In Cython x * x is faster than x ** 2 for C types, this should be
# periodically revisited to see if it's still true.
#
# -
def _check_minp(win, minp, N, floor=1):
if minp > win:
raise ValueError('min_periods (%d) must be <= window (%d)'
% (minp, win))
elif minp > N:
minp = N + 1
elif minp < 0:
raise ValueError('min_periods must be >= 0')
return max(minp, floor)
# original C implementation by N. Devillard.
# This code in public domain.
# Function : kth_smallest()
# In : array of elements, # of elements in the array, rank k
# Out : one element
# Job : find the kth smallest element in the array
# Reference:
# Author: Wirth, Niklaus
# Title: Algorithms + data structures = programs
# Publisher: Englewood Cliffs: Prentice-Hall, 1976
# Physical description: 366 p.
# Series: Prentice-Hall Series in Automatic Computation
ctypedef fused numeric:
int8_t
int16_t
int32_t
int64_t
uint8_t
uint16_t
uint32_t
uint64_t
float32_t
float64_t
cdef inline Py_ssize_t swap(numeric *a, numeric *b) nogil except -1:
cdef numeric t
# cython doesn't allow pointer dereference so use array syntax
t = a[0]
a[0] = b[0]
b[0] = t
return 0
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef numeric kth_smallest(numeric[:] a, Py_ssize_t k):
cdef:
Py_ssize_t i, j, l, m, n = a.size
numeric x
with nogil:
l = 0
m = n - 1
while l < m:
x = a[k]
i = l
j = m
while 1:
while a[i] < x: i += 1
while x < a[j]: j -= 1
if i <= j:
swap(&a[i], &a[j])
i += 1; j -= 1
if i > j: break
if j < k: l = i
if k < i: m = j
return a[k]
cdef inline kth_smallest_c(float64_t* a, Py_ssize_t k, Py_ssize_t n):
cdef:
Py_ssize_t i,j,l,m
double_t x, t
l = 0
m = n-1
while (l<m):
x = a[k]
i = l
j = m
while 1:
while a[i] < x: i += 1
while x < a[j]: j -= 1
if i <= j:
swap(&a[i], &a[j])
i += 1; j -= 1
if i > j: break
if j < k: l = i
if k < i: m = j
return a[k]
cpdef numeric median(numeric[:] arr):
'''
A faster median
'''
cdef Py_ssize_t n = arr.size
if n == 0:
return np.NaN
arr = arr.copy()
if n % 2:
return kth_smallest(arr, n // 2)
else:
return (kth_smallest(arr, n // 2) +
kth_smallest(arr, n // 2 - 1)) / 2
# -------------- Min, Max subsequence
def max_subseq(ndarray[double_t] arr):
cdef:
Py_ssize_t i=0,s=0,e=0,T,n
double m, S
n = len(arr)
if len(arr) == 0:
return (-1,-1,None)
m = arr[0]
S = m
T = 0
for i in range(1, n):
# S = max { S + A[i], A[i] )
if (S > 0):
S = S + arr[i]
else:
S = arr[i]
T = i
if S > m:
s = T
e = i
m = S
return (s, e, m)
def min_subseq(ndarray[double_t] arr):
cdef:
Py_ssize_t s, e
double m
(s, e, m) = max_subseq(-arr)
return (s, e, -m)
#-------------------------------------------------------------------------------
# Rolling sum
@cython.boundscheck(False)
@cython.wraparound(False)
def roll_sum(ndarray[double_t] input, int win, int minp):
cdef double val, prev, sum_x = 0
cdef int nobs = 0, i
cdef int N = len(input)
cdef ndarray[double_t] output = np.empty(N, dtype=float)
minp = _check_minp(win, minp, N)
with nogil:
for i from 0 <= i < minp - 1:
val = input[i]
# Not NaN
if val == val:
nobs += 1
sum_x += val
output[i] = NaN
for i from minp - 1 <= i < N:
val = input[i]
if val == val:
nobs += 1
sum_x += val
if i > win - 1:
prev = input[i - win]
if prev == prev:
sum_x -= prev
nobs -= 1
if nobs >= minp:
output[i] = sum_x
else:
output[i] = NaN
return output
#-------------------------------------------------------------------------------
# Rolling mean
@cython.boundscheck(False)
@cython.wraparound(False)
def roll_mean(ndarray[double_t] input,
int win, int minp):
cdef:
double val, prev, result, sum_x = 0
Py_ssize_t nobs = 0, i, neg_ct = 0
Py_ssize_t N = len(input)
cdef ndarray[double_t] output = np.empty(N, dtype=float)
minp = _check_minp(win, minp, N)
with nogil:
for i from 0 <= i < minp - 1:
val = input[i]
# Not NaN
if val == val:
nobs += 1
sum_x += val
if signbit(val):
neg_ct += 1
output[i] = NaN
for i from minp - 1 <= i < N:
val = input[i]
if val == val:
nobs += 1
sum_x += val
if signbit(val):
neg_ct += 1
if i > win - 1:
prev = input[i - win]
if prev == prev:
sum_x -= prev
nobs -= 1
if signbit(prev):
neg_ct -= 1
if nobs >= minp:
result = sum_x / nobs
if neg_ct == 0 and result < 0:
# all positive
output[i] = 0
elif neg_ct == nobs and result > 0:
# all negative
output[i] = 0
else:
output[i] = result
else:
output[i] = NaN
return output
#-------------------------------------------------------------------------------
# Exponentially weighted moving average
def ewma(ndarray[double_t] input, double_t com, int adjust, int ignore_na, int minp):
'''
Compute exponentially-weighted moving average using center-of-mass.
Parameters
----------
input : ndarray (float64 type)
com : float64
adjust: int
ignore_na: int
minp: int
Returns
-------
y : ndarray
'''
cdef Py_ssize_t N = len(input)
cdef ndarray[double_t] output = np.empty(N, dtype=float)
if N == 0:
return output
minp = max(minp, 1)
cdef double alpha, old_wt_factor, new_wt, weighted_avg, old_wt, cur
cdef Py_ssize_t i, nobs
alpha = 1. / (1. + com)
old_wt_factor = 1. - alpha
new_wt = 1. if adjust else alpha
weighted_avg = input[0]
is_observation = (weighted_avg == weighted_avg)