#### plot cloud forest for all different protected areas

for (year in 2002:2016)
{
  glm_un<-paste0("/mnt/storage/karger/cloudforest/glm_bino_3_cf_un_",year,".sgrd")
  glm_pr<-paste0("/mnt/storage/karger/cloudforest/glm_bino_3_cf_pr_",year,".sgrd")
  gam_un<-paste0("/mnt/storage/karger/cloudforest/gam_3_cf_un_",year,".sgrd")
  gam_pr<-paste0("/mnt/storage/karger/cloudforest/gam_3_cf_pr_",year,".sgrd")
  poi_un<-paste0("/mnt/storage/karger/cloudforest/glm_pois_3_cf_un_",year,".sgrd")
  poi_pr<-paste0("/mnt/storage/karger/cloudforest/glm_pois_3_cf_pr_",year,".sgrd")
  
  ens_out<-paste0("/mnt/storage/karger/cloudforest/ensamble_mean_",year,".sgrd")
  ens_out_sd<-paste0("/mnt/storage/karger/cloudforest/ensamble_sd_",year,".sgrd")
  
  glm<-paste0("/mnt/storage/karger/cloudforest/glm_bino_3_",year,".sgrd")
  grids<-paste0("\"",glm_un,";",glm_pr,"\"")
  sc<-paste0("saga_cmd statistics_grid 4 -GRIDS=",grids," -WEIGHTS=NULL -SUM=",glm)
  system(sc)
  
  poi<-paste0("/mnt/storage/karger/cloudforest/glm_pois_3_",year,".sgrd")
  grids<-paste0("\"",poi_un,";",poi_pr,"\"")
  sc<-paste0("saga_cmd statistics_grid 4 -GRIDS=",grids," -WEIGHTS=NULL -SUM=",poi)
  system(sc)
  
  gam<-paste0("/mnt/storage/karger/cloudforest/gam_bino_3_",year,".sgrd")
  grids<-paste0("\"",gam_un,";",gam_pr,"\"")
  sc<-paste0("saga_cmd statistics_grid 4 -GRIDS=",grids," -WEIGHTS=NULL -SUM=",gam)
  system(sc)
  
  grids<-paste0("\"",glm,";",gam,";",poi,"\"")
  sc<-paste0("saga_cmd statistics_grid 4 -GRIDS=",grids," -WEIGHTS=NULL -MEAN=",ens_out," -STDDEV=",ens_out_sd)
  system(sc)
}

years<-c(2001:2016)
xvect<-years
st1_mean<-stack(paste0("/mnt/storage/karger/cloudforest/ensamble_mean_",years,".sdat"))
st1_sd  <-stack(paste0("/mnt/storage/karger/cloudforest/ensamble_sd_",years,".sdat"))




library(RColorBrewer)
library(rasterVis)
library(raster)
library(viridis)
library(gridExtra)
library(maptools)
library(grid)
library(ggplotify)

shp1<-shapefile("Z:/karger/cloudforest_loss/WDPA_Dec2016-shapefile-polygons_TCF_v16.shp")


# Boxplot of change for IUCN categories
# library
library(multcompView)
library(viridis)

c=1
shp1$ensamble_change<-100-(100*shp1$tcf_ensembl.17/shp1$tcf_ensembl)

model=lm( shp1$ensamble_change~shp1$IUCN_CAT )
ANOVA=aov(model)

# Tukey test 
TUKEY <- TukeyHSD(x=ANOVA, 'shp1$IUCN_CAT', conf.level=0.95)

shp1$IUCN_CAT_NUM<-shp1$IUCN_CAT
shp1$IUCN_CAT_NUM<-factor(shp1$IUCN_CAT_NUM,levels=levels(shp1$IUCN_CAT_NUM)[c(7,8,4,5,6,3,1,10,9,2)])
shp1$IUCN_CAT_NUM<-as.numeric(as.factor(shp1$IUCN_CAT))


