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
|
import numba as nb
import numpy as np
from .utils import (
aggregate_common_doc,
aliasing,
check_dtype,
check_fill_value,
funcs_no_separate_nan,
get_func,
input_validation,
)
class AggregateOp(object):
"""
Every subclass of AggregateOp handles a different aggregation operation. There are
several private class methods that need to be overwritten by the subclasses
in order to implement different functionality.
On object instantiation, all necessary static methods are compiled together into
two jitted callables, one for scalar arguments, and one for arrays. Calling the
instantiated object picks the right cached callable, does some further preprocessing
and then executes the actual aggregation operation.
"""
forced_fill_value = None
counter_fill_value = 1
counter_dtype = bool
mean_fill_value = None
mean_dtype = np.float64
outer = False
reverse = False
nans = False
def __init__(self, func=None, **kwargs):
if func is None:
func = type(self).__name__.lower()
self.func = func
self.__dict__.update(kwargs)
# Cache the compiled functions, so they don't have to be recompiled on every call
self._jit_scalar = self.callable(self.nans, self.reverse, scalar=True)
self._jit_non_scalar = self.callable(self.nans, self.reverse, scalar=False)
def __call__(
self,
group_idx,
a,
size=None,
fill_value=0,
order="C",
dtype=None,
axis=None,
ddof=0,
):
iv = input_validation(
group_idx,
a,
size=size,
order=order,
axis=axis,
check_bounds=False,
func=self.func,
)
group_idx, a, flat_size, ndim_idx, size, unravel_shape = iv
# TODO: The typecheck should be done by the class itself, not by check_dtype
dtype = check_dtype(dtype, self.func, a, len(group_idx))
check_fill_value(fill_value, dtype, func=self.func)
input_dtype = type(a) if np.isscalar(a) else a.dtype
ret, counter, mean, outer = self._initialize(flat_size, fill_value, dtype, input_dtype, group_idx.size)
group_idx = np.ascontiguousarray(group_idx)
if not np.isscalar(a):
a = np.ascontiguousarray(a)
jitfunc = self._jit_non_scalar
else:
jitfunc = self._jit_scalar
jitfunc(group_idx, a, ret, counter, mean, outer, fill_value, ddof)
self._finalize(ret, counter, fill_value)
if self.outer:
ret = outer
# Deal with ndimensional indexing
if ndim_idx > 1:
if unravel_shape is not None:
# argreductions only
mask = ret == fill_value
ret[mask] = 0
ret = np.unravel_index(ret, unravel_shape)[axis]
ret[mask] = fill_value
ret = ret.reshape(size, order=order)
return ret
@classmethod
def _initialize(cls, flat_size, fill_value, dtype, input_dtype, input_size):
if cls.forced_fill_value is None:
ret = np.full(flat_size, fill_value, dtype=dtype)
else:
ret = np.full(flat_size, cls.forced_fill_value, dtype=dtype)
counter = mean = outer = None
if cls.counter_fill_value is not None:
counter = np.full_like(ret, cls.counter_fill_value, dtype=cls.counter_dtype)
if cls.mean_fill_value is not None:
dtype = cls.mean_dtype if cls.mean_dtype else input_dtype
mean = np.full_like(ret, cls.mean_fill_value, dtype=dtype)
if cls.outer:
outer = np.full(input_size, fill_value, dtype=dtype)
return ret, counter, mean, outer
@classmethod
def _finalize(cls, ret, counter, fill_value):
if cls.forced_fill_value is not None and fill_value != cls.forced_fill_value:
if cls.counter_dtype == bool:
ret[counter] = fill_value
else:
ret[~counter.astype(bool)] = fill_value
@classmethod
def callable(cls, nans=False, reverse=False, scalar=False):
"""Compile a jitted function doing the hard part of the job"""
_valgetter = cls._valgetter_scalar if scalar else cls._valgetter
valgetter = nb.njit(_valgetter)
outersetter = nb.njit(cls._outersetter)
if not nans:
inner = nb.njit(cls._inner)
else:
cls_inner = nb.njit(cls._inner)
cls_nan_check = nb.njit(cls._nan_check)
@nb.njit
def inner(ri, val, ret, counter, mean, fill_value):
if not cls_nan_check(val):
cls_inner(ri, val, ret, counter, mean, fill_value)
@nb.njit
def loop(group_idx, a, ret, counter, mean, outer, fill_value, ddof):
# ddof needs to be present for being exchangeable with loop_2pass
size = len(ret)
rng = range(len(group_idx) - 1, -1, -1) if reverse else range(len(group_idx))
for i in rng:
ri = group_idx[i]
if ri < 0:
raise ValueError("negative indices not supported")
if ri >= size:
raise ValueError("one or more indices in group_idx are too large")
val = valgetter(a, i)
inner(ri, val, ret, counter, mean, fill_value)
outersetter(outer, i, ret[ri])
return loop
@staticmethod
def _valgetter(a, i):
return a[i]
@staticmethod
def _valgetter_scalar(a, i):
return a
@staticmethod
def _nan_check(val):
return val != val
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
raise NotImplementedError("subclasses need to overwrite _inner")
@staticmethod
def _outersetter(outer, i, val):
pass
class Aggregate2pass(AggregateOp):
"""Base class for everything that needs to process the data twice like mean, var and std."""
@classmethod
def callable(cls, nans=False, reverse=False, scalar=False):
# Careful, cls needs to be passed, so that the overwritten methods remain available in
# AggregateOp.callable
loop_1st = super().callable(nans=nans, reverse=reverse, scalar=scalar)
_2pass_inner = nb.njit(cls._2pass_inner)
@nb.njit
def loop_2nd(ret, counter, mean, fill_value, ddof):
for ri in range(len(ret)):
if counter[ri] > ddof:
ret[ri] = _2pass_inner(ri, ret, counter, mean, ddof)
else:
ret[ri] = fill_value
@nb.njit
def loop_2pass(group_idx, a, ret, counter, mean, outer, fill_value, ddof):
loop_1st(group_idx, a, ret, counter, mean, outer, fill_value, ddof)
loop_2nd(ret, counter, mean, fill_value, ddof)
return loop_2pass
@staticmethod
def _2pass_inner(ri, ret, counter, mean, ddof):
raise NotImplementedError("subclasses need to overwrite _2pass_inner")
@classmethod
def _finalize(cls, ret, counter, fill_value):
"""Copying the fill value is already done in the 2nd pass"""
pass
class AggregateNtoN(AggregateOp):
"""Base class for cumulative functions, where the output size matches the input size."""
outer = True
@staticmethod
def _outersetter(outer, i, val):
outer[i] = val
class AggregateGeneric(AggregateOp):
"""Base class for jitting arbitrary functions."""
counter_fill_value = None
def __init__(self, func, **kwargs):
self.func = func
self.__dict__.update(kwargs)
self._jitfunc = self.callable(self.nans)
def __call__(
self,
group_idx,
a,
size=None,
fill_value=0,
order="C",
dtype=None,
axis=None,
ddof=0,
):
iv = input_validation(group_idx, a, size=size, order=order, axis=axis, check_bounds=False)
group_idx, a, flat_size, ndim_idx, size, _ = iv
# TODO: The typecheck should be done by the class itself, not by check_dtype
dtype = check_dtype(dtype, self.func, a, len(group_idx))
check_fill_value(fill_value, dtype, func=self.func)
input_dtype = type(a) if np.isscalar(a) else a.dtype
ret, _, _, _ = self._initialize(flat_size, fill_value, dtype, input_dtype, group_idx.size)
group_idx = np.ascontiguousarray(group_idx)
sortidx = np.argsort(group_idx, kind="mergesort")
self._jitfunc(sortidx, group_idx, a, ret)
# Deal with ndimensional indexing
if ndim_idx > 1:
ret = ret.reshape(size, order=order)
return ret
def callable(self, nans=False):
"""Compile a jitted function and loop it over the sorted data."""
func = nb.njit(self.func)
@nb.njit
def loop(sortidx, group_idx, a, ret):
size = len(ret)
group_idx_srt = group_idx[sortidx]
a_srt = a[sortidx]
indices = step_indices(group_idx_srt)
for i in range(len(indices) - 1):
start_idx, stop_idx = indices[i], indices[i + 1]
ri = group_idx_srt[start_idx]
if ri < 0:
raise ValueError("negative indices not supported")
if ri >= size:
raise ValueError("one or more indices in group_idx are too large")
ret[ri] = func(a_srt[start_idx:stop_idx])
return loop
class Sum(AggregateOp):
forced_fill_value = 0
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] += val
class Prod(AggregateOp):
forced_fill_value = 1
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] *= val
class Len(AggregateOp):
forced_fill_value = 0
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] += 1
class All(AggregateOp):
forced_fill_value = 1
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] &= bool(val)
class Any(AggregateOp):
forced_fill_value = 0
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] |= bool(val)
class Last(AggregateOp):
counter_fill_value = None
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
ret[ri] = val
class First(Last):
reverse = True
class AllNan(AggregateOp):
forced_fill_value = 1
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] &= val != val
class AnyNan(AggregateOp):
forced_fill_value = 0
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] |= val != val
class Max(AggregateOp):
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
if counter[ri]:
ret[ri] = val
counter[ri] = 0
elif ret[ri] < val:
ret[ri] = val
class Min(AggregateOp):
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
if counter[ri]:
ret[ri] = val
counter[ri] = 0
elif ret[ri] > val:
ret[ri] = val
class ArgMax(AggregateOp):
mean_fill_value = np.nan
@staticmethod
def _valgetter(a, i):
return a[i], i
@staticmethod
def _nan_check(val):
return val[0] != val[0]
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
cmp_val, arg = val
if counter[ri]:
# start of a new group
counter[ri] = 0
mean[ri] = cmp_val
if cmp_val == cmp_val:
# Don't point on nans
ret[ri] = arg
elif mean[ri] < cmp_val:
# larger valid value found
mean[ri] = cmp_val
ret[ri] = arg
elif cmp_val != cmp_val:
# nan found, reset group
mean[ri] = cmp_val
ret[ri] = fill_value
class ArgMin(ArgMax):
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
cmp_val, arg = val
if counter[ri]:
# start of a new group
counter[ri] = 0
mean[ri] = cmp_val
if cmp_val == cmp_val:
# Don't point on nans
ret[ri] = arg
elif mean[ri] > cmp_val:
# larger valid value found
mean[ri] = cmp_val
ret[ri] = arg
elif cmp_val != cmp_val:
# nan found, reset group
mean[ri] = cmp_val
ret[ri] = fill_value
class SumOfSquares(AggregateOp):
forced_fill_value = 0
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] = 0
ret[ri] += val * val
class Mean(Aggregate2pass):
forced_fill_value = 0
counter_fill_value = 0
counter_dtype = int
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] += 1
ret[ri] += val
@staticmethod
def _2pass_inner(ri, ret, counter, mean, ddof):
return ret[ri] / counter[ri]
class Std(Mean):
mean_fill_value = 0
@staticmethod
def _inner(ri, val, ret, counter, mean, fill_value):
counter[ri] += 1
mean[ri] += val
ret[ri] += val * val
@staticmethod
def _2pass_inner(ri, ret, counter, mean, ddof):
mean2 = mean[ri] * mean[ri]
return np.sqrt((ret[ri] - mean2 / counter[ri]) / (counter[ri] - ddof))
class Var(Std):
@staticmethod
def _2pass_inner(ri, ret, counter, mean, ddof):
mean2 = mean[ri] * mean[ri]
return (ret[ri] - mean2 / counter[ri]) / (counter[ri] - ddof)
class CumSum(AggregateNtoN, Sum):
pass
class CumProd(AggregateNtoN, Prod):
pass
class CumMax(AggregateNtoN, Max):
pass
class CumMin(AggregateNtoN, Min):
pass
def get_funcs():
funcs = dict()
for op in (
Sum,
Prod,
Len,
All,
Any,
Last,
First,
AllNan,
AnyNan,
Min,
Max,
ArgMin,
ArgMax,
Mean,
Std,
Var,
SumOfSquares,
CumSum,
CumProd,
CumMax,
CumMin,
):
funcname = op.__name__.lower()
funcs[funcname] = op(funcname)
if funcname not in funcs_no_separate_nan:
funcname = "nan" + funcname
funcs[funcname] = op(funcname, nans=True)
return funcs
_impl_dict = get_funcs()
_default_cache = {}
def aggregate(
group_idx, a, func="sum", size=None, fill_value=0, order="C", dtype=None, axis=None, cache=True, **kwargs
):
func = get_func(func, aliasing, _impl_dict)
if not isinstance(func, str):
if cache in (None, False):
# Keep None and False in order to accept empty dictionaries
aggregate_op = AggregateGeneric(func)
else:
if cache is True:
cache = _default_cache
aggregate_op = cache.setdefault(func, AggregateGeneric(func))
return aggregate_op(group_idx, a, size, fill_value, order, dtype, axis, **kwargs)
else:
func = _impl_dict[func]
return func(group_idx, a, size, fill_value, order, dtype, axis, **kwargs)
aggregate.__doc__ = (
"""
This is the numba implementation of aggregate.
"""
+ aggregate_common_doc
)
@nb.njit
def step_count(group_idx):
"""Return the amount of index changes within group_idx."""
cmp_pos = 0
steps = 1
if len(group_idx) < 1:
return 0
for i in range(len(group_idx)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
steps += 1
return steps
@nb.njit
def step_indices(group_idx):
"""Return the edges of areas within group_idx, which are filled with the same value."""
ilen = step_count(group_idx) + 1
indices = np.empty(ilen, np.int64)
indices[0] = 0
indices[-1] = group_idx.size
cmp_pos = 0
ri = 1
for i in range(len(group_idx)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
indices[ri] = i
ri += 1
return indices
|