@@ -620,7 +620,10 @@ def gradient(f, *varargs, **kwargs):
620620 return results
621621
622622
623- def _bincount_sum (bincounts , dtype = int ):
623+ def _bincount_agg (bincounts , dtype , ** kwargs ):
624+ if not isinstance (bincounts , list ):
625+ return bincounts
626+
624627 n = max (map (len , bincounts ))
625628 out = zeros_like_safe (bincounts [0 ], shape = n , dtype = dtype )
626629 for b in bincounts :
@@ -629,43 +632,38 @@ def _bincount_sum(bincounts, dtype=int):
629632
630633
631634@derived_from (np )
632- def bincount (x , weights = None , minlength = 0 ):
635+ def bincount (x , weights = None , minlength = 0 , split_every = None ):
633636 if x .ndim != 1 :
634637 raise ValueError ("Input array must be one dimensional. Try using x.ravel()" )
635638 if weights is not None :
636639 if weights .chunks != x .chunks :
637640 raise ValueError ("Chunks of input array x and weights must match." )
638641
639642 token = tokenize (x , weights , minlength )
640- name = "bincount-" + token
641- final_name = "bincount-sum" + token
642- # Call np.bincount on each block, possibly with weights
643+ args = [x , "i" ]
643644 if weights is not None :
644- dsk = {
645- (name , i ): (np .bincount , (x .name , i ), (weights .name , i ), minlength )
646- for i , _ in enumerate (x .__dask_keys__ ())
647- }
648- dtype = np .bincount ([1 ], weights = [1 ]).dtype
645+ meta = np .bincount ([1 ], weights = [1 ])
646+ args .extend ([weights , "i" ])
649647 else :
650- dsk = {
651- (name , i ): (np .bincount , (x .name , i ), None , minlength )
652- for i , _ in enumerate (x .__dask_keys__ ())
653- }
654- dtype = np .bincount ([]).dtype
648+ meta = np .bincount ([])
655649
656- dsk [(final_name , 0 )] = (_bincount_sum , list (dsk ), dtype )
657- graph = HighLevelGraph .from_collections (
658- final_name , dsk , dependencies = [x ] if weights is None else [x , weights ]
650+ chunked_counts = blockwise (
651+ partial (np .bincount , minlength = minlength ), "i" , * args , token = token , meta = meta
659652 )
660653
661- if minlength == 0 :
662- chunks = ((np .nan ,),)
663- else :
664- chunks = ((minlength ,),)
665-
666- meta = meta_from_array (x , 1 , dtype = dtype )
654+ from .reductions import _tree_reduce
667655
668- return Array (graph , final_name , chunks , meta = meta )
656+ output = _tree_reduce (
657+ chunked_counts ,
658+ aggregate = partial (_bincount_agg , dtype = meta .dtype ),
659+ axis = (0 ,),
660+ keepdims = False ,
661+ dtype = meta .dtype ,
662+ split_every = split_every ,
663+ concatenate = False ,
664+ )
665+ output ._meta = meta
666+ return output
669667
670668
671669@derived_from (np )
0 commit comments