python - Apply function to 2D numpy array elements -
i've seen post , want similar, not same.
i implementing little game of life game , using numpy arrays
representing states of game. need check, how many alive neighbors cell has. got function getting window of neighbors given coordinate , row count , column count window size want have.
so windows of 3x3 size this:
t = true f = false [[t,t,t], [f,t,t], [f,f,f]] # random truth values
in representation true
stands cell being alive. wrote code iterating on cells of state, counting true values , on using double loop, think there better numpy solution.
what i'd in naive approach:
- iterate on cells of state (not window) (i'd formulate code to executed if cell meets criteria or (being alive , surviving or being dead , coming alive))
- get window (wrapping or not wrapping) (function have)
- check if current cell alive (could lookup in state's numpy array)
- if alive start alive neighbors count of -1 otherwise start 0
- count true values of window (
np.sum
) , add alive neighbors count (which -1 if cell alive, count neighbors not cell itself) - depending on whether count of alive neighbors in ranges (configurable), write in (new) state's array
true
values. (i'd start out array, created using:np.full((height, width), false, dtype=bool)
) - go on new array, keeping old 1 in list history or logging purposes
basically:
if cell meets criteria: write true @ cell's position in new array
however meeting criteria depends on multiple rows, because state's numpy array 2d array. that's why think linked post close not need.
how can in efficient numpy-y way, avoiding unnecessary looping?
clarification
i searching best way of implementing in python using numpy , scipy, aims readable , has performance.
perhaps did not understand trying do, stopping using numpy.sum
function?
example - let state be:
import numpy np state = np.random.randint(1, 10, (9,9))
here using {0, 1} values state, 1 means "alive". can slice around cell being investigated, e.g. [2,3]
s = state[1:3,2:5] if s[1,1]: val = -1 else val = 0 val += s.sum()
if put in loop , pay attention border cases, clamping or wrapping appropriate, should describe.
if looking short elegant implementation, can done efficiently python , numpy.
Comments
Post a Comment