
# LOAD THE REQUIRED LIBRARIES
library(raster)
library(png)
library(scales)
library(plyr)
# SET FOLDER CONNECTIONS
INPUT <-"C:/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/data/"
OUTPUT<-"C:/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/output/"

# INPUT DATA
tc                  <- read.csv(paste0(INPUT,"cf_statistics_newid.txt"),header=T,sep="\t")
full                <- read.csv (paste0(INPUT,"vertsferns_by_cfID_speclist_101518_newid.csv"),sep=";")

#biodiv              <- read.csv(paste0(INPUT,"biodiversity_full.csv"),sep=";")
cf_contries_percent <- read.csv(paste0(INPUT,"cf_regions_countries_percent_newid.txt"),header=T,sep="\t")
contis              <- raster(paste0(INPUT,"continent.sdat"))

# do some data quentching on the input files
{
  CFRegCount_per_spec <- ddply(full, .(taxogroup,scientificname,cf_ass,cf_end), summarise, cfIDCount = length(na.omit(cf_id)))
  CFRegCountIsOne <- subset(CFRegCount_per_spec, cfIDCount ==1)
  
  CFSingleRegEndemicsInfo <- merge(CFRegCountIsOne, subset(full,select = c("scientificname","cf_id","CFRegionName","CFRegionContinent")),
                                   by = "scientificname", all.x= TRUE, all.y = FALSE)
  
  agg.cfEndemics <- ddply(CFSingleRegEndemicsInfo, .(cf_id, CFRegionName, CFRegionContinent, taxogroup), summarise,
                          EndSR.cf.assoc = sum(cf_ass),
                          EndSR.cf.restr = sum(cf_end))
  
  agg.cfEndemics <- agg.cfEndemics[order(-agg.cfEndemics$EndSR.cf.restr),]
  
  biodiv     <- ddply(full, .(cf_id, CFRegionName, CFRegionContinent, taxogroup), summarise,
                      cf_ass = sum(cf_ass),
                      cf_end = sum(cf_end))
}
namematching<-read.csv("Z:/karger/revision1/cf_namematching.csv")

pa_stat<- shapefile("Z:/karger/revision1/cloud_forest_regions_reshaped [ID]_v16.shp")
pa_stat<- as.data.frame(pa_stat)
pa_stat<- pa_stat[,-(c(2,3))]
colnames(pa_stat)[1]<-"ID"
pa_stat<- aggregate(x=pa_stat[,2:37],by=list(pa_stat$ID),FUN=function(x){sum(x)})
colnames(pa_stat)[1]<-"ID"
pa_stat<- merge(namematching,pa_stat,by.x="ID_new",by.y="ID")
pa_stat<- pa_stat[,-c(1,3,4)]

# file with cloud forest regions intersection with pa's tcf extent including all pa years
pa_stat_all<- shapefile("Z:/karger/revision1/Intersect [cloud_forest_regions_reshaped [ID]]-[Intersect_cfRegions_IUCN_cf [ID]]_v16.shp")
pa_stat_all<- as.data.frame(pa_stat_all)
pa_stat_all<- pa_stat_all[,-(c(2:6))]
pa_stat_all<- aggregate(x=pa_stat_all[,2:length(pa_stat_all[1,])],by=list(pa_stat_all$ID),FUN=function(x){sum(na.omit(x))})
colnames(pa_stat_all)[1]<-"ID"
pa_stat_all<- merge(namematching,pa_stat_all,by.x="ID_new",by.y="ID")
pa_stat_all<- pa_stat_all[,-c(1,3,4)]

pa_stat_un      <-pa_stat[,2:19]-pa_stat_all[,2:19]
pa_stat_un$ID   <-pa_stat_all$ID
pa_stat_un<-cbind(pa_stat_un[length(pa_stat_un[1,])],pa_stat_un[,2:(length(pa_stat_un[1,])-1)])

pa_stat_un_sd    <-pa_stat_all[,20:37]
pa_stat_un_sd$ID <-pa_stat_all$ID
pa_stat_un_sd    <-cbind(pa_stat_un_sd[length(pa_stat_un_sd[1,])],pa_stat_un_sd[,2:(length(pa_stat_un_sd[1,])-1)])

