How to cut a Numpy array to the border?

I use Numpy and Python in a project where a 2D map is represented by ndarray:

 map = [[1,2,3,4,5], [2,3,4,2,3], [2,2,2,1,2], [3,2,1,2,3], [4,6,5,7,4]] MAP_WIDTH = 5, MAP_HEIGHT = 5 

The object has a tuple:

 actor.location = (3,3) 

and viewing range:

 actor.range = 2 

How to write the actor.view_map(map) function, so that the map returns the area surrounding the actor’s location to a range. For example (using the map above),

 range = 1 location = (3, 2) => [[2,3,4], [3,4,2], [2,2,1]] 

but if the range of actors extends too far, I want the map to fill -1:

 range = 1 location = (1,1) [[-1,-1,-1], [-1, 1, 2], [-1, 2, 3]] 

The simplest case is a range of 0, which returns the current square:

 range = 0 location = (1, 2) [[2]] 

How to cut the map to a certain border?

+8
python numpy
source share
2 answers

So, thanks to Joe Kington, I added a border around my map (filled -1 sec.).

Here is how I did it, but it may not be very Pythonic, since I just started with the language / library:

 map = numpy.random.randint(10, size=(2 * World.MAP_WIDTH, 2 * World.MAP_HEIGHT)) map[0 : World.MAP_WIDTH / 4, :] = -1 map[7 * World.MAP_WIDTH / 4 : 2 * World.MAP_WIDTH, :] = -1 map[:, 0 : World.MAP_HEIGHT / 4] = -1 map[:, 7 * World.MAP_HEIGHT / 4 : 2 * World.MAP_WIDTH] = -1 
+4
source share

Here's a little Box class to make it easier to use boxes -

 from __future__ import division import numpy as np class Box: """ B = Box( 2d numpy array A, radius=2 ) B.box( j, k ) is a box A[ jk - 2 : jk + 2 ] clipped to the edges of A @askewchan, use np.pad (new in numpy 1.7): padA = np.pad( A, pad_width, mode="constant", edge=-1 ) B = Box( padA, radius ) """ def __init__( self, A, radius ): self.A = np.asanyarray(A) self.radius = radius def box( self, j, k ): """ b.box( j, k ): square around j, k clipped to the edges of A """ return self.A[ self.box_slice( j, k )] def box_slice( self, j, k ): """ square, jk-r : jk+r clipped to A.shape """ # or np.clip ? r = self.radius return np.s_[ max( j - r, 0 ) : min( j + r + 1, self.A.shape[0] ), max( k - r, 0 ) : min( k + r + 1, self.A.shape[1] )] #............................................................................... if __name__ == "__main__": A = np.arange(5*7).reshape((5,7)) print "A:\n", A B = Box( A, radius=2 ) print "B.box( 0, 0 ):\n", B.box( 0, 0 ) print "B.box( 0, 1 ):\n", B.box( 0, 1 ) print "B.box( 1, 2 ):\n", B.box( 1, 2 ) 
+2
source share

All Articles