def raster_weights(raster, rook=False, transform='<STR_LIT:r>', **kwargs):
rasterf = raster.flatten()<EOL>if len(raster.shape) == <NUM_LIT:1>:<EOL><INDENT>shape = (np.sqrt(raster.shape[<NUM_LIT:0>]) * np.array([<NUM_LIT:1>,<NUM_LIT:1>])).astype(int)<EOL><DEDENT>else:<EOL><INDENT>shape = raster.shape<EOL><DEDENT>w = pysal.lat2W(*shape, rook=rook, **kwargs)<EOL>if isinstance(rasterf, np.ma.core.MaskedArray):<EOL><INDENT>miss = rasterf.mask<EOL><DEDENT>else:<EOL><INDENT>miss = np.logical_or(np.isnan(rasterf), np.isinf(rasterf))<EOL><DEDENT>missn = set(np.arange(<NUM_LIT:0>, len(miss))[miss])<EOL>cneighbors = {}<EOL>for key, value in w.neighbors.items():<EOL><INDENT>if key not in missn:<EOL><INDENT>value = list(set(value).difference(missn))<EOL>cneighbors[key] = value<EOL><DEDENT><DEDENT>w = pysal.W(cneighbors)<EOL>w.transform = transform<EOL>return w<EOL>
Construct PySal weights for rasters
It drops weights for all cells that have no data or are Inf/NaN
Usage:

w = raster_weights(raster, rook=False, transform='r', **kwargs)

where
    raster: (Masked) Numpy array for which weights are to be constructed
    rook: Boolean, type of contiguity. Default is queen. For rook, rook = True
    **kwargs are defined by and passed to pysal.lat2W.
    See help(pysal.lat2W)