Skip to content

Instantly share code, notes, and snippets.

@SheikSadi
Created November 16, 2022 09:04
Show Gist options
  • Save SheikSadi/7f684c7ddbe91c63b22f066965f598f4 to your computer and use it in GitHub Desktop.
Save SheikSadi/7f684c7ddbe91c63b22f066965f598f4 to your computer and use it in GitHub Desktop.
numpy cumsum from a specified center
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
@SheikSadi
Copy link
Author

 [In] a = np.random.randint(1,9, (8,8))
 [In] a
[Out] array([[1, 6, 5, 7, 4, 7, 2, 8],
       [6, 8, 5, 1, 4, 4, 1, 4],
       [1, 5, 7, 5, 3, 3, 2, 6],
       [5, 7, 8, 5, 5, 6, 5, 2],
       [4, 3, 8, 4, 5, 5, 7, 4],
       [6, 2, 3, 5, 6, 5, 5, 1],
       [4, 4, 5, 8, 3, 6, 4, 5],
       [8, 5, 5, 7, 6, 3, 7, 4]])
 [In] center_cumsum(a, [3, 3])
[Out] array([[ 82,  69,  43,  18,  34,  54,  64,  84],
       [ 63,  51,  31,  11,  23,  36,  44,  56],
       [ 43,  37,  25,  10,  18,  27,  34,  42],
       [ 25,  20,  13,   5,  10,  16,  21,  23],
       [ 44,  35,  25,   9,  19,  30,  42,  48],
       [ 60,  45,  33,  14,  30,  46,  63,  70],
       [ 81,  62,  46,  22,  41,  63,  84,  96],
       [106,  79,  58,  29,  54,  79, 107, 123]])
 [In] center_cumsum(a, [0, 0]) == a.cumsum(axis=1).cumsum(axis=0)
[Out] array([[ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True]])

@SheikSadi
Copy link
Author

import matplotlib.pyplot as plt
from center_cumsum import center_cumsum

a = np.random.randint(0, 255, (9,9))
plt.imshow(a, cmap="Greys")
_ = plt.axis("off")

image

a_cum = center_cumsum(a, [4, 4])
plt.imshow(a_cum, cmap="Greys")
_ = plt.axis("off")

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment