forked from pandas-dev/pandas
/
algos.pyx
318 lines (246 loc) · 8.83 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
# cython: profile=False
cimport cython
from cython cimport Py_ssize_t
from libc.stdlib cimport malloc, free
from libc.string cimport memmove
from libc.math cimport fabs, sqrt
import numpy as np
cimport numpy as cnp
from numpy cimport (ndarray,
NPY_INT64, NPY_UINT64, NPY_INT32, NPY_INT16, NPY_INT8,
NPY_FLOAT32, NPY_FLOAT64,
NPY_OBJECT,
int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float32_t, float64_t,
double_t)
cnp.import_array()
cimport util
from util cimport numeric, get_nat
import missing
cdef float64_t FP_ERR = 1e-13
cdef double NaN = <double> np.NaN
cdef double nan = NaN
cdef int64_t iNaT = get_nat()
tiebreakers = {
'average': TIEBREAK_AVERAGE,
'min': TIEBREAK_MIN,
'max': TIEBREAK_MAX,
'first': TIEBREAK_FIRST,
'dense': TIEBREAK_DENSE,
}
cdef inline are_diff(object left, object right):
try:
return fabs(left - right) > FP_ERR
except TypeError:
return left != right
class Infinity(object):
""" provide a positive Infinity comparison method for ranking """
__lt__ = lambda self, other: False
__le__ = lambda self, other: isinstance(other, Infinity)
__eq__ = lambda self, other: isinstance(other, Infinity)
__ne__ = lambda self, other: not isinstance(other, Infinity)
__gt__ = lambda self, other: (not isinstance(other, Infinity) and
not missing.checknull(other))
__ge__ = lambda self, other: not missing.checknull(other)
class NegInfinity(object):
""" provide a negative Infinity comparison method for ranking """
__lt__ = lambda self, other: (not isinstance(other, NegInfinity) and
not missing.checknull(other))
__le__ = lambda self, other: not missing.checknull(other)
__eq__ = lambda self, other: isinstance(other, NegInfinity)
__ne__ = lambda self, other: not isinstance(other, NegInfinity)
__gt__ = lambda self, other: False
__ge__ = lambda self, other: isinstance(other, NegInfinity)
@cython.wraparound(False)
@cython.boundscheck(False)
def is_lexsorted(list list_of_arrays):
cdef:
Py_ssize_t i
Py_ssize_t n, nlevels
int64_t k, cur, pre
ndarray arr
bint result = True
nlevels = len(list_of_arrays)
n = len(list_of_arrays[0])
cdef int64_t **vecs = <int64_t**> malloc(nlevels * sizeof(int64_t*))
for i in range(nlevels):
arr = list_of_arrays[i]
assert arr.dtype.name == 'int64'
vecs[i] = <int64_t*> arr.data
# Assume uniqueness??
with nogil:
for i in range(1, n):
for k in range(nlevels):
cur = vecs[k][i]
pre = vecs[k][i -1]
if cur == pre:
continue
elif cur > pre:
break
else:
result = False
break
free(vecs)
return result
@cython.boundscheck(False)
@cython.wraparound(False)
def groupsort_indexer(ndarray[int64_t] index, Py_ssize_t ngroups):
"""
compute a 1-d indexer that is an ordering of the passed index,
ordered by the groups. This is a reverse of the label
factorization process.
Parameters
----------
index: int64 ndarray
mappings from group -> position
ngroups: int64
number of groups
return a tuple of (1-d indexer ordered by groups, group counts)
"""
cdef:
Py_ssize_t i, loc, label, n
ndarray[int64_t] counts, where, result
counts = np.zeros(ngroups + 1, dtype=np.int64)
n = len(index)
result = np.zeros(n, dtype=np.int64)
where = np.zeros(ngroups + 1, dtype=np.int64)
with nogil:
# count group sizes, location 0 for NA
for i in range(n):
counts[index[i] + 1] += 1
# mark the start of each contiguous group of like-indexed data
for i in range(1, ngroups + 1):
where[i] = where[i - 1] + counts[i - 1]
# this is our indexer
for i in range(n):
label = index[i] + 1
result[where[label]] = i
where[label] += 1
return result, counts
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef numeric kth_smallest(numeric[:] a, Py_ssize_t k) nogil:
cdef:
Py_ssize_t i, j, l, m, n = a.shape[0]
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]
# ----------------------------------------------------------------------
# Pairwise correlation/covariance
@cython.boundscheck(False)
@cython.wraparound(False)
def nancorr(ndarray[float64_t, ndim=2] mat, bint cov=0, minp=None):
cdef:
Py_ssize_t i, j, xi, yi, N, K
bint minpv
ndarray[float64_t, ndim=2] result
ndarray[uint8_t, ndim=2] mask
int64_t nobs = 0
float64_t vx, vy, sumx, sumy, sumxx, sumyy, meanx, meany, divisor
N, K = (<object> mat).shape
if minp is None:
minpv = 1
else:
minpv = <int>minp
result = np.empty((K, K), dtype=np.float64)
mask = np.isfinite(mat).view(np.uint8)
with nogil:
for xi in range(K):
for yi in range(xi + 1):
nobs = sumxx = sumyy = sumx = sumy = 0
for i in range(N):
if mask[i, xi] and mask[i, yi]:
vx = mat[i, xi]
vy = mat[i, yi]
nobs += 1
sumx += vx
sumy += vy
if nobs < minpv:
result[xi, yi] = result[yi, xi] = NaN
else:
meanx = sumx / nobs
meany = sumy / nobs
# now the cov numerator
sumx = 0
for i in range(N):
if mask[i, xi] and mask[i, yi]:
vx = mat[i, xi] - meanx
vy = mat[i, yi] - meany
sumx += vx * vy
sumxx += vx * vx
sumyy += vy * vy
divisor = (nobs - 1.0) if cov else sqrt(sumxx * sumyy)
if divisor != 0:
result[xi, yi] = result[yi, xi] = sumx / divisor
else:
result[xi, yi] = result[yi, xi] = NaN
return result
# ----------------------------------------------------------------------
# Pairwise Spearman correlation
@cython.boundscheck(False)
@cython.wraparound(False)
def nancorr_spearman(ndarray[float64_t, ndim=2] mat, Py_ssize_t minp=1):
cdef:
Py_ssize_t i, j, xi, yi, N, K
ndarray[float64_t, ndim=2] result
ndarray[float64_t, ndim=1] maskedx
ndarray[float64_t, ndim=1] maskedy
ndarray[uint8_t, ndim=2] mask
int64_t nobs = 0
float64_t vx, vy, sumx, sumxx, sumyy, mean, divisor
N, K = (<object> mat).shape
result = np.empty((K, K), dtype=np.float64)
mask = np.isfinite(mat).view(np.uint8)
for xi in range(K):
for yi in range(xi + 1):
nobs = 0
for i in range(N):
if mask[i, xi] and mask[i, yi]:
nobs += 1
if nobs < minp:
result[xi, yi] = result[yi, xi] = NaN
else:
maskedx = np.empty(nobs, dtype=np.float64)
maskedy = np.empty(nobs, dtype=np.float64)
j = 0
for i in range(N):
if mask[i, xi] and mask[i, yi]:
maskedx[j] = mat[i, xi]
maskedy[j] = mat[i, yi]
j += 1
maskedx = rank_1d_float64(maskedx)
maskedy = rank_1d_float64(maskedy)
mean = (nobs + 1) / 2.
# now the cov numerator
sumx = sumxx = sumyy = 0
for i in range(nobs):
vx = maskedx[i] - mean
vy = maskedy[i] - mean
sumx += vx * vy
sumxx += vx * vx
sumyy += vy * vy
divisor = sqrt(sumxx * sumyy)
if divisor != 0:
result[xi, yi] = result[yi, xi] = sumx / divisor
else:
result[xi, yi] = result[yi, xi] = NaN
return result
# generated from template
include "algos_common_helper.pxi"
include "algos_rank_helper.pxi"
include "algos_take_helper.pxi"