Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a window from a numpy array with periodic boundary conditions?

Tags:

python

numpy

Suppose I make a 2d array like this:

>>> A=np.arange(16).reshape((4,4))
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

and I want to be able to select a 3x3 window around any given element so that the window wraps around the boundaries how would I do that? I know I can do this if the boundaries of the window don't overlap the boundaries of the original array:

>>> A[1:4,0:3]
array([[ 4,  5,  6],
       [ 8,  9, 10],
       [12, 13, 14]])

but if I use an expression like A[i-1:i+2,j-1:j+2] it only returns an empty array for i=0, j=0 for example.

like image 670
2daaa Avatar asked Nov 10 '10 19:11

2daaa


People also ask

How do you access elements of an array in NumPy?

Access Array Elements You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do I select specific rows and columns in NumPy?

We can use [][] operator to select an element from Numpy Array i.e. Example 1: Select the element at row index 1 and column index 2. Or we can pass the comma separated list of indices representing row index & column index too i.e.

How do I slice a row in NumPy array?

To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .


1 Answers

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]]
like image 139
unutbu Avatar answered Sep 23 '22 16:09

unutbu