### Turnover plots 
library(labdsv)
library(vegan)
library(raster)
library(png)
library(viridis)
INPUT <-"/home/karger/Documents/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/data/"

df1 <- read.csv (paste0(INPUT,"vertsferns_by_cfID_speclist_101518_newid.csv"),sep=";")
shape_path       <- "/mnt/lud11/karger/natural_earth_vector/50m_physical/"
shape_path2       <- "/mnt/lud11/karger/natural_earth_vector/"


########### PLOT THE JACCARD AS MAPS  
coast_shapefile  <- shapefile(paste0(shape_path, "/ne_50m_coastline.shp"))
ocean_shapefile  <- shapefile(paste0(shape_path, "/ne_50m_ocean.shp"))
admin0_shapefile <- shapefile(paste0(shape_path2, "/50m_cultural/ne_50m_admin_0_countries.shp"))
admin1_shapefile <- shapefile(paste0(shape_path2, "/50m_cultural/ne_50m_admin_1_states_provinces_lakes.shp"))
lakes_shapefile  <- shapefile(paste0(shape_path, "/ne_50m_lakes.shp"))
bb_shapefile     <- shapefile(paste0(shape_path, "ne_50m_graticules_all/ne_50m_wgs84_bounding_box.shp"))
grat30_shapefile <- shapefile(paste0(shape_path, "ne_50m_graticules_all/ne_50m_graticules_30.shp"))

unproj_crs         <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
robin_crs          <- CRS("+proj=robin +lon_0=0w")

bb_poly_proj       <- spTransform(bb_shapefile, robin_crs)
coast_lines_proj   <- spTransform(coast_shapefile, robin_crs)
admin0_poly_proj   <- spTransform(admin0_shapefile, robin_crs)
admin1_poly_proj   <- spTransform(admin1_shapefile, robin_crs)
lakes_poly_proj    <- spTransform(lakes_shapefile, robin_crs)
grat30_lines_proj  <- spTransform(grat30_shapefile, robin_crs)
ocean_proj         <- spTransform(ocean_shapefile, robin_crs)


pp    <- read.table(paste0(INPUT,"pp.txt"),header=T)
coordinates(pp)<-~x+y
coords<- coordinates(pp)
pp    <- pp[,1:2]
pp@proj4string@projargs<-"+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
pp_proj            <- spTransform(pp,robin_crs)

cf_id_new<-read.csv("/home/karger/Documents/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/data/cf_id_new.txt",sep="\t")
tcf_regions <- shapefile("/mnt/lud11/karger/cloudforest_loss/tcf_region_boundaries.shp")
line_numbers<- shapefile("/mnt/lud11/karger/cloudforest_loss/lines_numbers.shp")
line_numbers<- spTransform(line_numbers,robin_crs)
tcf_regions <- merge(tcf_regions,cf_id_new,by.x="ID",by.y="cf_id")
tcf_proj    <- spTransform(tcf_regions,robin_crs)
ll    <- shapefile(paste0(INPUT,"cloudforest_regions_lines.shp"))
ll@proj4string@projargs<-"+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
ll    <- spTransform(ll,robin_crs)


