# mask nodata values
raster_array = pyGISlib.mask_raster(raster_array, nodata)
print 'mean elevation = ', raster_array.mean()

# calculate the topographic gradient
grad_x, grad_y = np.gradient(raster_array)
grad_x = grad_x/pixelsize[0]
grad_y = grad_y/pixelsize[1]
grad = np.sqrt(grad_x**2 + grad_y**2)
print 'mean topographic gradient ', grad.mean()

#
print 'saving raster file'
pyGISlib.write_raster_file('examples/topo_gradient.tif', grad.data,
                            new_origin, pixelsize, nodata,
                            crs=projection )

# get coordinates of new raster
raster_x, raster_y = pyGISlib.get_raster_coordinates(new_dimensions, 
                                                     pixelsize,
                                                     new_origin)

# make figures of elevation & topographic gradient
pl.figure(figsize=(8, 4))
pl.subplots_adjust(wspace=0.35, left=0.1, right=0.92)

ax1 = pl.subplot(1, 2, 1)
pl.contourf(raster_x, raster_y, raster_array)
cbar = pl.colorbar(shrink=0.5)
cbar.set_label('Elevation (m)')
Nintervals = len(raster_values)

band_values = np.zeros((Nintervals, Nbands))

for i in range(Nbands):
    band_values[:, i] = df["value_band%i" % (i + 1)].values

# determine closeness to band values:
diff_raster = np.zeros((Nbands, nx, ny, Nintervals))
for i in xrange(Nbands):
    for j in xrange(Nintervals):
        diff_raster[i, :, :, j] = np.abs(raster[i, :, :] - band_values[j, i])

diff_raster_sum = np.zeros((nx, ny, Nintervals))

# sum the differences for each band
for j in xrange(Nintervals):
    diff_raster_sum[:, :, j] = np.sum(diff_raster[:, :, :, j], axis=0)

raster_class = np.argmin(diff_raster_sum, axis=2)
raster_class_final = np.zeros(raster_class.shape)
for i in xrange(Nintervals):
    ind = np.where(raster_class == i)
    raster_class_final[ind] = raster_values[i]

# save raster
outputFilename = "examples/classified_raster.tif"
print "saving raster file %s" % outputFilename
pyGISlib.write_raster_file(outputFilename, raster_class_final, origin, cellsize, nodata, crs=projection)
print "done"