# specify number of desired yvalues for each weld.type.ID
n <- 33

dfx1<-as.data.frame(log(shp1$ensamble_change+c)*-1)
dfx1$cat<-shp1$IUCN_CAT_NUM
colnames(dfx1)<-c("change","cat")
dfx1<-dfx1[complete.cases(dfx1),]



pdf(paste0("Z:/karger/cloudforest_loss/Fig_S5_v16.pdf"),width = 8, height=7)
# I need to group the treatments that are not different each other together.
  generate_label_df <- function(TUKEY, variable){
    
    # Extract labels and factor levels from Tukey post-hoc 
    Tukey.levels <- TUKEY[[variable]][,4]
    Tukey.labels <- data.frame(multcompLetters(Tukey.levels)['Letters'])
    
    #I need to put the labels in the same order as in the boxplot :
    Tukey.labels$treatment=rownames(Tukey.labels)
    Tukey.labels=Tukey.labels[order(Tukey.labels$treatment) , ]
    return(Tukey.labels)
  }
  
  # Apply the function on my dataset
  LABELS <- generate_label_df(TUKEY , "shp1$IUCN_CAT")
  LABELS$sorting<-c(1,2,3,4,5,9,8,10,6,7)
  LABELS<-LABELS[order(LABELS$sorting),]
  # A panel of colors to draw each group with the same color :
  my_colors <- c( 
    rgb(166,206,227,maxColorValue = 255),
    rgb(31,120,180,maxColorValue = 255),
    rgb(178,223,138,maxColorValue = 255),
    rgb(51,160,44,maxColorValue = 255),
    rgb(186,186,186,maxColorValue = 255),
    rgb(253,184,99,maxColorValue = 255)
  )

   over <- log(25+c)
 
   boxplot(log(shp1$ensamble_change+c)*-1~shp1$IUCN_CAT_NUM, axes=F,
          col=my_colors[as.numeric(LABELS[,1])],
          xlab="IUCN Category",
          ylab="percent TCF change 2001-2018",
          las=1,
          ylim=c(-3.5,0.1))
  
  axis(1, at=seq(1,10,1), labels=c("Ia","Ib","II","III","IV","V","VI","NA","NAp","NR"))
  
  yaxis<-c(log(5+c)*-1,log(2.5+c)*-1,log(0+c),log(2.5+c),log(5+c),log(10+c),log(25+c),log(50+c))*-1
  axis(2, at=yaxis, 
       labels=c("5","2.5","0","-2.5","-5","-10","-25","-50"))
  
  abline(h = 0, col="grey50", lwd=1, lty=2)
  box()

  #Add the labels
  text( seq(1,10,1) , log(0.12+c) , LABELS[,1]  , col=my_colors[as.numeric(LABELS[,1])] )

dev.off()














e2001<-raster("/nfs/lud/work/karger/cloud_forest_2001_2016/ensemble_2001l.sdat")
e2016<-raster("/nfs/lud/work/karger/cloud_forest_2001_2016/ensemble_2016l.sdat")
esd2001<-raster("/nfs/lud/work/karger/cloud_forest_2001_2016/ensemble_sd_2001l.sdat")
esd2016<-raster("/nfs/lud/work/karger/cloud_forest_2001_2016/ensemble_sd_2016l.sdat")

pdf("/mnt/storage/karger/cloudforest/cf_pa_areas_4.pdf",height=20,width=14)
for (n in 2034:2244)

