Created
November 16, 2022 09:04
-
-
Save SheikSadi/7f684c7ddbe91c63b22f066965f598f4 to your computer and use it in GitHub Desktop.
numpy cumsum from a specified center
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def center_cumsum(a:np.ndarray, pivot:tuple) -> np.ndarray: | |
""" | |
Compute the cumsum but pivoting a specified index | |
""" | |
assert isinstance(a, np.ndarray) | |
assert a.ndim == 2 | |
a_cum = np.zeros_like(a, dtype=a.dtype) | |
assert len(pivot) == 2 | |
i, j = pivot | |
assert (i >= 0) and (i < a.shape[0]) | |
assert (j >= 0) and (j < a.shape[1]) | |
quad1 = a[:i+1,j:] | |
a_cum[:i+1,j:] = quad1.cumsum(axis=1)[::-1].cumsum(axis=0)[::-1] | |
quad2 = a[:i+1,:j+1] | |
a_cum[:i+1,:j+1] = quad2[::-1, ::-1].cumsum(axis=1).cumsum(axis=0)[::-1, ::-1] | |
quad3 = a[i:,:j+1] | |
a_cum[i:,:j+1] = quad3[:, ::-1].cumsum(axis=1).cumsum(axis=0)[:, ::-1] | |
quad4 = a[i:,j:] | |
a_cum[i:,j:] = quad4.cumsum(axis=1).cumsum(axis=0) | |
return a_cum |
Author
SheikSadi
commented
Nov 16, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment