#!/usr/bin/env python

#%Module
#% description: Select a random cell from a moving window
#% keywords: raster
#%end
#%option G_OPT_R_INPUT
#%end
#%option G_OPT_R_OUTPUT
#%end
#%option
#% key: size
#% type: integer
#% required: yes
#% multiple: no
#% description: Size of window in raster cells
#%end

import numpy as np
import grass.script as grass
from grass.script.array import array

null = -0x80000000

def main():
    input = options['input']
    output = options['output']
    size = int(options['size'])

    if size % 2 == 0:
        grass.fatal(_("Window size must be odd"))

    radius = (size - 1) / 2

    src = array(dtype = np.int32)
    src.read(input, null = null)
    rows, cols = src.shape

    orows = rows - size + 1
    ocols = cols - size + 1

    out = array(dtype = np.int32)
    out[...] = null
    dst = out[radius:-radius,radius:-radius]

    ix = np.arange(ocols)

    for row in xrange(orows):
        dx,dy = np.random.randint(0, size, size=(2,ocols))
        x = ix + dx
        y = row + dy
        dst[row,:] = src[y,x]

    dst.write(output, null = null)

if __name__ == "__main__":
    options, flags = grass.parser()
    main()