{

shpx<-shp1[n,]
if(shpx@data$MARINE=="1"){next()}
  
c2001<-crop(e2001,extent(shpx))
c2016<-crop(e2016,shpx)
csd2001<-crop(esd2001,shpx)
csd2016<-crop(esd2016,shpx)


shpx_proj<-spTransform(shpx, crs("+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"))


st1_mean_c<-crop(st1_mean,shpx_proj)
st1_sd_c  <-crop(st1_sd,shpx_proj)

st1_plussd  <- st1_mean_c+st1_sd_c
st1_minussd <- st1_mean_c-st1_sd_c


st1_mean_c  <- st1_mean_c/10000
st1_plussd  <- st1_plussd/10000
st1_minussd <- st1_minussd/10000


ex_st1_mean     <- extract(st1_mean_c,  shpx_proj, fun=sum, na.rm=TRUE, df=TRUE)
ex_st1_plussd   <- extract(st1_plussd,  shpx_proj, fun=sum, na.rm=TRUE, df=TRUE)
ex_st1_minussd  <- extract(st1_minussd, shpx_proj, fun=sum, na.rm=TRUE, df=TRUE)


mn<-unlist(ex_st1_minussd)[2:length(ex_st1_minussd)]
mp<-unlist(ex_st1_plussd)[2:length(ex_st1_plussd)]
mm<-unlist(ex_st1_mean)[2:length(ex_st1_mean)]
mn<-100*mn/(max(mn))
mp<-100*mp/(max(mp))
mm<-100*mm/(max(mm))


ymin<-min(mn,mp,mm)
ymax<-max(mn,mp,mm)

pp1 <- ggplot(as.data.frame(cbind(xvect,mn,mp,mm)), aes(xvect,mn))+
                theme_classic() +
                scale_colour_manual(values = c("green")) +
                geom_line(aes(xvect,mm))+
                xlab("year") +
                ylab("percent cf area") +
                geom_ribbon(data=as.data.frame(cbind(xvect,mn,mp,mm)),aes(ymin=mn,ymax=mp),alpha=0.3,fill="green")


breaks<-c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
breaks2<-c(-0.05,-0.04,-0.03,-0.02,-0.01,0,0.01,0.02,0.03,0.04,0.05)
breakssd<-c(0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.1)
colors_1<-viridis(11)
colors_2<-c("#a50026",
  "#d73027",
  "#f46d43",
  "#fdae61",
  "#fee090",
  "#ffffbf",
  "#e0f3f8",
  "#abd9e9",
  "#74add1",
  "#4575b4",
  "#313695")
lp1<-levelplot(c2001,col.regions=colors_1,main="ensemble mean cf cover 2001",colorkey=list(space="bottom"),at=breaks,margin=FALSE,ylab="",xlab="percent cover/100",par.settings = list(layout.heights=list(xlab.key.padding=1)))+latticeExtra::layer(sp.polygons(shpx), packets = 1)
lp2<-levelplot(c2016,col.regions=colors_1,main="ensemble mean cf cover 2016",colorkey=list(space="bottom"),at=breaks,margin=FALSE,ylab="",xlab="percent cover/100",par.settings = list(layout.heights=list(xlab.key.padding=1)))+latticeExtra::layer(sp.polygons(shpx), packets = 1)

ranges<-max(abs(max(na.omit(values(csd2001)))),abs(min(na.omit(values(csd2001)))))
if(ranges==0){ranges<-0.01}
breaks_adjsd<-seq((ranges*-1),ranges,ranges*2/11)

lp1sd<-levelplot(csd2016,col.regions=inferno(11),main="ensemble sd cf cover 2001",colorkey=list(space="bottom"),at=breaks_adjsd,margin=FALSE,ylab="",xlab="percent cover/100",par.settings = list(layout.heights=list(xlab.key.padding=1)))+latticeExtra::layer(sp.polygons(shpx), packets = 1)
lp2sd<-levelplot(csd2016,col.regions=inferno(11),main="ensemble sd cf cover 2016",colorkey=list(space="bottom"),at=breaks_adjsd,margin=FALSE,ylab="",xlab="percent cover/100",par.settings = list(layout.heights=list(xlab.key.padding=1)))+latticeExtra::layer(sp.polygons(shpx), packets = 1)

cc<-(c2016-c2001)

ccsd<-c2016-csd2016-c2001+csd2001


ranges<-max(abs(max(na.omit(values(cc)))),abs(min(na.omit(values(cc)))))
breaks_adj1<-seq((ranges*-1),ranges,ranges*2/11)
ranges<-max(abs(max(na.omit(values(ccsd)))),abs(min(na.omit(values(ccsd)))))
breaks_adj2<-seq((ranges*-1),ranges,ranges*2/11)

lpcc  <-levelplot(cc,col.regions=colors_2,main="mean cf cover change",colorkey=list(space="bottom"),at=breaks_adj2,margin=FALSE,ylab="",xlab="percent cover/100",par.settings = list(layout.heights=list(xlab.key.padding=1)))+latticeExtra::layer(sp.polygons(shpx), packets = 1)
lpccsd<-levelplot(ccsd,col.regions=colors_2,main="mean+sd cf cover change",colorkey=list(space="bottom"),at=breaks_adj2,margin=FALSE,ylab="",xlab="percent cover/100",par.settings = list(layout.heights=list(xlab.key.padding=1)))+latticeExtra::layer(sp.polygons(shpx), packets = 1)

rdummy <- raster(xmn=-180, xmx=180, ymn=-40, ymx=40)
rdummy <- init(rdummy, runif)

x<-mean(coordinates(shpx)[,1])
y<-mean(coordinates(shpx)[,2])
xy<-data.frame(x,y)
xy$z<-1
coordinates(xy)<-~x+y

wwp<-rasterVis::levelplot(rdummy,col.regions="white",main="Location of protected area",margin=FALSE,ylab="",xlab="", colorkey=FALSE)+
  latticeExtra::layer(sp.polygons(wrld_simpl),packets=1)+
  latticeExtra::layer(sp.points(xy, pch=16, cex=1, col="red"),columns=1) 


c2001proj<-projectRaster(c2001,res=1000,crs= "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", method="bilinear")
c2016proj<-projectRaster(c2016,res=1000,crs= "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", method="bilinear")



ex2001 <- extract(c2001proj, shpx_proj, fun=sum, na.rm=TRUE, df=TRUE)
ex2016 <- extract(c2016proj, shpx_proj, fun=sum, na.rm=TRUE, df=TRUE)
exC    <- ex2016[2]-ex2001[2]
tgrob<-grid.text(paste0("WDPA_PID: ",shpx@data$WDPA_PID,"\n",
                        "ORIG_NAME: ",shpx@data$ORIG_NAME,"\n",
                        "NAME: ",shpx@data$NAME,"\n",
                        "DESIG_ENG: ",shpx@data$DESIG_ENG,"\n",
                        "COUNTRY: ",shpx@data$ISO3,"\n",
                        "IUCN_CAT: ",shpx@data$IUCN_CAT,"\n",
                        "REP_AREA: ",round(shpx@data$REP_AREA,2),"km_sqr\n",
                        "GIS_AREA: ",round(shpx@data$GIS_AREA,2),"km_sqr\n",
                        "%_CF_AREA_2001_OF_GIS_AREA: ",round(100*(ex2001[2])/(shpx@data$GIS_AREA),2),"\n",
                        "%_CF_AREA_2016_OF_GIS_AREA: ",round(100*(ex2016[2])/(shpx@data$GIS_AREA),2),"\n",
                        "cf_area_2001: ",round(ex2001[2],2),"km_sqr\n",
                        "cf_area_2016: ",round(ex2016[2],2),"km_sqr\n",
                        "cf_area_change: ",round(exC,2),"km_sqr\n"),
                        
                 just="center",draw=FALSE)

lay<-rbind(c(1,2),
           c(3,3),
           c(4,5),
           c(6,7),
           c(8,9))
gs<-list(tgrob,pp1,wwp,lp1,lp1sd,lp2,lp2sd,lpcc,lpccsd)

grid.arrange(grobs=gs,layout_matrix=lay)
}
dev.off()



