# Install required packages
install.packages("fields")
install.packages("RColorBrewer")
# Change the current work directory to the one containg POPSutilities
setwd("pathonyourcomputer/POPS/R/")
source("POPSutilities.r")


# You should copy the files you want to analyse in the work directory
# Or replace the lines below by correct file names
# e.g. "MyProject/Example_RUN_000003/example.txtTR.txt"
estimationFile="example.txtTR.txt"
predictionFile="example.txtPPM_T+3.txt"

# Calulate rate of turnover between current population genetic structure
# and structure forecasted for temperature increase
correlationFromPops(file1=estimationFile,file2=predictionFile,nind=268)

# Load spatial coordinates
data=read.table("example.txt",header=T)
coord=data[,c("longitude","latitude")]

# Create a grid from these coordinates
# with 100 pixels for longitude, 100 for latitude
grid=createGrid(min(coord[,"longitude"]),max(coord[,"longitude"]),
	min(coord[,"latitude"]),max(coord[,"latitude"]),100,100)
constraints=NULL

# OR Create a grid from an ascii raster file
# ascii raster files can for example be downloaded from NOAA website
# http://www.ngdc.noaa.gov/mgg/geodas/geodas.html
asciiFile="alps.asc"
grid=createGridFromAsciiRaster(asciiFile)
# To display only altitudes above 1000:
constraints=getConstraintsFromAsciiRaster(asciiFile,cell_value_min=1000)


# Plot estimated coefficients and predicted coefficients maps
x11() # optional
par(mfrow=c(2,1))
mapsFromPops(file=estimationFile,nind=268,coord=coord,grid=grid,
	constraints=constraints,method="max",main="Present")
mapsFromPops(file=predictionFile,nind=268,coord=coord,grid=grid,
	constraints=constraints,method="max",main="Temperature increase: +3")

#Display legend
x11()
displayLegend(K=3)