Skip to content

Instantly share code, notes, and snippets.

@binshengliu
Created August 13, 2020 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binshengliu/fa9c9aa87067ecd887fa0cd4cb3d60e8 to your computer and use it in GitHub Desktop.
Save binshengliu/fa9c9aa87067ecd887fa0cd4cb3d60e8 to your computer and use it in GitHub Desktop.
Independently roll rows of a tensor.
# Copied from https://stackoverflow.com/a/56175538/955952
def indep_roll(arr, shifts, axis=1):
"""Apply an independent roll for each dimensions of a single axis.
Parameters
----------
arr : np.ndarray
Array of any shape.
shifts : np.ndarray
How many shifting to use for each dimension. Shape: `(arr.shape[axis],)`.
axis : int
Axis along which elements are shifted.
"""
arr = np.swapaxes(arr,axis,-1)
all_idcs = np.ogrid[[slice(0,n) for n in arr.shape]]
# Convert to a positive shift
shifts[shifts < 0] += arr.shape[-1]
all_idcs[-1] = all_idcs[-1] - shifts[:, np.newaxis]
result = arr[tuple(all_idcs)]
arr = np.swapaxes(result,-1,axis)
return arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment