Compute sum of the elements in a chunk of a dask array
<p>I'd like to apply a function to each block and return a single element, for example, from a 10x10 matrix I'd like to sum each 2x2 block.</p>

<p>I've tried some combinations of what you see below but I always get an <code>IndexError</code>.</p>

<pre><code>m = da.from_array(np.ones((10,10)), chunks=(2,2))
def compute_block_sum(block):
    return np.array([np.sum(block)])
m.map_blocks(compute_block_sum, chunks=(1,1)).compute()
</code></pre>

<p>Using the default settings <code>map_blocks</code> assumes that the user-provided function returns a numpy array of the same number of dimensions as the input.  So you can get your example above to work by adding in a second empty dimension to your <code>compute_block_sum</code> function using numpy slicing with <code>None</code>.</p>

<pre><code>In [1]: import dask.array as da
In [2]: import numpy as np
In [3]: m = da.from_array(np.ones((10,10)), chunks=(2,2))

In [4]: def compute_block_sum(block):
   ...:     return np.array([np.sum(block)])[:, None]

In [5]: m.map_blocks(compute_block_sum, chunks=(1, 1)).compute()
Out[5]: 
array([[ 4.,  4.,  4.,  4.,  4.],
       [ 4.,  4.,  4.,  4.,  4.],
       [ 4.,  4.,  4.,  4.,  4.],
       [ 4.,  4.,  4.,  4.,  4.],
       [ 4.,  4.,  4.,  4.,  4.]])
</code></pre>

python dask