# The data used in this script was collected by Eduardo M. Arraut.
# For more information, see 
# E. M. Arraut, M. Marmontel, J. E. Mantovani, E. M. L. M. Novo, D. W. Macdonald, R. E. Kenward
# The lesser of two evils: seasonal migrations of Amazonian manatees in the Western Amazon
# Journal of Zoology, 280(3) 247-256, March 2010
# DOI: 10.1111/j.1469-7998.2009.00655.x

require(adehabitat)
require(aRT)

# choose the parameters
con=openConn()
db=createDb(con, "peixeboi", replace=TRUE)

l=createLayer(db, l="mat")
addShape(l, tab="tab", file="CBZ_mat_pt.shp", ID="SPRNOME")

#l=openLayer(db,"CBZ_mat_pt") # layer of points with the samples

points = getPoints(l) # read the samples

th = createTheme(l, view="view")
setVisual(th, visualPoints(pch=19, size=5))

# convert to adehabitat's format
matdata = data.frame(points@coords)
ids = rep(1, 125)

hr = mcp(matdata, ids, percent=90)

plot(points, pch="+")
plot(hr, add=T)
points(points, pch="+")

# converting to sp
hr = hr[,c(2,3)]
hr = rbind(hr, hr[1,])
hr = as.matrix(hr)
artpols <- SpatialPolygons(list(Polygons(list(Polygon(hr)),"1")),1)

# saving in the database
lpol = createLayer(db, "homerange")
addPolygons(lpol, artpols)
createTable(lpol)
lpol
th = createTheme(lpol)

x=clusthr(matdata)
plot(x)

jj=mcp.area(matdata, ids)
plot(jj)

hr = kernelUD(matdata, ids)
image(hr)

# converting to sp
asc = hr[[1]]$UD
size = attr(asc, "cellsize")
cellsize = c(size, size)
coords = getXYcoords(asc)
cellcentre.offset = c(min(coords$x), min(coords$y))
cells.dim = dim(asc)
gt = GridTopology(cellcentre.offset, cellsize, cells.dim)
raster = as.numeric(asc) * 10000000000
r = matrix(raster, ncol=cells.dim[2])
for(i in 1:(cells.dim[1])) { r[i,] = rev(r[i,]) }
raster = as.numeric(r)
raster[which(raster==0)] = NA
kernel <- SpatialGridDataFrame(gt, data=as.data.frame(raster))

par(mfrow=c(1,2))
image(kernel)
points(points, pch="+")
image(hr)

lraster = createLayer(db, "kernelUD")
addRaster(lraster, kernel)

th = createTheme(lraster, view="view")
setVisual(th, visualRaster(color = heat.colors(15)), mode="r")

jj=kernel.area(matdata, ids)
plot(jj)