pdf("/home/karger/Documents/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/output/fig_SJaccard_groups2ass.pdf",height=10,width=20)
par(mfrow=c(2,2),mar=c(1,5,2,0),oma=c(0,0,0,0))
for (group in unique(df1$taxogroup))
{
  
## calculate dissimilarites
{
dfx <- df1[df1$taxogroup==group,]
df2 <- data.frame(matrix(ncol = 3, nrow = length(dfx$cf_id)))
colnames(df2)<-c("cf_id","species","occurence")
df2$cf_id<-as.character(df2$cf_id)
df2$species<-as.character(df2$species)
df2$occurence<-as.integer(df2$occurence)
df2$cf_id <- dfx$cf_id
df2$species<-dfx$scientificname
df2$occurence<-dfx$cf_ass

mat2<- matrify(df2)

dis <- vegdist(mat2, method="jaccard",binary=T,diag=F,na.rm = FALSE)
dis <- as.matrix(dis)
dis[dis==0]<-1
dis <- apply(dis,1,min)

# merge with jaccard
dis<-as.data.frame(dis)
colnames(dis)<-c("jaccard")
dis$cf_id<-rownames(dis)
tcf_proj    <- spTransform(tcf_regions,robin_crs)

tcf_proj <- merge(tcf_proj,dis,by.x="cf_id_new",by.y="cf_id")
disp <- SpatialPoints(tcf_proj)
disp$jaccard <- tcf_proj$jaccard

plot(bb_poly_proj)
plot(ocean_proj,col="white",add=T)
plot(admin0_poly_proj,col = "grey80", border="grey80",add=T)
#plot(tcf,col="black",add=T)
plot(grat30_lines_proj,add=T,col="grey50",lty="dotted")
#plot(ll,add=T)
disp$Col <- plasma(12)[as.numeric(cut(disp$jaccard,breaks = 11))]
points(disp,cex=disp$jaccard*7,pch=1,col=disp$Col,lwd=3)
plot(bb_poly_proj,add=T)

label<-as.character(seq(1,60,1))
par(xpd=TRUE)
#text(pp_proj,labels=label,cex=1)
text(x=0,y=9400000,  group ,cex=3)
}
if(group == "Mammals")
{
img_mammals<-readPNG("/home/karger/Documents/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/mammals2.png")
rasterImage(img_mammals,-18000000,4000000,-12000000,11000000)
}
if(group == "Birds")
{
img_birds  <-readPNG("/home/karger/Documents/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/birds.png")
rasterImage(img_birds,-19500000,5000000,-15000000,11000000)
for (n in 1:6)
{
  legend_p <- c(0.001,0.2,0.4,0.6,0.8,1)
  legend_c <- c("0","0.2","0.4","0.6","0.8","1")
  legend_x <- rep(-19000000,6)
  legend_y <- rep(-9000000,6)
  legend_yPLUS <- c(0,1000000,2000000,3300000,4650000,6500000)
  legend_col<-plasma(12)[as.numeric(cut(legend_p,breaks = 11))]
  points(x=legend_x[n],y=legend_y[n]+legend_yPLUS[n],cex=legend_p[n]*7,col=legend_col[n],lwd=3)
  text(x=legend_x[n]-900000,y=legend_y[n]+legend_yPLUS[n],legend_c[n],cex=1.5,pos=2)
}
text(x=-21500000,y=-3000000,"Dissimilarity",srt=90,cex=1.5,pos=2)

}
if(group == "Cyatheaceae")
{
img_treefern<-readPNG("/home/karger/Documents/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/treeferns.png")
rasterImage(img_treefern,-18000000,6000000,-15000000,10000000)
}
if(group == "Amphibians")
{
img_amphi  <-readPNG("/home/karger/Documents/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/amphibians.png")
rasterImage(img_amphi,-18000000,6000000,-15000000,10000000)
}
par(xpd=FALSE)
}
dev.off()


##### Scatterplots for area
# SET FOLDER CONNECTIONS
library(plyr)
library(ggpubr)
library(grid)
library(gridExtra)
library(lattice)
library(scales)
library(png)
# data prep
{
INPUT <-"C:/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/data/"
OUTPUT<-"C:/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/output/"

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=";")

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))



pp    <- read.table(paste0(INPUT,"pp.txt"),header=T)
coordinates(pp)<-~x+y
coords<- coordinates(pp)
pp    <- pp[,1:2]


# biodiv
biodiv<- merge(biodiv,pp,by.x="cf_id",by.y="ID")

tc2<-tc

tcx<-merge(biodiv,tc2,by.y="ID",by.x="cf_id")
tcx[is.na(tcx)]<-0
tcx$tcf_2001<-(as.double(tcx$gam_3_cf_pr_2001..SUM.)+as.double(tcx$gam_3_cf_un_2001..SUM.)+as.double(tcx$glm_bino_3_cf_pr_2001..SUM.)+as.double(tcx$glm_bino_3_cf_un_2001..SUM.)+as.double(tcx$glm_pois_3_cf_pr_2001..SUM.)+as.double(tcx$glm_pois_3_cf_un_2001..SUM.))/3

tcx$tcf_2001<-tcx$tcf_2001/10000
}


