Coarsen array by applying reduction to fixed size neighborhoods Parameters ---------- reduction: function Reduction function (for example ``np.sum`` or ``np.mean``). The function must accept: - an ``array_like`` positional input, - an ``axis=`` keyword
(reduction, x, axes, trim_excess=False, **kwargs)
| 83 | |
| 84 | |
| 85 | def coarsen(reduction, x, axes, trim_excess=False, **kwargs): |
| 86 | """Coarsen array by applying reduction to fixed size neighborhoods |
| 87 | |
| 88 | Parameters |
| 89 | ---------- |
| 90 | reduction: function |
| 91 | Reduction function (for example ``np.sum`` or ``np.mean``). |
| 92 | |
| 93 | The function must accept: |
| 94 | |
| 95 | - an ``array_like`` positional input, |
| 96 | - an ``axis=`` keyword containing a tuple of axes, |
| 97 | - and any extra ``**kwargs`` forwarded by ``coarsen``. |
| 98 | |
| 99 | In practice, NumPy-style reductions and Array-API-compatible |
| 100 | reductions work well. |
| 101 | x: np.ndarray |
| 102 | Array to be coarsened |
| 103 | axes: dict |
| 104 | Mapping of axis to coarsening factor |
| 105 | |
| 106 | Examples |
| 107 | -------- |
| 108 | >>> x = np.array([1, 2, 3, 4, 5, 6]) |
| 109 | >>> coarsen(np.sum, x, {0: 2}) |
| 110 | array([ 3, 7, 11]) |
| 111 | >>> coarsen(np.max, x, {0: 3}) |
| 112 | array([3, 6]) |
| 113 | |
| 114 | Provide dictionary of scale per dimension |
| 115 | |
| 116 | >>> x = np.arange(24).reshape((4, 6)) |
| 117 | >>> x |
| 118 | array([[ 0, 1, 2, 3, 4, 5], |
| 119 | [ 6, 7, 8, 9, 10, 11], |
| 120 | [12, 13, 14, 15, 16, 17], |
| 121 | [18, 19, 20, 21, 22, 23]]) |
| 122 | |
| 123 | >>> coarsen(np.min, x, {0: 2, 1: 3}) |
| 124 | array([[ 0, 3], |
| 125 | [12, 15]]) |
| 126 | |
| 127 | You must avoid excess elements explicitly |
| 128 | |
| 129 | >>> x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) |
| 130 | >>> coarsen(np.min, x, {0: 3}, trim_excess=True) |
| 131 | array([1, 4]) |
| 132 | """ |
| 133 | # Insert singleton dimensions if they don't exist already |
| 134 | for i in range(x.ndim): |
| 135 | if i not in axes: |
| 136 | axes[i] = 1 |
| 137 | |
| 138 | if trim_excess: |
| 139 | ind = tuple( |
| 140 | slice(0, -(d % axes[i])) if d % axes[i] else slice(None, None) |
| 141 | for i, d in enumerate(x.shape) |
| 142 | ) |