-
Notifications
You must be signed in to change notification settings - Fork 18
/
core.py
2620 lines (2231 loc) · 95.6 KB
/
core.py
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 __future__ import annotations
import itertools
import logging
import math
import operator
import sys
import warnings
from collections import namedtuple
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from functools import partial, reduce
from itertools import product
from numbers import Integral
from typing import (
TYPE_CHECKING,
Any,
Callable,
Literal,
TypedDict,
TypeVar,
Union,
overload,
)
import numpy as np
import numpy_groupies as npg
import pandas as pd
import toolz as tlz
from scipy.sparse import csc_array, csr_array
from . import xrdtypes
from .aggregate_flox import _prepare_for_flox
from .aggregations import (
Aggregation,
_atleast_1d,
_initialize_aggregation,
generic_aggregate,
quantile_new_dims_func,
)
from .cache import memoize
from .xrutils import (
is_chunked_array,
is_duck_array,
is_duck_cubed_array,
is_duck_dask_array,
isnull,
module_available,
notnull,
)
if module_available("numpy", minversion="2.0.0"):
from numpy.lib.array_utils import ( # type: ignore[import-not-found]
normalize_axis_tuple,
)
else:
from numpy.core.numeric import normalize_axis_tuple # type: ignore[attr-defined]
HAS_NUMBAGG = module_available("numbagg", minversion="0.3.0")
if TYPE_CHECKING:
try:
if sys.version_info < (3, 11):
from typing_extensions import Unpack
else:
from typing import Unpack
except (ModuleNotFoundError, ImportError):
Unpack: Any # type: ignore[no-redef]
import cubed.Array as CubedArray
import dask.array.Array as DaskArray
from dask.typing import Graph
T_DuckArray = Union[np.ndarray, DaskArray, CubedArray] # Any ?
T_By = T_DuckArray
T_Bys = tuple[T_By, ...]
T_ExpectIndex = pd.Index
T_ExpectIndexTuple = tuple[T_ExpectIndex, ...]
T_ExpectIndexOpt = Union[T_ExpectIndex, None]
T_ExpectIndexOptTuple = tuple[T_ExpectIndexOpt, ...]
T_Expect = Union[Sequence, np.ndarray, T_ExpectIndex]
T_ExpectTuple = tuple[T_Expect, ...]
T_ExpectOpt = Union[Sequence, np.ndarray, T_ExpectIndexOpt]
T_ExpectOptTuple = tuple[T_ExpectOpt, ...]
T_ExpectedGroups = Union[T_Expect, T_ExpectOptTuple]
T_ExpectedGroupsOpt = Union[T_ExpectedGroups, None]
T_Func = Union[str, Callable]
T_Funcs = Union[T_Func, Sequence[T_Func]]
T_Agg = Union[str, Aggregation]
T_Axis = int
T_Axes = tuple[T_Axis, ...]
T_AxesOpt = Union[T_Axis, T_Axes, None]
T_Dtypes = Union[np.typing.DTypeLike, Sequence[np.typing.DTypeLike], None]
T_FillValues = Union[np.typing.ArrayLike, Sequence[np.typing.ArrayLike], None]
T_Engine = Literal["flox", "numpy", "numba", "numbagg"]
T_EngineOpt = None | T_Engine
T_Method = Literal["map-reduce", "blockwise", "cohorts"]
T_MethodOpt = None | Literal["map-reduce", "blockwise", "cohorts"]
T_IsBins = Union[bool | Sequence[bool]]
T = TypeVar("T")
IntermediateDict = dict[Union[str, Callable], Any]
FinalResultsDict = dict[str, Union["DaskArray", "CubedArray", np.ndarray]]
FactorProps = namedtuple("FactorProps", "offset_group nan_sentinel nanmask")
# This dummy axis is inserted using np.expand_dims
# and then reduced over during the combine stage by
# _simple_combine.
DUMMY_AXIS = -2
logger = logging.getLogger("flox")
class FactorizeKwargs(TypedDict, total=False):
"""Used in _factorize_multiple"""
by: T_Bys
axes: T_Axes
fastpath: bool
expected_groups: T_ExpectIndexOptTuple | None
reindex: bool
sort: bool
def _postprocess_numbagg(result, *, func, fill_value, size, seen_groups):
"""Account for numbagg not providing a fill_value kwarg."""
from .aggregate_numbagg import DEFAULT_FILL_VALUE
if not isinstance(func, str) or func not in DEFAULT_FILL_VALUE:
return result
# The condition needs to be
# len(found_groups) < size; if so we mask with fill_value (?)
default_fv = DEFAULT_FILL_VALUE[func]
needs_masking = fill_value is not None and not np.array_equal(
fill_value, default_fv, equal_nan=True
)
groups = np.arange(size)
if needs_masking:
mask = np.isin(groups, seen_groups, assume_unique=True, invert=True)
if mask.any():
result[..., groups[mask]] = fill_value
return result
def identity(x: T) -> T:
return x
def _issorted(arr: np.ndarray) -> bool:
return bool((arr[:-1] <= arr[1:]).all())
def _is_arg_reduction(func: T_Agg) -> bool:
if isinstance(func, str) and func in ["argmin", "argmax", "nanargmax", "nanargmin"]:
return True
if isinstance(func, Aggregation) and func.reduction_type == "argreduce":
return True
return False
def _is_minmax_reduction(func: T_Agg) -> bool:
return not _is_arg_reduction(func) and (
isinstance(func, str) and ("max" in func or "min" in func)
)
def _is_first_last_reduction(func: T_Agg) -> bool:
return isinstance(func, str) and func in ["nanfirst", "nanlast", "first", "last"]
def _get_expected_groups(by: T_By, sort: bool) -> T_ExpectIndex:
if is_duck_dask_array(by):
raise ValueError("Please provide expected_groups if not grouping by a numpy array.")
flatby = by.reshape(-1)
expected = pd.unique(flatby[notnull(flatby)])
return _convert_expected_groups_to_index((expected,), isbin=(False,), sort=sort)[0]
def _get_chunk_reduction(reduction_type: Literal["reduce", "argreduce"]) -> Callable:
if reduction_type == "reduce":
return chunk_reduce
elif reduction_type == "argreduce":
return chunk_argreduce
else:
raise ValueError(f"Unknown reduction type: {reduction_type}")
def is_nanlen(reduction: T_Func) -> bool:
return isinstance(reduction, str) and reduction == "nanlen"
def _move_reduce_dims_to_end(arr: np.ndarray, axis: T_Axes) -> np.ndarray:
"""Transpose `arr` by moving `axis` to the end."""
axis = tuple(axis)
order = tuple(ax for ax in np.arange(arr.ndim) if ax not in axis) + axis
arr = arr.transpose(order)
return arr
def _collapse_axis(arr: np.ndarray, naxis: int) -> np.ndarray:
"""Reshape so that the last `naxis` axes are collapsed to one axis."""
newshape = arr.shape[:-naxis] + (math.prod(arr.shape[-naxis:]),)
return arr.reshape(newshape)
@memoize
def _get_optimal_chunks_for_groups(chunks, labels):
chunkidx = np.cumsum(chunks) - 1
# what are the groups at chunk boundaries
labels_at_chunk_bounds = _unique(labels[chunkidx])
# what's the last index of all groups
last_indexes = npg.aggregate_numpy.aggregate(labels, np.arange(len(labels)), func="last")
# what's the last index of groups at the chunk boundaries.
lastidx = last_indexes[labels_at_chunk_bounds]
if len(chunkidx) == len(lastidx) and (chunkidx == lastidx).all():
return chunks
first_indexes = npg.aggregate_numpy.aggregate(labels, np.arange(len(labels)), func="first")
firstidx = first_indexes[labels_at_chunk_bounds]
newchunkidx = [0]
for c, f, l in zip(chunkidx, firstidx, lastidx): # noqa
Δf = abs(c - f)
Δl = abs(c - l)
if c == 0 or newchunkidx[-1] > l:
continue
if Δf < Δl and f > newchunkidx[-1]:
newchunkidx.append(f)
else:
newchunkidx.append(l + 1)
if newchunkidx[-1] != chunkidx[-1] + 1:
newchunkidx.append(chunkidx[-1] + 1)
newchunks = np.diff(newchunkidx)
assert sum(newchunks) == sum(chunks)
return tuple(newchunks)
def _unique(a: np.ndarray) -> np.ndarray:
"""Much faster to use pandas unique and sort the results.
np.unique sorts before uniquifying and is slow."""
return np.sort(pd.unique(a.reshape(-1)))
def slices_from_chunks(chunks):
"""slightly modified from dask.array.core.slices_from_chunks to be lazy"""
cumdims = [tlz.accumulate(operator.add, bds, 0) for bds in chunks]
slices = (
(slice(s, s + dim) for s, dim in zip(starts, shapes))
for starts, shapes in zip(cumdims, chunks)
)
return product(*slices)
def _compute_label_chunk_bitmask(labels, chunks, nlabels):
def make_bitmask(rows, cols):
data = np.broadcast_to(np.array(1, dtype=np.uint8), rows.shape)
return csc_array((data, (rows, cols)), dtype=bool, shape=(nchunks, nlabels))
assert isinstance(labels, np.ndarray)
shape = tuple(sum(c) for c in chunks)
nchunks = math.prod(len(c) for c in chunks)
approx_chunk_size = math.prod(c[0] for c in chunks)
# Shortcut for 1D with size-1 chunks
if shape == (nchunks,):
rows_array = np.arange(nchunks)
cols_array = labels
mask = labels >= 0
return make_bitmask(rows_array[mask], cols_array[mask])
labels = np.broadcast_to(labels, shape[-labels.ndim :])
cols = []
ilabels = np.arange(nlabels)
def chunk_unique(labels, slicer, nlabels, label_is_present=None):
if label_is_present is None:
label_is_present = np.empty((nlabels + 1,), dtype=bool)
label_is_present[:] = False
subset = labels[slicer]
# This is a quite fast way to find unique integers, when we know how many there are
# inspired by a similar idea in numpy_groupies for first, last
# instead of explicitly finding uniques, repeatedly write True to the same location
label_is_present[subset.reshape(-1)] = True
# skip the -1 sentinel by slicing
# Faster than np.argwhere by a lot
uniques = ilabels[label_is_present[:-1]]
return uniques
# TODO: refine this heuristic.
# The general idea is that with the threadpool, we repeatedly allocate memory
# for `label_is_present`. We trade that off against the parallelism across number of chunks.
# For large enough number of chunks (relative to number of labels), it makes sense to
# suffer the extra allocation in exchange for parallelism.
THRESHOLD = 2
if nlabels < THRESHOLD * approx_chunk_size:
logger.debug(
"Using threadpool since num_labels %s < %d * chunksize %s",
nlabels,
THRESHOLD,
approx_chunk_size,
)
with ThreadPoolExecutor() as executor:
futures = [
executor.submit(chunk_unique, labels, slicer, nlabels)
for slicer in slices_from_chunks(chunks)
]
cols = tuple(f.result() for f in futures)
else:
logger.debug(
"Using serial loop since num_labels %s > %d * chunksize %s",
nlabels,
THRESHOLD,
approx_chunk_size,
)
cols = []
# Add one to handle the -1 sentinel value
label_is_present = np.empty((nlabels + 1,), dtype=bool)
for region in slices_from_chunks(chunks):
uniques = chunk_unique(labels, region, nlabels, label_is_present)
cols.append(uniques)
rows_array = np.repeat(np.arange(nchunks), tuple(len(col) for col in cols))
cols_array = np.concatenate(cols)
return make_bitmask(rows_array, cols_array)
# @memoize
def find_group_cohorts(
labels, chunks, expected_groups: None | pd.RangeIndex = None, merge: bool = False
) -> tuple[T_Method, dict]:
"""
Finds groups labels that occur together aka "cohorts"
If available, results are cached in a 1MB cache managed by `cachey`.
This allows us to be quick when repeatedly calling groupby_reduce
for arrays with the same chunking (e.g. an xarray Dataset).
Parameters
----------
labels : np.ndarray
mD Array of integer group codes, factorized so that -1
represents NaNs.
chunks : tuple
chunks of the array being reduced
expected_groups: pd.RangeIndex (optional)
Used to extract the largest label expected
merge: bool (optional)
Whether to merge cohorts or not. Set to True if a user
specifies "cohorts" but other methods are preferable.
Returns
-------
preferred_method: {"blockwise", cohorts", "map-reduce"}
cohorts: dict_values
Iterable of cohorts
"""
# To do this, we must have values in memory so casting to numpy should be safe
labels = np.asarray(labels)
shape = tuple(sum(c) for c in chunks)
nchunks = math.prod(len(c) for c in chunks)
# assumes that `labels` are factorized
if expected_groups is None:
nlabels = labels.max() + 1
else:
nlabels = expected_groups[-1] + 1
# 1. Single chunk, blockwise always
if nchunks == 1:
return "blockwise", {(0,): list(range(nlabels))}
labels = np.broadcast_to(labels, shape[-labels.ndim :])
bitmask = _compute_label_chunk_bitmask(labels, chunks, nlabels)
CHUNK_AXIS, LABEL_AXIS = 0, 1
chunks_per_label = bitmask.sum(axis=CHUNK_AXIS)
# can happen when `expected_groups` is passed but not all labels are present
# (binning, resampling)
present_labels = np.arange(bitmask.shape[LABEL_AXIS])
present_labels_mask = chunks_per_label != 0
if not present_labels_mask.all():
present_labels = present_labels[present_labels_mask]
bitmask = bitmask[..., present_labels_mask]
chunks_per_label = chunks_per_label[present_labels_mask]
label_chunks = {
present_labels[idx]: bitmask.indices[slice(bitmask.indptr[idx], bitmask.indptr[idx + 1])]
for idx in range(bitmask.shape[LABEL_AXIS])
}
# Invert the label_chunks mapping so we know which labels occur together.
def invert(x) -> tuple[np.ndarray, ...]:
arr = label_chunks[x]
return tuple(arr)
chunks_cohorts = tlz.groupby(invert, label_chunks.keys())
# 2. Every group is contained to one block, use blockwise here.
if bitmask.shape[CHUNK_AXIS] == 1 or (chunks_per_label == 1).all():
logger.debug("find_group_cohorts: blockwise is preferred.")
return "blockwise", chunks_cohorts
# 3. Perfectly chunked so there is only a single cohort
if len(chunks_cohorts) == 1:
logger.debug("Only found a single cohort. 'map-reduce' is preferred.")
return "map-reduce", chunks_cohorts if merge else {}
# 4. Our dataset has chunksize one along the axis,
single_chunks = all(all(a == 1 for a in ac) for ac in chunks)
# 5. Every chunk only has a single group, but that group might extend across multiple chunks
one_group_per_chunk = (bitmask.sum(axis=LABEL_AXIS) == 1).all()
# 6. Existing cohorts don't overlap, great for time grouping with perfect chunking
no_overlapping_cohorts = (np.bincount(np.concatenate(tuple(chunks_cohorts.keys()))) == 1).all()
if one_group_per_chunk or single_chunks or no_overlapping_cohorts:
logger.debug("find_group_cohorts: cohorts is preferred, chunking is perfect.")
return "cohorts", chunks_cohorts
# We'll use containment to measure degree of overlap between labels.
# Containment C = |Q & S| / |Q|
# - |X| is the cardinality of set X
# - Q is the query set being tested
# - S is the existing set
# The bitmask matrix S allows us to calculate this pretty efficiently using a dot product.
# S.T @ S / chunks_per_label
#
# We treat the sparsity(C) = (nnz/size) as a summary measure of the net overlap.
# 1. For high enough sparsity, there is a lot of overlap and we should use "map-reduce".
# 2. When labels are uniformly distributed amongst all chunks
# (and number of labels < chunk size), sparsity is 1.
# 3. Time grouping cohorts (e.g. dayofyear) appear as lines in this matrix.
# 4. When there are no overlaps at all between labels, containment is a block diagonal matrix
# (approximately).
#
# However computing S.T @ S can still be the slowest step, especially if S
# is not particularly sparse. Empirically the sparsity( S.T @ S ) > min(1, 2 x sparsity(S)).
# So we use sparsity(S) as a shortcut.
MAX_SPARSITY_FOR_COHORTS = 0.4 # arbitrary
sparsity = bitmask.nnz / math.prod(bitmask.shape)
preferred_method: Literal["map-reduce"] | Literal["cohorts"]
logger.debug(
"sparsity of bitmask is {}, threshold is {}".format( # noqa
sparsity, MAX_SPARSITY_FOR_COHORTS
)
)
# 7. Groups seem fairly randomly distributed, use "map-reduce".
if sparsity > MAX_SPARSITY_FOR_COHORTS:
if not merge:
logger.debug(
"find_group_cohorts: bitmask sparsity={}, merge=False, choosing 'map-reduce'".format( # noqa
sparsity
)
)
return "map-reduce", {}
preferred_method = "map-reduce"
else:
preferred_method = "cohorts"
# Note: While A.T @ A is a symmetric matrix, the division by chunks_per_label
# makes it non-symmetric.
asfloat = bitmask.astype(float)
containment = csr_array(asfloat.T @ asfloat / chunks_per_label)
logger.debug(
"sparsity of containment matrix is {}".format( # noqa
containment.nnz / math.prod(containment.shape)
)
)
# Use a threshold to force some merging. We do not use the filtered
# containment matrix for estimating "sparsity" because it is a bit
# hard to reason about.
MIN_CONTAINMENT = 0.75 # arbitrary
mask = containment.data < MIN_CONTAINMENT
containment.data[mask] = 0
containment.eliminate_zeros()
# Iterate over labels, beginning with those with most chunks
logger.debug("find_group_cohorts: merging cohorts")
order = np.argsort(containment.sum(axis=LABEL_AXIS))[::-1]
merged_cohorts = {}
merged_keys = set()
# TODO: we can optimize this to loop over chunk_cohorts instead
# by zeroing out rows that are already in a cohort
for rowidx in order:
cohidx = containment.indices[
slice(containment.indptr[rowidx], containment.indptr[rowidx + 1])
]
cohort_ = present_labels[cohidx]
cohort = [elem for elem in cohort_ if elem not in merged_keys]
if not cohort:
continue
merged_keys.update(cohort)
allchunks = (label_chunks[member] for member in cohort)
chunk = tuple(set(itertools.chain(*allchunks)))
merged_cohorts[chunk] = cohort
actual_ngroups = np.concatenate(tuple(merged_cohorts.values())).size
expected_ngroups = present_labels.size
assert expected_ngroups == actual_ngroups, (expected_ngroups, actual_ngroups)
# sort by first label in cohort
# This will help when sort=True (default)
# and we have to resort the dask array
as_sorted = dict(sorted(merged_cohorts.items(), key=lambda kv: kv[1][0]))
return preferred_method, as_sorted
def rechunk_for_cohorts(
array: DaskArray,
axis: T_Axis,
labels: np.ndarray,
force_new_chunk_at: Sequence,
chunksize: int | None = None,
ignore_old_chunks: bool = False,
debug: bool = False,
) -> DaskArray:
"""
Rechunks array so that each new chunk contains groups that always occur together.
Parameters
----------
array : dask.array.Array
array to rechunk
axis : int
Axis to rechunk
labels : np.array
1D Group labels to align chunks with. This routine works
well when ``labels`` has repeating patterns: e.g.
``1, 2, 3, 1, 2, 3, 4, 1, 2, 3`` though there is no requirement
that the pattern must contain sequences.
force_new_chunk_at : Sequence
Labels at which we always start a new chunk. For
the example ``labels`` array, this would be `1`.
chunksize : int, optional
nominal chunk size. Chunk size is exceeded when the label
in ``force_new_chunk_at`` is less than ``chunksize//2`` elements away.
If None, uses median chunksize along axis.
Returns
-------
dask.array.Array
rechunked array
"""
if chunksize is None:
chunksize = np.median(array.chunks[axis]).astype(int)
if len(labels) != array.shape[axis]:
raise ValueError(
"labels must be equal to array.shape[axis]. "
f"Received length {len(labels)}. Expected length {array.shape[axis]}"
)
force_new_chunk_at = _atleast_1d(force_new_chunk_at)
oldchunks = array.chunks[axis]
oldbreaks = np.insert(np.cumsum(oldchunks), 0, 0)
if debug:
labels_at_breaks = labels[oldbreaks[:-1]]
print(labels_at_breaks[:40])
isbreak = np.isin(labels, force_new_chunk_at)
if not np.any(isbreak):
raise ValueError("One or more labels in ``force_new_chunk_at`` not present in ``labels``.")
divisions = []
counter = 1
for idx, lab in enumerate(labels):
if lab in force_new_chunk_at or idx == 0:
divisions.append(idx)
counter = 1
continue
next_break = np.nonzero(isbreak[idx:])[0]
if next_break.any():
next_break_is_close = next_break[0] <= chunksize // 2
else:
next_break_is_close = False
if (not ignore_old_chunks and idx in oldbreaks) or (
counter >= chunksize and not next_break_is_close
):
divisions.append(idx)
counter = 1
continue
counter += 1
divisions.append(len(labels))
if debug:
labels_at_breaks = labels[divisions[:-1]]
print(labels_at_breaks[:40])
newchunks = tuple(np.diff(divisions))
if debug:
print(divisions[:10], newchunks[:10])
print(divisions[-10:], newchunks[-10:])
assert sum(newchunks) == len(labels)
if newchunks == array.chunks[axis]:
return array
else:
return array.rechunk({axis: newchunks})
def rechunk_for_blockwise(array: DaskArray, axis: T_Axis, labels: np.ndarray) -> DaskArray:
"""
Rechunks array so that group boundaries line up with chunk boundaries, allowing
embarrassingly parallel group reductions.
This only works when the groups are sequential
(e.g. labels = ``[0,0,0,1,1,1,1,2,2]``).
Such patterns occur when using ``.resample``.
Parameters
----------
array : DaskArray
Array to rechunk
axis : int
Axis along which to rechunk the array.
labels : np.ndarray
Group labels
Returns
-------
DaskArray
Rechunked array
"""
labels = factorize_((labels,), axes=())[0]
chunks = array.chunks[axis]
newchunks = _get_optimal_chunks_for_groups(chunks, labels)
if newchunks == chunks:
return array
else:
return array.rechunk({axis: newchunks})
def reindex_(
array: np.ndarray,
from_,
to,
fill_value: Any = None,
axis: T_Axis = -1,
promote: bool = False,
) -> np.ndarray:
if not isinstance(to, pd.Index):
if promote:
to = pd.Index(to)
else:
raise ValueError("reindex requires a pandas.Index or promote=True")
if to.ndim > 1:
raise ValueError(f"Cannot reindex to a multidimensional array: {to}")
if array.shape[axis] == 0:
# all groups were NaN
reindexed = np.full(array.shape[:-1] + (len(to),), fill_value, dtype=array.dtype)
return reindexed
from_ = pd.Index(from_)
# short-circuit for trivial case
if from_.equals(to):
return array
if from_.dtype.kind == "O" and isinstance(from_[0], tuple):
raise NotImplementedError(
"Currently does not support reindexing with object arrays of tuples. "
"These occur when grouping by multi-indexed variables in xarray."
)
idx = from_.get_indexer(to)
indexer = [slice(None, None)] * array.ndim
indexer[axis] = idx
reindexed = array[tuple(indexer)]
if any(idx == -1):
if fill_value is None:
raise ValueError("Filling is required. fill_value cannot be None.")
indexer[axis] = idx == -1
# This allows us to match xarray's type promotion rules
if fill_value is xrdtypes.NA or isnull(fill_value):
new_dtype, fill_value = xrdtypes.maybe_promote(reindexed.dtype)
reindexed = reindexed.astype(new_dtype, copy=False)
reindexed[tuple(indexer)] = fill_value
return reindexed
def offset_labels(labels: np.ndarray, ngroups: int) -> tuple[np.ndarray, int]:
"""
Offset group labels by dimension. This is used when we
reduce over a subset of the dimensions of by. It assumes that the reductions
dimensions have been flattened in the last dimension
Copied from xhistogram &
https://stackoverflow.com/questions/46256279/bin-elements-per-row-vectorized-2d-bincount-for-numpy
"""
assert labels.ndim > 1
offset: np.ndarray = (
labels + np.arange(math.prod(labels.shape[:-1])).reshape((*labels.shape[:-1], -1)) * ngroups
)
# -1 indicates NaNs. preserve these otherwise we aggregate in the wrong groups!
offset[labels == -1] = -1
size: int = math.prod(labels.shape[:-1]) * ngroups
return offset, size
@overload
def factorize_(
by: T_Bys,
axes: T_Axes,
*,
fastpath: Literal[True],
expected_groups: T_ExpectIndexOptTuple | None = None,
reindex: bool = False,
sort: bool = True,
) -> tuple[np.ndarray, tuple[np.ndarray, ...], tuple[int, ...], int, int, None]: ...
@overload
def factorize_(
by: T_Bys,
axes: T_Axes,
*,
expected_groups: T_ExpectIndexOptTuple | None = None,
reindex: bool = False,
sort: bool = True,
fastpath: Literal[False] = False,
) -> tuple[np.ndarray, tuple[np.ndarray, ...], tuple[int, ...], int, int, FactorProps]: ...
@overload
def factorize_(
by: T_Bys,
axes: T_Axes,
*,
expected_groups: T_ExpectIndexOptTuple | None = None,
reindex: bool = False,
sort: bool = True,
fastpath: bool = False,
) -> tuple[np.ndarray, tuple[np.ndarray, ...], tuple[int, ...], int, int, FactorProps | None]: ...
def factorize_(
by: T_Bys,
axes: T_Axes,
*,
expected_groups: T_ExpectIndexOptTuple | None = None,
reindex: bool = False,
sort: bool = True,
fastpath: bool = False,
) -> tuple[np.ndarray, tuple[np.ndarray, ...], tuple[int, ...], int, int, FactorProps | None]:
"""
Returns an array of integer codes for groups (and associated data)
by wrapping pd.cut and pd.factorize (depending on isbin).
This method handles reindex and sort so that we don't spend time reindexing / sorting
a possibly large results array. Instead we set up the appropriate integer codes (group_idx)
so that the results come out in the appropriate order.
"""
if expected_groups is None:
expected_groups = (None,) * len(by)
factorized = []
found_groups = []
for groupvar, expect in zip(by, expected_groups):
flat = groupvar.reshape(-1)
if isinstance(expect, pd.RangeIndex):
# idx is a view of the original `by` array
# copy here so we don't have a race condition with the
# group_idx[nanmask] = nan_sentinel assignment later
# this is important in shared-memory parallelism with dask
# TODO: figure out how to avoid this
idx = flat.copy()
found_groups.append(np.array(expect))
# TODO: fix by using masked integers
idx[idx > expect[-1]] = -1
elif isinstance(expect, pd.IntervalIndex):
if expect.closed == "both":
raise NotImplementedError
bins = np.concatenate([expect.left.to_numpy(), expect.right.to_numpy()[[-1]]])
# digitize is 0 or idx.max() for values outside the bounds of all intervals
# make it behave like pd.cut which uses -1:
if len(bins) > 1:
right = expect.closed_right
idx = np.digitize(
flat,
bins=bins.view(np.int64) if bins.dtype.kind == "M" else bins,
right=right,
)
idx -= 1
within_bins = flat <= bins.max() if right else flat < bins.max()
idx[~within_bins] = -1
else:
idx = np.zeros_like(flat, dtype=np.intp) - 1
found_groups.append(np.array(expect))
else:
if expect is not None and reindex:
sorter = np.argsort(expect)
groups = expect[(sorter,)] if sort else expect
idx = np.searchsorted(expect, flat, sorter=sorter)
mask = ~np.isin(flat, expect) | isnull(flat) | (idx == len(expect))
if not sort:
# idx is the index in to the sorted array.
# if we didn't want sorting, unsort it back
idx[(idx == len(expect),)] = -1
idx = sorter[(idx,)]
idx[mask] = -1
else:
idx, groups = pd.factorize(flat, sort=sort) # type: ignore[arg-type]
found_groups.append(np.array(groups))
factorized.append(idx.reshape(groupvar.shape))
grp_shape = tuple(len(grp) for grp in found_groups)
ngroups = math.prod(grp_shape)
if len(by) > 1:
group_idx = np.ravel_multi_index(factorized, grp_shape, mode="wrap")
# NaNs; as well as values outside the bins are coded by -1
# Restore these after the raveling
nan_by_mask = reduce(np.logical_or, [(f == -1) for f in factorized])
group_idx[nan_by_mask] = -1
else:
group_idx = factorized[0]
if fastpath:
return group_idx, tuple(found_groups), grp_shape, ngroups, ngroups, None
if len(axes) == 1 and groupvar.ndim > 1:
# Not reducing along all dimensions of by
# this is OK because for 3D by and axis=(1,2),
# we collapse to a 2D by and axis=-1
offset_group = True
group_idx, size = offset_labels(group_idx.reshape(by[0].shape), ngroups)
else:
size = ngroups
offset_group = False
# numpy_groupies cannot deal with group_idx = -1
# so we'll add use ngroups as the sentinel
# note we cannot simply remove the NaN locations;
# that would mess up argmax, argmin
nan_sentinel = size if offset_group else ngroups
nanmask = group_idx == -1
if nanmask.any():
# bump it up so there's a place to assign values to the nan_sentinel index
size += 1
group_idx[nanmask] = nan_sentinel
props = FactorProps(offset_group, nan_sentinel, nanmask)
return group_idx, tuple(found_groups), grp_shape, ngroups, size, props
def chunk_argreduce(
array_plus_idx: tuple[np.ndarray, ...],
by: np.ndarray,
func: T_Funcs,
expected_groups: pd.Index | None,
axis: T_AxesOpt,
fill_value: T_FillValues,
dtype: T_Dtypes = None,
reindex: bool = False,
engine: T_Engine = "numpy",
sort: bool = True,
user_dtype=None,
) -> IntermediateDict:
"""
Per-chunk arg reduction.
Expects a tuple of (array, index along reduction axis). Inspired by
dask.array.reductions.argtopk
"""
array, idx = array_plus_idx
by = np.broadcast_to(by, array.shape)
results = chunk_reduce(
array,
by,
func,
expected_groups=None,
axis=axis,
fill_value=fill_value,
dtype=dtype,
engine=engine,
sort=sort,
user_dtype=user_dtype,
)
if not isnull(results["groups"]).all():
idx = np.broadcast_to(idx, array.shape)
# array, by get flattened to 1D before passing to npg
# so the indexes need to be unraveled
newidx = np.unravel_index(results["intermediates"][1], array.shape)
# Now index into the actual "global" indexes `idx`
results["intermediates"][1] = idx[newidx]
if reindex and expected_groups is not None:
results["intermediates"][1] = reindex_(
results["intermediates"][1], results["groups"].squeeze(), expected_groups, fill_value=0
)
assert results["intermediates"][0].shape == results["intermediates"][1].shape
return results
def chunk_reduce(
array: np.ndarray,
by: np.ndarray,
func: T_Funcs,
expected_groups: pd.Index | None,
axis: T_AxesOpt = None,
fill_value: T_FillValues = None,
dtype: T_Dtypes = None,
reindex: bool = False,
engine: T_Engine = "numpy",
kwargs: Sequence[dict] | None = None,
sort: bool = True,
user_dtype=None,
) -> IntermediateDict:
"""
Wrapper for numpy_groupies aggregate that supports nD ``array`` and
mD ``by``.
Core groupby reduction using numpy_groupies. Uses ``pandas.factorize`` to factorize
``by``. Offsets the groups if not reducing along all dimensions of ``by``.
Always ravels ``by`` to 1D, flattens appropriate dimensions of array.
When dask arrays are passed to groupby_reduce, this function is called on every
block.
Parameters
----------
array : numpy.ndarray
Array of values to reduced
by : numpy.ndarray
Array to group by.
func : str or Callable or Sequence[str] or Sequence[Callable]
Name of reduction or function, passed to numpy_groupies.
Supports multiple reductions.
axis : (optional) int or Sequence[int]
If None, reduce along all dimensions of array.
Else reduce along specified axes.
Returns
-------
dict
"""
funcs = _atleast_1d(func)
nfuncs = len(funcs)
dtypes = _atleast_1d(dtype, nfuncs)
fill_values = _atleast_1d(fill_value, nfuncs)
kwargss = _atleast_1d({}, nfuncs) if kwargs is None else kwargs
if isinstance(axis, Sequence):
axes: T_Axes = axis
nax = len(axes)
else:
nax = by.ndim
if axis is None:
axes = ()
else:
axes = (axis,) * nax
assert by.ndim <= array.ndim
final_array_shape = array.shape[:-nax] + (1,) * (nax - 1)
final_groups_shape = (1,) * (nax - 1)
if 1 < nax < by.ndim:
# when axis is a tuple
# collapse and move reduction dimensions to the end
by = _collapse_axis(by, nax)
array = _collapse_axis(array, nax)
axes = (-1,)
nax = 1
# if indices=[2,2,2], npg assumes groups are (0, 1, 2);
# and will return a result that is bigger than necessary
# avoid by factorizing again so indices=[2,2,2] is changed to
# indices=[0,0,0]. This is necessary when combining block results
# factorize can handle strings etc unlike digitize
group_idx, grps, found_groups_shape, _, size, props = factorize_(
(by,), axes, expected_groups=(expected_groups,), reindex=reindex, sort=sort
)
(groups,) = grps
# do this *before* possible broadcasting below.
# factorize_ has already taken care of offsetting
if engine == "numbagg":
seen_groups = _unique(group_idx)
order = "C"
if nax > 1:
needs_broadcast = any(
group_idx.shape[ax] != array.shape[ax] and group_idx.shape[ax] == 1
for ax in range(-nax, 0)