How do I select a window from a numpy array with periodic boundary conditions?
import numpy as np
A=np.arange(16).reshape((4,4))
def neighbors(arr,x,y,n=3):
''' Given a 2D-array, returns an nxn array whose "center" element is arr[x,y]'''
arr=np.roll(np.roll(arr,shift=-x+1,axis=0),shift=-y+1,axis=1)
return arr[:n,:n]
print(A)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
print(neighbors(A,0,0))
# [[15 12 13]
# [ 3 0 1]
# [ 7 4 5]]
print(neighbors(A,1,0))
# [[ 3 0 1]
# [ 7 4 5]
# [11 8 9]]