Dani
Dani

Reputation: 544

Determine neighboring cells in a two-dimensional grid with periodic conditions

Suppose we have the following two-dimensional network, whose cell indexes we label with integers:

20  21  22  23  24
15  16  17  18  19
10  11  12  13  14
5   6   7   8   9
0   1   2   3   4

What I want is a function that receives as input a cell index (cell) and the number of cells along an axis (n=5 in this case), and returns an array with its 9 neighbors (including the cell itself), taking into account the periodicity of the global box.

I show you what I've tried, which 'almost' works:

def celdas_vecinas(cell,n):

    return np.mod(cell + np.array([0, -n-1, -n, -n+1, -1, 1, n-1, n, n+1], dtype=np.int64), n**2)

Where I have entered np.mod to reflect the periodic conditions. The point is that this function behaves well only for some values.

>>> celdas_vecinas(1,5) 
array([ 1, 20, 21, 22,  0,  2,  5,  6,  7]) # right!

>>> celdas_vecinas(21,5)
array([21, 15, 16, 17, 20, 22,  0,  1,  2]) # right!

But if I enter the index of one of the cells in the corners, the following happens:

>>> celdas_vecinas(0,5)
array([ 0, 19, 20, 21, 24,  1,  4,  5,  6]) # should be 9 instead of 19

Also fails for cell=5 for example.

Does anyone know how I could implement this function? When the cell index doesn't touch any border it's very easy to implement, but I don't know how to include the periodic effects, although I guess it must be something related to the np.mod function

Upvotes: 2

Views: 485

Answers (4)

Dani
Dani

Reputation: 544

Based on Comevussor's answer, I've end up with this code:

@nb.njit(nb.i8[:](nb.i8, nb.i8), fastmath=True)
def celdas_vecinas(cell,n):

    Nt = n**2 # total number of cells

    x = cell % n; y = cell // n # x,y cell coordinates
    izq =      (x - 1) % n + y * n
    der =      (x + 1) % n + y * n
    arri =     (x % n + (y+1) * n) % Nt
    aba =      (x % n + (y-1) * n) % Nt
    aba_izq =  (izq - n) % Nt
    aba_der =  (der - n) % Nt
    arri_izq = (izq + n) % Nt
    arri_der = (der + n) % Nt

    return np.array([cell, aba_izq, aba, aba_der, izq, der, arri_izq, arri, arri_der])

which works with following performance:

>>> %timeit celdas_vecinas(0,5)
567 ns ± 13.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Upvotes: 0

GolamMazid Sajib
GolamMazid Sajib

Reputation: 9447

Try with this:

grid = [[20,  21,  22,  23,  24],[15,  16,  17,  18,  19],[10,  11,  12,  13,  14],[5,   6,   7,   8,   9],[0,   1,   2,   3,   4]]
def celdas_vecinas(cell,n):
    Row = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
    Col = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
    x = y = 0
    for i in range(n):
        z = 0;
        for j in range(n):
            if grid[i][j] == cell:
                x = i
                y = j
                z = 1
                break
        if z:
            break

    ans = []
    for i in range(9):
        xx = (n + x + Row[i]) % n
        yy = (n + y + Col[i]) % n
        ans.append(grid[xx][yy])
    return ans;
print(celdas_vecinas(1,5))
print(celdas_vecinas(21,5))
print(celdas_vecinas(5,5))

Upvotes: 0

Comevussor
Comevussor

Reputation: 318

The lines periodicity is not working like the columns periodicity. I think you should first get the 2 cells on each side and then move up and down. I have tried this and it seems to work :

def celdas_vecinas(cell, n) :
    last_row = n * (cell // n)
    left_cell = last_row + ( cell - last_row - 1 ) % n
    right_cell = last_row + ( cell - last_row + 1 ) % n
    line = np.array( [ left_cell, cell, right_cell ] )
    return np.mod( [ line + n, line, line - n ], n**2)

(I removed my previous answer as I messed up in indeces)

Upvotes: 1

FBruzzesi
FBruzzesi

Reputation: 6495

Numpy implementation can take advantage numpy.argwhere to retrieve value indeces, create the grid of indices with numpy.ix_, and finally apply numpy.narray.ravel method to flat the array::

import numpy as np

n = 5
grid = np.arange(n**2).reshape(n,n)[::-1]

def celdas_vecinas_np(grid, v, n):

    x, y = np.argwhere(grid == v)[0]
    idx = np.arange(x-1, x+2) %n
    idy = np.arange(y-1, y+2) %n

    return grid[np.ix_(idx, idy)].ravel()

celdas_vecinas_np(grid, 24, n)
array([ 3,  4,  0, 23, 24, 20, 18, 19, 15])

On the other hand, for a Numba implementation we cannot use numpy.argwhere, but we can use numpy.where to get indices. Once we do that, it is only a matter of looping in the right ranges, namely:

from numba import njit

@njit
def celdas_vecinas_numba(grid, v, n):

    x, y = np.where(grid == v)
    x, y = x[0], y[0]

    result = []
    for ix in range(x-1, x+2):
        for iy in range(y-1, y+2):
            result.append(grid[ix%n, iy%n])

    return result

celdas_vecinas_numba(grid, 24, n)
[3, 4, 0, 23, 24, 20, 18, 19, 15]

Perfomance Comparison with such small grid numba already runs ~20x faster in my local machine:

%timeit celdas_vecinas_np(grid, 24, 5)
38 µs ± 1.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit celdas_vecinas_numba(grid, 24, n)
1.81 µs ± 93.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Upvotes: 1

Related Questions