cols<-c(alpha("goldenrod1", 0.5), alpha("royalblue4", 0.5), alpha("darkgreen",0.5), alpha("firebrick",0.5))
groups = c("Mammals","Birds","Cyatheaceae","Amphibians")
for (n in 1:4)
{
group=groups[n]
df_g<-tcx[tcx$taxogroup==group,]
df_g<-as.data.frame(cbind(df_g$cf_ass,df_g$tcf_2001,df_g$cf_id))
colnames(df_g)<-c("species_richness","TCF_area","cf_id")
df_g$species_richness<-log(df_g$species_richness)
df_g$TCF_area<-log(df_g$TCF_area)
maxy<-(max(df_g$species_richness))+(max(df_g$species_richness))/4
#if(maxy<=1){maxy=1}
maxyy<-maxy-maxy/50
title1<-""
title2<-""
if(group == "Mammals")
{
  title1<-"associated"
  title2<-"strict"
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/mammals2.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=1
  gxmax=4
  gymin=4.5
  gymax=6
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","   100","1,000")
}
if(group == "Birds")
{
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/birds.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=0.1
  gxmax=6
  gymin=5
  gymax=8
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","100","1,000")
}
if(group == "Cyatheaceae")
{
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/treeferns.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=.1
  gxmax=4.5
  gymin=3.5
  gymax=5
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","   100","1,000")
}
if(group == "Amphibians")
{
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/amphibians.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=0.5
  gxmax=4
  gymin=6
  gymax=8
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","100","1,000")
}

assign(paste0('ass',n),ggscatter(df_g, x = "TCF_area", y = "species_richness", 
                                color = cols[n], shape = 19, size = 2, # Points color, shape and size
                                repel = TRUE,
                                label = "cf_id",
                                title = title1,
                                add.params = list(color = cols[n], fill = cols[n]), # Customize reg. line
                                conf.int = TRUE, # Add confidence interval
                                xlab = "", ylab = "",ylim=c(0,maxy))
          + font("title", size = 22, color = "black")
          + annotation_custom(g, xmin=gxmin, xmax=gxmax, ymin=gymin, ymax=gymax)
          + scale_x_continuous(breaks = c(log(10),log(100),log(1000),log(10000),log(100000)),
                               labels = c("10","100","1,000","10,000","100,000"))
       + scale_y_continuous(breaks = breaks1,
                            labels = labels1)
)
                
      
ass1

df_g<-tcx[tcx$taxogroup==group,]
df_g<-as.data.frame(cbind(df_g$cf_end,df_g$tcf_2001,df_g$cf_id))
colnames(df_g)<-c("species_richness","TCF_area","cf_id")
df_g$species_richness<-log(df_g$species_richness)
df_g$TCF_area<-log(df_g$TCF_area)
assign(paste0('str',n),ggscatter(df_g, x = "TCF_area", y = "species_richness", 
                                 color = cols[n], shape = 19, size = 2, # Points color, shape and size
                                 repel = TRUE,
                                 label = "cf_id",
                                 title = title2,
                                 add.params = list(color = cols[n], fill = cols[n]), # Customize reg. line
                                 conf.int = TRUE, # Add confidence interval
                                 xlab = "", ylab = "",ylim=c(0,maxy))
       
       + font("title", size = 22, color = "black")
       + scale_x_continuous(breaks = c(log(10),log(100),log(1000),log(10000),log(100000)),
                            labels = c("10","100","1,000","10,000","100,000"))
       + scale_y_continuous(breaks = breaks1,
                            labels = labels1)
       
)
str1
}


gs<-list(ass1,str1,ass2,str2,ass3,str3,ass4,str4)
pdf(paste0(OUTPUT,"Fig_SX_species_area.pdf"),height=16,width=10)
margin = theme(plot.margin = unit(c(0,1.1,0,0), "cm"))
gs = lapply(gs, "+", margin)

grid.arrange(grobs=gs, ncol=2, 
             top=c(""), bottom=textGrob(bquote("TCF area ("~km^2*")"), gp=gpar(fontsize=24)), 
             left=textGrob("species richness", gp=gpar(fontsize=24),rot=90),right=textGrob("", gp=gpar(fontsize=24),rot=90))
dev.off()