pa_stat_pa      <-pa_stat_all[,2:19]
pa_stat_pa$ID   <-pa_stat_all$ID
pa_stat_pa      <-cbind(pa_stat_pa[length(pa_stat_pa[1,])],pa_stat_pa[,2:(length(pa_stat_pa[1,])-1)])

pa_stat_pa_sd    <-pa_stat_all[,20:37]
pa_stat_pa_sd$ID <-pa_stat_all$ID
pa_stat_pa_sd    <-cbind(pa_stat_pa_sd[length(pa_stat_pa_sd[1,])],pa_stat_pa_sd[,2:(length(pa_stat_pa_sd[1,])-1)])

######################################################################################################################################################################################
{
  # DATA PREPARATION
  {
  tc2<-tc
  tc2=cbind(tc2[,1:2],tc2[,3:98]/1000)
  tc_pr<-cbind(tc2[,1:2],(tc2[,3:18]+tc2[,35:50]+tc2[,67:82])/3)
  tc_un<-cbind(tc2[,1:2],(tc2[,19:34]+tc2[,51:66]+tc2[,83:98])/3)
  tc_un[is.na(tc_un)]<-1
  tc_pr[is.na(tc_pr)]<-1
  
  tc_un_pr<-cbind(tc_un[,1:2],100*(tc_un[,3:18]/tc_un[,3]))
  tc_pr_pr<-cbind(tc_pr[,1:2],100*(tc_pr[,3:18]/tc_pr[,3]))
  
  col1<-rgb(51/255, 51/255, 255/255, alpha=1)
  col2<-rgb(255/255, 153/255, 0, alpha=1)
  tc3<-cbind(tc_un[,1:2],tc_un[,3:18],tc_pr[,3:18])
  tc3[,3:34][tc3[,3:34]<=1]<-1

  tc3<-tc3[order(tc3$gam_3_cf_un_2001..SUM.+tc3$gam_3_cf_pr_2001..SUM.),]
  #tc3<-tc3[6:64,]
  }
    regionnames<-tc3[,1:2]
  


  pa_stat1<-merge(pa_stat_pa,pa_stat_un,by="ID")
  pa_stat1[,2:length(pa_stat1[1,])]<-pa_stat1[,2:length(pa_stat1[1,])]/1000
  pa_stat1<-merge(pa_stat1,regionnames,by="ID")

 # tc3<-tc3[-c(3:34)]
  # PLOT THE CONTINENT INLET
  {
  png(paste0(OUTPUT,"barplot_cf_regions_continents.png"),height = 400, width = 1000)
  contis<-raster(paste0(INPUT,"continent.sdat"))
  col_Af<-rgb(27/255,158/255,119/255)
  col_Am<-rgb(217/255,95/255,2/255)
  col_As<-rgb(0,0,0)
  image(contis,col=c(col_As,col_Am,"grey",col_Af,col_Am,col_As,col_As),ylab="",xlab="",frame.plot=F,axes=F)
  dev.off()
  }
  
  # CREATE THE BARPLOTS
  {
  pdf(paste0(OUTPUT,"Fig3_r2.pdf"),height = 8, width = 10)
  mm=0.25
  col1<-alpha("white")
  col2<-alpha("grey35",1)
  
  par(mfrow=c(1,2),mai=c(1,1.2,0.5,0.5),lend=1)
  {  
    allspecs<-aggregate(cf_ass~cf_id,sum,data=biodiv)
    endemics<-aggregate(cf_end~cf_id,sum,data=biodiv)
    tc3 <-merge(pa_stat1,allspecs,by.x="ID",by.y="cf_id")
    tc3 <-merge(tc3,endemics,by.x="ID",by.y="cf_id")


    tt<-merge(tc3,full,by.x="ID",by.y="cf_id",all=F)
    ttid<-tt[!duplicated(tt$ID),]
    tc3$continents<-ttid$CFRegionContinent
    
    tc3 <-tc3[order(tc3$tcf_ensembl.1.x+tc3$tcf_ensembl.1.y),]
    tc3$specloss<-tc3$cf_ass*(1-((tc3$tcf_ensembl.17.x+tc3$tcf_ensembl.17.y)/(tc3$tcf_ensembl.1.x+tc3$tcf_ensembl.1.y))^0.5)
    tc3 <-tc3[order(tc3$specloss, decreasing = FALSE),]
    tc3 <-tc3[complete.cases(tc3),]
    unp2001<-tc3$tcf_ensembl.1.y
    pro2001<-tc3$tcf_ensembl.1.x
    unp2016<-tc3$tcf_ensembl.17.y
    pro2016<-tc3$tcf_ensembl.17.x
    cpro   <-pro2001-pro2016
    cunp   <-unp2001-unp2016
    cpro_p <-100*(cpro/(pro2001+unp2001))
    cunp_p <-100*(cunp/(unp2001+pro2001))
   
    # SETTING THE COLORS
    col_Af<-rgb(27/255,158/255,119/255)
    col_Am<-rgb(217/255,95/255,2/255)
    col_As<-rgb(0,0,0)
    tc3$continents<-as.character(tc3$continents)
    tc3$continents[tc3$continents=="Africa"]<-col_Af
    tc3$continents[tc3$continents=="Americas"]<-col_Am
    tc3$continents[tc3$continents=="Asia-Pacific"]<-col_As

    
    # PLOT THE LEFT SIDE OF THE FIGURE    
    greysbg<-cunp_p
    colos<-rep(c("white","grey95"),length(greysbg)/2)
    greysbg[]<-(max(na.omit((tc3$tcf_ensembl.1.y+tc3$tcf_ensembl.1.x)/10)))
    df_bg<-barplot(greysbg,horiz=T,col=colos, border=colos,main="",axes=F)
    greysbg[]<-(max(na.omit(tc3$tcf_ensembl.1.y+tc3$tcf_ensembl.1.x)))*(1)    
    greys<-rgb(1,1,1,alpha="0.65")

    df_bg<-barplot(greysbg,horiz=T,col=colos, border=colos,main="",axes=F,add=T)
    df.bar <-barplot(((tc3$tcf_ensembl.1.y+tc3$tcf_ensembl.1.x)/10),horiz=T, main="",col=col1, border=col2,las=1,cex.names=0.6,axes=F,xlab=expression("TCF area ("~"km"^"2"~")"),add=T)
    axis(side=1, at=axTicks(1), 
         labels=formatC(axTicks(1), format="d", big.mark=','))
    barplot((tc3$tcf_ensembl.1.x/10),horiz=T, col=col2, border=col2,add=T,axes=F)
    
    # ADD THE CONTINENTS
    require(png)
    par(xpd=NA)
    img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/barplot_cf_regions_continents.png")
    rasterImage(img,80000,-10,125000,-3)
    par(xpd=TRUE)
    
    par(xpd=NA)
    #text(0,max(df.bar)+5,"(a)",cex=1.5)
    par(xpd=TRUE)
  
    
    cf_contries_percent<-cf_contries_percent[rowSums(cf_contries_percent[,2:(length(cf_contries_percent[1,]))])>0,]
    cf_countries<-c()
    for(id in unique(cf_contries_percent$ID))
    {
      df_sub<-cf_contries_percent[cf_contries_percent$ID==id,]
      df_sub<-df_sub[,2:length(df_sub[1,])]
      cids <-colnames(df_sub)[df_sub>=10]
      percs<-df_sub[df_sub>=10]
      cf_countries<-rbind(cf_countries,cbind(id,cids,percs))
    }
    cf_countries<-as.data.frame(cf_countries)
    colnames(cf_countries)<-c("cf_id","country","percs")
    
    for (n in 1:length(tc3[,1]))
    {
      m<-tc3[n,1]
      
      countrys<-cf_countries$country[cf_countries$cf_id==m]
      percen  <-cf_countries$percs[cf_countries$cf_id==m]
      nnn<-c()
      nnp<-c()
      for (nn in unique(countrys))
      {
        np <-percen[countrys==nn]
        nnn<-paste0(nnn,",",nn,"(",np,")")
      }
      nnn<-substring(nnn,2)
      lll<-rev(seq(1:length(tc3[,1])))
      xx=(((tc3$tcf_ensembl.1.x+tc3$tcf_ensembl.1.y)/10)*(1))[n]
      yy=df.bar[n]
      post=2
      col5="black"
      if(xx<=60000){post<-4}
      #if(xx<=(-4)){col5<-"white"}
      text(nnn,x=xx,y=yy,cex=0.48,pos=post,col=col5)
      
    }
    
    text(45000,min(df.bar)-10,as.expression(bquote("2001 TCF area (" ~ km^2 ~ ")")),cex=1)
    
    
    
    
    # PLOT THE RIGHT SIDE OF THE FIGURE
    greysbg<-cunp_p
    greysbg[]<-(-8)
    colos<-rep(c("white","grey95"),length(greysbg)/2)
    
    df_bg<-barplot(greysbg,horiz=T,col=colos, border=colos,main="",axes=F)
    
    par(xpd=TRUE)
    greysbg[]<-(-2000)
    df_bg<-barplot(greysbg,horiz=T,col=colos, border=colos,main="",axes=F,add=T)
    
    loosing<-cbind(tc3$ID,100*(tc3$tcf_ensembl.1.x+tc3$tcf_ensembl.1.y)/(tc3$tcf_ensembl.17.x+tc3$tcf_ensembl.17.y))
    loosing<-as.data.frame(loosing)
    colnames(loosing)<-c("id","loss")
    
    df_bar1<-barplot((cunp_p+cpro_p)*(-1),horiz=T,col=col1, border=col2,main="",axes=F,xlab=expression("TCF loss"),add=T)
    barplot((cunp_p)*(-1),horiz=T,col=col2, border=col2,main="",axes=F,add=T)
    axis(side=1, at=axTicks(1), 
         labels=c("-8%","-6%","-4%","-2%","0%"))
   
    
   
    legend(5,max(df_bar1)+6,c("protected","unprotected"),col=c(col1,col2),pch = 15,border = col2,bty="n")
    specloss<-tc3$cf_ass.x*(1-((tc3$tcf_ensembl.17.x+tc3$tcf_ensembl.17.y)/(tc3$tcf_ensembl.1.x+tc3$tcf_ensembl.1.y))^0.5)
    
    for (z in seq(0.1,1,0.01))
    {
      assign(paste0("specloss",z),tc3$cf_ass*(1-((tc3$tcf_ensembl.17.x+tc3$tcf_ensembl.17.y)/(tc3$tcf_ensembl.1.x+tc3$tcf_ensembl.1.y))^z))
    }  
 
    colL=rgb(85/255, 26/255, 139/255,alpha=0.005)
    colF=rgb(85/255, 26/255, 139/255,alpha=1)
    for(yval in 1:length(df.bar))
    {
      zz1<-seq(0.1,1,0.01)
      zz2<-rev(seq(0.1,1,0.01))
      for (z in 1:length(zz1))
      {
        z1<-zz1[z]
        z2<-zz2[z]
        zv1<-get(paste0("specloss",z1))
        zv2<-get(paste0("specloss",z2))
        lines(y=c(df.bar[yval],df.bar[yval]),x=c(zv1[yval]*mm*(-1),zv2[yval]*mm*(-1)),col=colL,lwd=10)
      }
    }
    points(y = df.bar, x = specloss0.5*mm*(-1),pch=15,col=colF,cex=1.2)
    points(y = df.bar, x = specloss0.5*mm*(-1),pch="|",col="white",cex=0.7)
    
    #text(-10,max(df_bar1)+5,"(b)",cex=1.5)

    ticklabels<-paste0(gsub("_"," ",tc3$Name)," (",as.character(tc3$ID),")")
    par(xpd=NA)
    for (n in 1:length(ticklabels))
    {
      y=df.bar[n]
      x=(-10)
      col=tc3$continents[n]
      text(x=x,y=y,ticklabels[n],col=col,cex=0.7)
    }
    par(xpd=TRUE)
    
    axis(side=3,c(0,-5*mm,-10*mm,-15*mm,-20*mm,-25*mm,-30*mm),labels = c(0,-5,-10,-15,-20,-25,-30),cex.axis=0.95)
    text(-4,max(df.bar)+2,"Expected species loss")
    
    text(-4,min(df_bar1)-10,as.expression(bquote("TCF loss")),cex=1)
    
  }
  dev.off()   
  }
}
#################################################################################################################################################################################################  
