#### do analysis on time dependency
library(raster)

df1<-shapefile("Z:/karger/cloudforest_loss/WDPA_Dec2016-shapefile-polygons_TCF_v16.shp")
dfx1<-as.data.frame(df1)
dfx1<-dfx1[complete.cases(dfx1),]
dfx1<-dfx1[dfx1$ensembl!=0,]
write.table(dfx1,"Z:/karger/cloudforest_loss/Supplementary_table2.txt",sep=",")

dfx<-as.data.frame(df1)
dfx$STATUS_YR<-as.numeric(as.character(dfx$STATUS_YR))
dfx<-dfx[dfx$STATUS_YR>=2002,]
dfx<-dfx[dfx$'tcf_ensembl'>=0.000001,]
dfx<-dfx[dfx$STATUS=="Designated",]
dfx<-dfx[!is.na(dfx$'tcf_ensembl'),]

calc_rates_obs<-function(x){
  b<-c()
  for (m in 1:(length(x)-1))
  {
    a<-x[m]-x[m+1]
    b<-c(b,a)
  }
  mb<-mean(b)
  rat<-100*mb/x[1]
  return(rat*(-1))
}

n=1
start_yr_v<-c()
rat_v_obs<-c()
rat_sd_upper<-c()
rat_sd_lower<-c()

prot_rat<-c()
unpr_rat<-c()
year_v<-c()
for (n in 1:length(dfx[,1]))
{
  vect<-dfx[n,29:46]
  names(vect)<-seq(2001:2018)
  stat_yr<-dfx$STATUS_YR[n]
  
  unpr<-unlist(vect[names(vect)<=stat_yr])
  prot<-unlist(vect[names(vect)>stat_yr])

  lm_unpr<-calc_rates_obs(unpr)
  lm_prot<-calc_rates_obs(prot)
  
  diff<-lm_prot-lm_unpr
  start_yr_v<-c(start_yr_v,stat_yr)
  rat_v_obs<-c(rat_v_obs,diff)
  
  prot_rat<-c(prot_rat,lm_prot)
  unpr_rat<-c(unpr_rat,lm_unpr)
  
  year_v<-c(year_v,stat_yr)
}

prot_unprot<-cbind(prot_rat,unpr_rat,year_v)
prot_unprot<-prot_unprot[year_v!=2019,]
prot_unprot<-as.data.frame(prot_unprot)

# Define colour pallete
pal = viridis(15)
# Use the following line with RColorBrewer

# Rank variable for colour assignment
prot_unprot$order = findInterval(prot_unprot$year_v, sort(prot_unprot$year_v))

# Make plot
pdf("Z:/lud11/karger/cloudforest_loss/pa_establish_v16.pdf",height=7,width = 7)
{
plot(prot_unprot$prot ~ prot_unprot$unpr, prot_unprot, pch=19, col=viridis(nrow(prot_unprot))[prot_unprot$order],ylim=c(-3,0.5),xlim=c(-3,0.5)
     , ylab="TCF loss after PA designation [%]",xlab="TCF loss before PA designation [%]")
abline(0,1,col="firebrick")
# Add a simple legend
legend("bottomright", col=viridis(15), pch=19,
       legend=sort(unique(prot_unprot$year_v)))
}

dev.off()





