|
| 1 | +# ***************************************************************************** |
| 2 | +# Copyright (c) 2024, Intel Corporation |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# Redistribution and use in source and binary forms, with or without |
| 6 | +# modification, are permitted provided that the following conditions are met: |
| 7 | +# - Redistributions of source code must retain the above copyright notice, |
| 8 | +# this list of conditions and the following disclaimer. |
| 9 | +# - Redistributions in binary form must reproduce the above copyright notice, |
| 10 | +# this list of conditions and the following disclaimer in the documentation |
| 11 | +# and/or other materials provided with the distribution. |
| 12 | +# |
| 13 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 14 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 15 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 16 | +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 17 | +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 18 | +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 19 | +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 20 | +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 21 | +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 22 | +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF |
| 23 | +# THE POSSIBILITY OF SUCH DAMAGE. |
| 24 | +# ***************************************************************************** |
| 25 | + |
| 26 | +""" |
| 27 | +Interface of the functional programming routines part of the DPNP |
| 28 | +
|
| 29 | +Notes |
| 30 | +----- |
| 31 | +This module is a face or public interface file for the library |
| 32 | +it contains: |
| 33 | + - Interface functions |
| 34 | + - documentation for the functions |
| 35 | + - The functions parameters check |
| 36 | +
|
| 37 | +""" |
| 38 | + |
| 39 | + |
| 40 | +import numpy |
| 41 | +from dpctl.tensor._numpy_helper import normalize_axis_index |
| 42 | + |
| 43 | +import dpnp |
| 44 | + |
| 45 | +__all__ = ["apply_along_axis"] |
| 46 | + |
| 47 | + |
| 48 | +def apply_along_axis(func1d, axis, arr, *args, **kwargs): |
| 49 | + """ |
| 50 | + Apply a function to 1-D slices along the given axis. |
| 51 | +
|
| 52 | + Execute ``func1d(a, *args, **kwargs)`` where `func1d` operates on |
| 53 | + 1-D arrays and `a` is a 1-D slice of `arr` along `axis`. |
| 54 | +
|
| 55 | + This is equivalent to (but faster than) the following use of |
| 56 | + :obj:`dpnp.ndindex` and :obj:`dpnp.s_`, which sets each of |
| 57 | + ``ii``, ``jj``, and ``kk`` to a tuple of indices:: |
| 58 | +
|
| 59 | + Ni, Nk = a.shape[:axis], a.shape[axis+1:] |
| 60 | + for ii in ndindex(Ni): |
| 61 | + for kk in ndindex(Nk): |
| 62 | + f = func1d(arr[ii + s_[:,] + kk]) |
| 63 | + Nj = f.shape |
| 64 | + for jj in ndindex(Nj): |
| 65 | + out[ii + jj + kk] = f[jj] |
| 66 | +
|
| 67 | + Equivalently, eliminating the inner loop, this can be expressed as:: |
| 68 | +
|
| 69 | + Ni, Nk = a.shape[:axis], a.shape[axis+1:] |
| 70 | + for ii in ndindex(Ni): |
| 71 | + for kk in ndindex(Nk): |
| 72 | + out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk]) |
| 73 | +
|
| 74 | + Parameters |
| 75 | + ---------- |
| 76 | + func1d : function (M,) -> (Nj...) |
| 77 | + This function should accept 1-D arrays. It is applied to 1-D |
| 78 | + slices of `arr` along the specified axis. |
| 79 | + axis : int |
| 80 | + Axis along which `arr` is sliced. |
| 81 | + arr : {dpnp.ndarray, usm_ndarray} (Ni..., M, Nk...) |
| 82 | + Input array. |
| 83 | + args : any |
| 84 | + Additional arguments to `func1d`. |
| 85 | + kwargs : any |
| 86 | + Additional named arguments to `func1d`. |
| 87 | +
|
| 88 | + Returns |
| 89 | + ------- |
| 90 | + out : dpnp.ndarray (Ni..., Nj..., Nk...) |
| 91 | + The output array. The shape of `out` is identical to the shape of |
| 92 | + `arr`, except along the `axis` dimension. This axis is removed, and |
| 93 | + replaced with new dimensions equal to the shape of the return value |
| 94 | + of `func1d`. |
| 95 | +
|
| 96 | + See Also |
| 97 | + -------- |
| 98 | + :obj:`dpnp.apply_over_axes` : Apply a function repeatedly over |
| 99 | + multiple axes. |
| 100 | +
|
| 101 | + Examples |
| 102 | + -------- |
| 103 | + >>> import dpnp as np |
| 104 | + >>> def my_func(a): # Average first and last element of a 1-D array |
| 105 | + ... return (a[0] + a[-1]) * 0.5 |
| 106 | + >>> b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
| 107 | + >>> np.apply_along_axis(my_func, 0, b) |
| 108 | + array([4., 5., 6.]) |
| 109 | + >>> np.apply_along_axis(my_func, 1, b) |
| 110 | + array([2., 5., 8.]) |
| 111 | +
|
| 112 | + For a function that returns a 1D array, the number of dimensions in |
| 113 | + `outarr` is the same as `arr`. |
| 114 | +
|
| 115 | + >>> b = np.array([[8, 1, 7], [4, 3, 9], [5, 2, 6]]) |
| 116 | + >>> np.apply_along_axis(sorted, 1, b) |
| 117 | + array([[1, 7, 8], |
| 118 | + [3, 4, 9], |
| 119 | + [2, 5, 6]]) |
| 120 | +
|
| 121 | + For a function that returns a higher dimensional array, those dimensions |
| 122 | + are inserted in place of the `axis` dimension. |
| 123 | +
|
| 124 | + >>> b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
| 125 | + >>> np.apply_along_axis(np.diag, -1, b) |
| 126 | + array([[[1, 0, 0], |
| 127 | + [0, 2, 0], |
| 128 | + [0, 0, 3]], |
| 129 | + [[4, 0, 0], |
| 130 | + [0, 5, 0], |
| 131 | + [0, 0, 6]], |
| 132 | + [[7, 0, 0], |
| 133 | + [0, 8, 0], |
| 134 | + [0, 0, 9]]]) |
| 135 | +
|
| 136 | + """ |
| 137 | + |
| 138 | + dpnp.check_supported_arrays_type(arr) |
| 139 | + nd = arr.ndim |
| 140 | + exec_q = arr.sycl_queue |
| 141 | + usm_type = arr.usm_type |
| 142 | + axis = normalize_axis_index(axis, nd) |
| 143 | + |
| 144 | + # arr, with the iteration axis at the end |
| 145 | + inarr_view = dpnp.moveaxis(arr, axis, -1) |
| 146 | + |
| 147 | + # compute indices for the iteration axes, and append a trailing ellipsis to |
| 148 | + # prevent 0d arrays decaying to scalars |
| 149 | + # TODO: replace with dpnp.ndindex |
| 150 | + inds = numpy.ndindex(inarr_view.shape[:-1]) |
| 151 | + inds = (ind + (Ellipsis,) for ind in inds) |
| 152 | + |
| 153 | + # invoke the function on the first item |
| 154 | + try: |
| 155 | + ind0 = next(inds) |
| 156 | + except StopIteration: |
| 157 | + raise ValueError( |
| 158 | + "Cannot apply_along_axis when any iteration dimensions are 0" |
| 159 | + ) from None |
| 160 | + res = dpnp.asanyarray( |
| 161 | + func1d(inarr_view[ind0], *args, **kwargs), |
| 162 | + sycl_queue=exec_q, |
| 163 | + usm_type=usm_type, |
| 164 | + ) |
| 165 | + |
| 166 | + # build a buffer for storing evaluations of func1d. |
| 167 | + # remove the requested axis, and add the new ones on the end. |
| 168 | + # laid out so that each write is contiguous. |
| 169 | + # for a tuple index inds, buff[inds] = func1d(inarr_view[inds]) |
| 170 | + buff = dpnp.empty_like(res, shape=inarr_view.shape[:-1] + res.shape) |
| 171 | + |
| 172 | + # save the first result, then compute and save all remaining results |
| 173 | + buff[ind0] = res |
| 174 | + for ind in inds: |
| 175 | + buff[ind] = dpnp.asanyarray( |
| 176 | + func1d(inarr_view[ind], *args, **kwargs), |
| 177 | + sycl_queue=exec_q, |
| 178 | + usm_type=usm_type, |
| 179 | + ) |
| 180 | + |
| 181 | + # restore the inserted axes back to where they belong |
| 182 | + for _ in range(res.ndim): |
| 183 | + buff = dpnp.moveaxis(buff, -1, axis) |
| 184 | + |
| 185 | + return buff |
0 commit comments