##################
### REANALISYS ###
### 01 May 2021 ##
##################

rm(list = ls())
sample(1:.Machine$integer.max, 1) # This command had generated the value 1487175758 to be used as set.seed(1487175758) to get reproducible results


################
### PACKAGES ###
################

library(vegan)
library(plyr)
library(iNEXT)
library(ggplot2)
library(gridExtra)
library(reshape2)
library(eulerr)


#############
### DADOS ###
#############

# importa a matriz de dados baseada nos dados brutos
matrix = read.csv("mammalData.csv")

# importa as coordenadas das trilhas
coordinates = read.csv("siteCoordinates.csv", row.names = 1)

# exclui a especie Didelphis imperfecta
matrix$Didelphis_imperfecta = NULL

# renomeia o municipio Porto_Grande para Tartarugalzinho, pois ambos constituem um par de sitios (i.e. uma das quatro area de estudo)
matrix$municipio[matrix$municipio == "Porto_Grande"] = "Tartarugalzinho"
matrix = droplevels(matrix)

# combina (soma) os dados de segmentos em trilhas
trilhas = aggregate(matrix[7:ncol(matrix)],
                    by = list(municipio = matrix$municipio,
                              ambiente = matrix$ambiente,
                              trilha = matrix$trilha2,
                              locationID = matrix$trilha3),
                    FUN = sum)

# seleciona somente trilhas (locationID) com coordenadas geograficas
trilhas$analisar = match(trilhas$locationID,
                         rownames(coordinates),
                         nomatch = 0)
trilhas = subset(trilhas, analisar != 0)

# nomeia as linhas
rownames(trilhas) = trilhas$locationID

# exclui as colunas "locationID" e "analisar"
trilhas$locationID = NULL
trilhas$analisar = NULL

# separa os dados por area de estudo
alm = subset(trilhas, municipio == "Almeirim")
alm = droplevels(alm)

moj = subset(trilhas, municipio == "Moju")
moj = droplevels(moj)

par = subset(trilhas, municipio == "Paragominas")
par = droplevels(par)

tar = subset(trilhas, municipio == "Tartarugalzinho")
tar = droplevels(tar)


###############
### RIQUEZA ###
###############

# PREPARACAO DOS DADOS
# combina (soma) os dados de trilhas em ambientes
# Almeirim
alm.ambientes = aggregate(alm[5:ncol(alm)],
                          by = list(ambiente = alm$ambiente),
                          FUN = sum)
rownames(alm.ambientes) = alm.ambientes$ambiente
alm.ambientes = alm.ambientes[-1]

# Moju
moj.ambientes = aggregate(moj[5:ncol(moj)],
                          by = list(ambiente = moj$ambiente),
                          FUN = sum)
rownames(moj.ambientes) = moj.ambientes$ambiente
moj.ambientes = moj.ambientes[-1]

# Paragominas
par.ambientes = aggregate(par[5:ncol(par)],
                          by = list(ambiente = par$ambiente),
                          FUN = sum)
rownames(par.ambientes) = par.ambientes$ambiente
par.ambientes = par.ambientes[-1]

# Tartarugalzinho + Porto_Grande
tar.ambientes = aggregate(tar[5:ncol(tar)],
                          by = list(ambiente = tar$ambiente),
                          FUN = sum)
rownames(tar.ambientes) = tar.ambientes$ambiente
tar.ambientes = tar.ambientes[-1]

# Adequa os dados no formato a ser utilizado na funcao iNEXT
# Almeirim
alm.raref = alm.ambientes[colSums(alm.ambientes) > 0]
alm.raref = as.data.frame(t(alm.raref))
alm.raref$relict = ifelse(alm.raref$PF != 0, alm.raref$SF, 0)

# Moju
moj.raref = moj.ambientes[colSums(moj.ambientes) > 0]
moj.raref = as.data.frame(t(moj.raref))
moj.raref$relict = ifelse(moj.raref$PF != 0, moj.raref$OP, 0)

# Paragominas
par.raref = par.ambientes[colSums(par.ambientes) > 0]
par.raref = as.data.frame(t(par.raref))
par.raref$relict = ifelse(par.raref$PF != 0, par.raref$LF, 0)

# Tartarugalzinho + Porto_Grande
tar.raref = tar.ambientes[colSums(tar.ambientes) > 0]
tar.raref = as.data.frame(t(tar.raref))
tar.raref$relict = ifelse(tar.raref$PF != 0, tar.raref$EP, 0)


####################################
### Numero rarefeito de especies ###
####################################

# Almeirim
set.seed(1487175758)
alm.inext = iNEXT(alm.raref, q = 0, datatype = "abundance",
                  size = NULL,
                  endpoint = max(colSums(alm.raref)),
                  knots = max(colSums(alm.raref)),
                  se = TRUE, conf = 0.95, nboot = 1000)

alm.richness = rbind(alm.inext$iNextEst$PF,
                     alm.inext$iNextEst$SF,
                     alm.inext$iNextEst$relict)

alm.richness$habitat = c(rep("a.Primary forest",
                             nrow(alm.inext$iNextEst$PF)),
                         rep("b.Secondary forest (total species)",
                             nrow(alm.inext$iNextEst$SF)),
                         rep("c.Secondary forest (primary forest species)",
                             nrow(alm.inext$iNextEst$relict)))

alm.richness = alm.richness[, c(1, 2, 4, 5, 6, 7, 10)]

# Moju
set.seed(1487175758)
moj.inext = iNEXT(moj.raref, q = 0, datatype = "abundance",
                  size = NULL,
                  endpoint = max(colSums(moj.raref)),
                  knots = max(colSums(moj.raref)),
                  se = TRUE, conf = 0.95, nboot = 1000)

moj.richness = rbind(moj.inext$iNextEst$PF,
                     moj.inext$iNextEst$OP,
                     moj.inext$iNextEst$relict)

moj.richness$habitat = c(rep("a.Primary forest",
                             nrow(moj.inext$iNextEst$PF)),
                         rep("b.Oil palm plantation (total species)",
                             nrow(moj.inext$iNextEst$OP)),
                         rep("c.Oil palm plantation (primary forest species)",
                             nrow(moj.inext$iNextEst$relict)))

moj.richness = moj.richness[, c(1, 2, 4, 5, 6, 7, 10)]

# Paragominas
set.seed(1487175758)
par.inext = iNEXT(par.raref, q = 0, datatype = "abundance",
                  size = NULL,
                  endpoint = max(colSums(par.raref)),
                  knots = max(colSums(par.raref)),
                  se = TRUE, conf = 0.95, nboot = 1000)

par.richness = rbind(par.inext$iNextEst$PF,
                     par.inext$iNextEst$LF,
                     par.inext$iNextEst$relict)

par.richness$habitat = c(rep("a.Primary forest",
                             nrow(par.inext$iNextEst$PF)),
                         rep("b.Logged forest (total species)",
                             nrow(par.inext$iNextEst$LF)),
                         rep("c.Logged forest (primary forest species)",
                             nrow(par.inext$iNextEst$relict)))

par.richness = par.richness[, c(1, 2, 4, 5, 6, 7, 10)]

# Tartarugalzinho + Porto_Grande
set.seed(1487175758)
tar.inext = iNEXT(tar.raref, q = 0, datatype = "abundance",
                  size = NULL,
                  endpoint = max(colSums(tar.raref)),
                  knots = max(colSums(tar.raref)),
                  se = TRUE, conf = 0.95, nboot = 1000)

tar.richness = rbind(tar.inext$iNextEst$PF,
                     tar.inext$iNextEst$EP,
                     tar.inext$iNextEst$relict)

tar.richness$habitat = c(rep("a.Primary forest",
                             nrow(tar.inext$iNextEst$PF)),
                         rep("b.Eucalypt plantation (total species)",
                             nrow(tar.inext$iNextEst$EP)),
                         rep("c.Eucalypt plantation (primary forest species)",
                             nrow(tar.inext$iNextEst$relict)))

tar.richness = tar.richness[, c(1, 2, 4, 5, 6, 7, 10)]


###################################
### Numero estimado de especies ###
###################################

# Almeirim
set.seed(1487175758)
almD = estimateD(alm.raref, datatype = "abundance",
                 base = "coverage", level = NULL, conf = 0.95)
almD = subset(almD, order == 0)

# Moju
set.seed(1487175758)
mojD = estimateD(moj.raref, datatype = "abundance",
                 base = "coverage", level = NULL, conf = 0.95)
mojD = subset(mojD, order == 0)[c(2, 1, 3), ]

# Paragominas
set.seed(1487175758)
parD = estimateD(par.raref, datatype = "abundance",
                 base = "coverage", level = NULL, conf = 0.95)
parD = subset(parD, order == 0)[c(2, 1, 3), ]

# Tartarugalzinho + Porto_Grande
set.seed(1487175758)
tarD = estimateD(tar.raref, datatype = "abundance",
                 base = "coverage", level = NULL, conf = 0.95)
tarD = subset(tarD, order == 0)[c(2, 1, 3), ]
# Use sample coverage of 0.905 rather than 0.886
# 0.905 is closer to 0.910 than 0.886
tarD[2, ] = c("EP", 20, "interpolated", 0, 0.905, 7.905, 6.079, 9.731)
tarD$m = as.numeric(tarD$m)
tarD$qD = as.numeric(tarD$qD)
tarD$qD.LCL = as.numeric(tarD$qD.LCL)
tarD$qD.UCL = as.numeric(tarD$qD.UCL)


#################################################################
### Species richness difference in relation to Primary forest ###
#################################################################

almDiff = -(1 - (almD[, 6:8] / almD$qD[almD$site == "PF"])) * 100
mojDiff = -(1 - (mojD[, 6:8] / mojD$qD[mojD$site == "PF"])) * 100
parDiff = -(1 - (parD[, 6:8] / parD$qD[parD$site == "PF"])) * 100
tarDiff = -(1 - (tarD[, 6:8] / tarD$qD[tarD$site == "PF"])) * 100

richnessDiff = rbind(almDiff,
                     mojDiff,
                     parDiff,
                     tarDiff)

richnessDiff$site = rep(c("a.alm", "b.moj", "c.par", "d.tar"),
                        each = 3)

richnessDiff$habitat = c(unique(alm.richness$habitat),
                         unique(moj.richness$habitat),
                         unique(par.richness$habitat),
                         unique(tar.richness$habitat))

richnessDiff$pairs = c(4, 4.5, 4.5, # Secondaty forest
                       10, 10.5, 10.5, # Oil palm plantation
                       1, 1.5, 1.5, # Logged forest
                       7, 7.5, 7.5) # Eucalypt plantation

richnessDiff$m = c(almD$m, mojD$m, parD$m, tarD$m)


#####################################
### Graficos: curvas de rarefacao ###
#####################################

#####################################################
# Almerim: Dados (adiciona pontos e barras de erro) #
#####################################################
alm.richness = rbind(alm.richness,
                     c(almD$m[1], "added", 
                       almD$qD[1], almD$qD.LCL[1], almD$qD.UCL[1],
                       almD$SC[1],
                       "a.Primary forest"),
                     c(almD$m[2], "added", 
                       almD$qD[2], almD$qD.LCL[2], almD$qD.UCL[2],
                       almD$SC[2],
                       "b.Secondary forest (total species)"),
                     c(almD$m[3], "added", 
                       almD$qD[3], almD$qD.LCL[3], almD$qD.UCL[3],
                       almD$SC[3],
                       "c.Secondary forest (primary forest species)"))

alm.richness$m = as.numeric(alm.richness$m)
alm.richness$qD = as.numeric(alm.richness$qD)
alm.richness$qD.LCL = as.numeric(alm.richness$qD.LCL)
alm.richness$qD.UCL = as.numeric(alm.richness$qD.UCL)
alm.richness$SC = as.numeric(alm.richness$SC)

rbind(head(alm.richness),
      tail(alm.richness))

####################
# Almerim: Grafico #
####################
alm.raref.graph =
  
  ggplot(data = subset(alm.richness,
                       method != "extrapolated" &
                         method != "added"),
         aes(x = m, y = qD,
             shape = habitat, fill = habitat, linetype = habitat)) +
  
  labs(x = "Number of records",
       y = "",
       shape = NULL,
       fill = NULL,
       linetype = NULL) +
  
  scale_x_continuous(limits = c(1, NA),
                     breaks = c(1, 50, 100, 150)) +
  scale_y_continuous(limits = c(1, NA),
                     breaks = c(1, 5, 10, 15)) +
  scale_shape_manual(values = c(21, 21, 24),
                     labels = c("Primary forest",
                                "Secondary forest (total species)",
                                "Secondary forest (primary forest species)")) +
  scale_fill_manual(values = c("grey", "#34a853", "#34a853"),
                    labels = c("Primary forest",
                               "Secondary forest (total species)",
                               "Secondary forest (primary forest species)")) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
  
  geom_line(colour = "black", size = 1) +
  
  geom_errorbar(data = subset(alm.richness,
                              method == "added"),
                aes(x = m, ymin = qD.LCL, ymax = qD.UCL),
                width = 4.166666667,
                linetype = "solid") +
  
  geom_point(data = subset(alm.richness,
                           method == "added"),
             size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.95, 0.05),
        legend.justification = c(0.95, 0.05)) +
  guides(linetype = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(b)")

#ggsave(alm.raref.graph,
#       filename = "./new_figures/Fig3b.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


##################################################
# Moju: Dados (adiciona pontos e barras de erro) #
##################################################
moj.richness = rbind(moj.richness,
                     c(mojD$m[1], "added", 
                       mojD$qD[1], mojD$qD.LCL[1], mojD$qD.UCL[1],
                       mojD$SC[1],
                       "a.Primary forest"),
                     c(mojD$m[2], "added", 
                       mojD$qD[2], mojD$qD.LCL[2], mojD$qD.UCL[2],
                       mojD$SC[2],
                       "b.Oil palm plantation (total species)"),
                     c(mojD$m[3], "added", 
                       mojD$qD[3], mojD$qD.LCL[3], mojD$qD.UCL[3],
                       mojD$SC[3],
                       "c.Oil palm plantation (primary forest species)"))

moj.richness$m = as.numeric(moj.richness$m)
moj.richness$qD = as.numeric(moj.richness$qD)
moj.richness$qD.LCL = as.numeric(moj.richness$qD.LCL)
moj.richness$qD.UCL = as.numeric(moj.richness$qD.UCL)
moj.richness$SC = as.numeric(moj.richness$SC)

rbind(head(moj.richness),
      tail(moj.richness))

#################
# Moju: Grafico #
#################
moj.raref.graph =
  
  ggplot(data = subset(moj.richness,
                       method != "extrapolated" &
                         method != "added"),
         aes(x = m, y = qD,
             shape = habitat, fill = habitat, linetype = habitat)) +
  
  labs(x = "Number of records",
       y = "",
       shape = NULL,
       fill = NULL,
       linetype = NULL) +
  
  scale_x_continuous(limits = c(1, NA),
                     breaks = c(1, 250, 500, 750, 1000)) +
  scale_y_continuous(limits = c(1, NA),
                     breaks = c(1, 10, 20, 30)) +
  scale_shape_manual(values = c(21, 21, 24),
                     labels = c("Primary forest",
                                "Oil palm plantation (total species)",
                                "Oil palm plantation (primary forest species)")) +
  scale_fill_manual(values = c("grey", "#ea4335", "#ea4335"),
                    labels = c("Primary forest",
                               "Oil palm plantation (total species)",
                               "Oil palm plantation (primary forest species)")) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
  
  geom_line(colour = "black", size = 1) +
  
  geom_errorbar(data = subset(moj.richness,
                              method == "added"),
                aes(x = m, ymin = qD.LCL, ymax = qD.UCL),
                width = 28.97222222,
                linetype = "solid") +
  
  geom_point(data = subset(moj.richness,
                           method == "added"),
             size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.95, 0.05),
        legend.justification = c(0.95, 0.05)) +
  guides(linetype = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(d)")

#ggsave(moj.raref.graph,
#       filename = "./new_figures/Fig3d.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


#########################################################
# Paragominas: Dados (adiciona pontos e barras de erro) #
#########################################################
par.richness = rbind(par.richness,
                     c(parD$m[1], "added", 
                       parD$qD[1], parD$qD.LCL[1], parD$qD.UCL[1],
                       parD$SC[1],
                       "a.Primary forest"),
                     c(parD$m[2], "added", 
                       parD$qD[2], parD$qD.LCL[2], parD$qD.UCL[2],
                       parD$SC[2],
                       "b.Logged forest (total species)"),
                     c(parD$m[3], "added", 
                       parD$qD[3], parD$qD.LCL[3], parD$qD.UCL[3],
                       parD$SC[3],
                       "c.Logged forest (primary forest species)"))

par.richness$m = as.numeric(par.richness$m)
par.richness$qD = as.numeric(par.richness$qD)
par.richness$qD.LCL = as.numeric(par.richness$qD.LCL)
par.richness$qD.UCL = as.numeric(par.richness$qD.UCL)
par.richness$SC = as.numeric(par.richness$SC)

rbind(head(par.richness),
      tail(par.richness))

########################
# Paragominas: Grafico #
########################
par.raref.graph =
  
  ggplot(data = subset(par.richness,
                       method != "extrapolated" &
                         method != "added"),
         aes(x = m, y = qD,
             shape = habitat, fill = habitat, linetype = habitat)) +
  
  labs(x = "Number of records",
       y = "Number of species",
       shape = NULL,
       fill = NULL,
       linetype = NULL) +
  
  scale_x_continuous(limits = c(1, NA),
                     breaks = c(1, 500, 1000, 1500, 2000)) +
  scale_y_continuous(limits = c(1, NA),
                     breaks = c(1, 5, 10, 15, 20)) +
  scale_shape_manual(values = c(21, 21, 24),
                     labels = c("Primary forest",
                                "Logged forest (total species)",
                                "Logged forest (primary forest species)")) +
  scale_fill_manual(values = c("grey", "#4285f4", "#4285f4"),
                    labels = c("Primary forest",
                               "Logged forest (total species)",
                               "Logged forest (primary forest species)")) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
  
  geom_line(colour = "black", size = 1) +
  
  geom_errorbar(data = subset(par.richness,
                              method == "added"),
                aes(x = m, ymin = qD.LCL, ymax = qD.UCL),
                width = 56.52777778,
                linetype = "solid") +
  
  geom_point(data = subset(par.richness,
                           method == "added"),
             size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.95, 0.05),
        legend.justification = c(0.95, 0.05)) +
  guides(linetype = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(a)")

#ggsave(par.raref.graph,
#       filename = "./new_figures/Fig3a.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


#############################################################
# Tartarugalzinho: Dados (adiciona pontos e barras de erro) #
#############################################################
tar.richness = rbind(tar.richness,
                     c(tarD$m[1], "added", 
                       tarD$qD[1], tarD$qD.LCL[1], tarD$qD.UCL[1],
                       tarD$SC[1],
                       "a.Primary forest"),
                     c(tarD$m[2], "added", 
                       tarD$qD[2], tarD$qD.LCL[2], tarD$qD.UCL[2],
                       tarD$SC[2],
                       "b.Eucalypt plantation (total species)"),
                     c(tarD$m[3], "added", 
                       tarD$qD[3], tarD$qD.LCL[3], tarD$qD.UCL[3],
                       tarD$SC[3],
                       "c.Eucalypt plantation (primary forest species)"))

tar.richness$m = as.numeric(tar.richness$m)
tar.richness$qD = as.numeric(tar.richness$qD)
tar.richness$qD.LCL = as.numeric(tar.richness$qD.LCL)
tar.richness$qD.UCL = as.numeric(tar.richness$qD.UCL)
tar.richness$SC = as.numeric(tar.richness$SC)

rbind(head(tar.richness),
      tail(tar.richness))

############################
# Tartarugalzinho: Grafico #
############################
tar.raref.graph =
  
  ggplot(data = subset(tar.richness,
                       method != "extrapolated" &
                         method != "added"),
         aes(x = m, y = qD,
             shape = habitat, fill = habitat, linetype = habitat)) +
  
  labs(x = "Number of records",
       y = "",
       shape = NULL,
       fill = NULL,
       linetype = NULL) +
  
  scale_x_continuous(limits = c(1, NA),
                     breaks = c(1, 20, 40, 60)) +
  scale_y_continuous(limits = c(1, NA),
                     breaks = c(1, 5, 10, 15)) +
  scale_shape_manual(values = c(21, 21, 24),
                     labels = c("Primary forest",
                                "Eucalypt plantation (total species)",
                                "Eucalypt plantation (primary forest species)")) +
  scale_fill_manual(values = c("grey", "#fbbc04", "#fbbc04"),
                    labels = c("Primary forest",
                               "Eucalypt plantation (total species)",
                               "Eucalypt plantation (primary forest species)")) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
  
  geom_line(colour = "black", size = 1) +
  
  geom_errorbar(data = subset(tar.richness,
                              method == "added"),
                aes(x = m, ymin = qD.LCL, ymax = qD.UCL),
                width = 2,
                linetype = "solid") +
  
  geom_point(data = subset(tar.richness,
                           method == "added"),
             size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.95, 0.05),
        legend.justification = c(0.95, 0.05)) +
  guides(linetype = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(c)")

#ggsave(tar.raref.graph,
#       filename = "./new_figures/Fig3c.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


############################################
### Graph of species richness difference ###
### in relation to Primary forest ##########
############################################

# Total species
graphRichnessAllDiff = 
  
  ggplot(data = richnessDiff[-which(grepl("c\\.",
                                          richnessDiff$habitat)), ],
         aes(x = pairs, y = qD,
             fill = habitat)) +
  
  labs(x = NULL,
       y = "Change in relation to primary forest (%)") +
  
  ggtitle("Total species") +
  
  scale_x_continuous(limits = c(0, 11.5),
                     breaks = c(1.25, 4.25, 7.25, 10.25),
                     labels =   c("Logged\nforest",
                                  "Secondary\nforest",
                                  "Eucalypt\nplantation",
                                  "Oil palm\nplantation")) +
  scale_y_continuous(limits = c(-108.745285, 108.745285),
                     breaks = seq(-100, 100, 25)) +
  scale_fill_manual(values = c("grey",
                               "#fbbc04", # amarelo
                               "#4285f4", # azul,
                               "#ea4335", # vermelho
                               "#34a853")) + # verde
  
  geom_hline(yintercept = 0, colour = "black",
             size = 0.5, linetype = "dashed") +
  
  geom_errorbar(aes(ymin = qD.LCL,
                    ymax = qD.UCL,
                    x = pairs),
                width = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(plot.title = element_text(hjust = 0.5,
                                  size = 20, face = "bold")) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(a)")

#ggsave(graphRichnessAllDiff,
#       filename = "./new_figures/Fig4a.png",
#       w = 20, h = 20, units = "cm", dpi = 600)


# Primary forest species held
graphRichnessRelictDiff = 
  
  ggplot(data = richnessDiff[-which(grepl("b\\.",
                                          richnessDiff$habitat)), ],
         aes(x = pairs, y = qD,
             fill = habitat, shape = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  ggtitle("Primary forest species") +
  
  scale_x_continuous(limits = c(0, 11.5),
                     breaks = c(1.25, 4.25, 7.25, 10.25),
                     labels =   c("Logged\nforest",
                                  "Secondary\nforest",
                                  "Eucalypt\nplantation",
                                  "Oil palm\nplantation")) +
  scale_y_continuous(limits = c(-108.745285, 108.745285),
                     breaks = seq(-100, 100, 25)) +
  scale_fill_manual(values = c("grey",
                               "#fbbc04", # amarelo
                               "#4285f4", # azul,
                               "#ea4335", # vermelho
                               "#34a853")) + # verde
  scale_shape_manual(values = c(21, 24, 24, 24, 24)) +
  
  geom_hline(yintercept = 0, colour = "black",
             size = 0.5, linetype = "dashed") +
  
  geom_errorbar(aes(ymin = qD.LCL,
                    ymax = qD.UCL,
                    x = pairs),
                width = 0.2) +
  geom_point(colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(plot.title = element_text(hjust = 0.5,
                                  size = 20, face = "bold")) +
  guides(fill = FALSE, shape = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(b)")

#ggsave(graphRichnessRelictDiff,
#       filename = "./new_figures/Fig4b.png",
#       w = 20, h = 20, units = "cm", dpi = 600)


##################
### ABUNDANCIA ###
##################

# transforma avistamentos em taxa de avistamento a cada 10 km
# "/ 1000" transformar metros em km e "* 10" transforma a taxa de 'individuos a cada 1 km' para 'individuos a cada 10 km'
# remove especies nao registradas nos sitios
alm.spp.tx = (alm[5:ncol(alm)] / (alm$metros_percorridos / 1000)) * 10
alm.spp.tx = alm.spp.tx[colSums(alm.spp.tx) > 0]

moj.spp.tx = (moj[5:ncol(moj)] / (moj$metros_percorridos / 1000)) * 10
moj.spp.tx = moj.spp.tx[colSums(moj.spp.tx) > 0]

par.spp.tx = (par[5:ncol(par)] / (par$metros_percorridos / 1000)) * 10
par.spp.tx = par.spp.tx[colSums(par.spp.tx) > 0]

tar.spp.tx = (tar[5:ncol(tar)] / (tar$metros_percorridos / 1000)) * 10
tar.spp.tx = tar.spp.tx[colSums(tar.spp.tx) > 0]


############################
### TESTE T - ABUNDANCIA ###
############################

# Calcula a abundancia das trilhas
# Corresponde a soma das taxas de avistamento das especies a cada 10 km
alm.abund.PF = rowSums(alm.spp.tx[grepl("PF", rownames(alm.spp.tx)), ])
alm.abund.SF = rowSums(alm.spp.tx[!grepl("PF", rownames(alm.spp.tx)), ])

moj.abund.PF = rowSums(moj.spp.tx[grepl("PF", rownames(moj.spp.tx)), ])
moj.abund.OP = rowSums(moj.spp.tx[!grepl("PF", rownames(moj.spp.tx)), ])

par.abund.PF = rowSums(par.spp.tx[grepl("PF", rownames(par.spp.tx)), ])
par.abund.LF = rowSums(par.spp.tx[!grepl("PF", rownames(par.spp.tx)), ])

tar.abund.PF = rowSums(tar.spp.tx[grepl("PF", rownames(tar.spp.tx)), ])
tar.abund.EP = rowSums(tar.spp.tx[!grepl("PF", rownames(tar.spp.tx)), ])

# t-test
t.test(alm.abund.PF, alm.abund.SF) # no difference
t.test(moj.abund.PF, moj.abund.OP) # there is difference
t.test(par.abund.PF, par.abund.LF, paired = TRUE) # no difference
t.test(tar.abund.PF, tar.abund.EP) # there is difference


##################################################################
### Species abundance difference in relation to Primary forest ###
##################################################################

# Almerim (PF vs. SF)
alm.abund.SF.mean  = -(1 - mean(alm.abund.SF) /
                         mean(alm.abund.PF)) * 100
alm.abund.SF.lowerCI = -(1 - t.test(alm.abund.SF)$conf.int[1] /
                           mean(alm.abund.PF)) * 100
alm.abund.SF.upperCI = -(1 - t.test(alm.abund.SF)$conf.int[2] /
                           mean(alm.abund.PF)) * 100

alm.abund.PF.mean  = -(1 - mean(alm.abund.PF) /
                         mean(alm.abund.PF)) * 100
alm.abund.PF.lowerCI = -(1 - t.test(alm.abund.PF)$conf.int[1] /
                           mean(alm.abund.PF)) * 100
alm.abund.PF.upperCI = -(1 - t.test(alm.abund.PF)$conf.int[2] /
                           mean(alm.abund.PF)) * 100


# Moju (PF vs. OP)
moj.abund.OP.mean  = -(1 - mean(moj.abund.OP) /
                         mean(moj.abund.PF)) * 100
moj.abund.OP.lowerCI = -(1 - t.test(moj.abund.OP)$conf.int[1] /
                           mean(moj.abund.PF)) * 100
moj.abund.OP.upperCI = -(1 - t.test(moj.abund.OP)$conf.int[2] /
                           mean(moj.abund.PF)) * 100

moj.abund.PF.mean  = -(1 - mean(moj.abund.PF) /
                         mean(moj.abund.PF)) * 100
moj.abund.PF.lowerCI = -(1 - t.test(moj.abund.PF)$conf.int[1] /
                           mean(moj.abund.PF)) * 100
moj.abund.PF.upperCI = -(1 - t.test(moj.abund.PF)$conf.int[2] /
                           mean(moj.abund.PF)) * 100


# Paragominas (PF vs. LF)
par.abund.LF.mean  = -(1 - mean(par.abund.LF) /
                         mean(par.abund.PF)) * 100
par.abund.LF.lowerCI = -(1 - t.test(par.abund.LF)$conf.int[1] /
                           mean(par.abund.PF)) * 100
par.abund.LF.upperCI = -(1 - t.test(par.abund.LF)$conf.int[2] /
                           mean(par.abund.PF)) * 100

par.abund.PF.mean  = -(1 - mean(par.abund.PF) /
                         mean(par.abund.PF)) * 100
par.abund.PF.lowerCI = -(1 - t.test(par.abund.PF)$conf.int[1] /
                           mean(par.abund.PF)) * 100
par.abund.PF.upperCI = -(1 - t.test(par.abund.PF)$conf.int[2] /
                           mean(par.abund.PF)) * 100

# Tartarugalzinho + Porto_Grande (PF vs. EP)
tar.abund.EP.mean  = -(1 - mean(tar.abund.EP) /
                         mean(tar.abund.PF)) * 100
tar.abund.EP.lowerCI = -(1 - t.test(tar.abund.EP)$conf.int[1] /
                           mean(tar.abund.PF)) * 100
tar.abund.EP.upperCI = -(1 - t.test(tar.abund.EP)$conf.int[2] /
                           mean(tar.abund.PF)) * 100

tar.abund.PF.mean  = -(1 - mean(tar.abund.PF) /
                         mean(tar.abund.PF)) * 100
tar.abund.PF.lowerCI = -(1 - t.test(tar.abund.PF)$conf.int[1] /
                           mean(tar.abund.PF)) * 100
tar.abund.PF.upperCI = -(1 - t.test(tar.abund.PF)$conf.int[2] /
                           mean(tar.abund.PF)) * 100


#######################################################
### combina os resultados do t-test para abundancia ###
#######################################################

ttest.abund = data.frame(metric = rep("abundance", 8),
                         mean = c(alm.abund.PF.mean, alm.abund.SF.mean,
                                  moj.abund.PF.mean, moj.abund.OP.mean,
                                  par.abund.PF.mean, par.abund.LF.mean,
                                  tar.abund.PF.mean, tar.abund.EP.mean),
                         lowerCI = c(alm.abund.PF.lowerCI, alm.abund.SF.lowerCI,
                                     moj.abund.PF.lowerCI, moj.abund.OP.lowerCI,
                                     par.abund.PF.lowerCI, par.abund.LF.lowerCI,
                                     tar.abund.PF.lowerCI, tar.abund.EP.lowerCI),
                         upperCI = c(alm.abund.PF.upperCI, alm.abund.SF.upperCI,
                                     moj.abund.PF.upperCI, moj.abund.OP.upperCI,
                                     par.abund.PF.upperCI, par.abund.LF.upperCI,
                                     tar.abund.PF.upperCI, tar.abund.EP.upperCI),
                         test = rep("ttest", 8),
                         habitat = c(4, 4.5, # Secondaty forest
                                     10, 10.5, # Oil palm plantation
                                     1, 1.5, # Logged forest
                                     7, 7.5)) # Eucalypt plantation


############################
### Graficos: abundancia ###
############################

# preparacao dos dados
alm.tx = data.frame(tx = rowSums(alm.spp.tx),
                    habitat = c(rep("a.Primary forest", 5),
                                rep("b.Secondary forest", 5)))
moj.tx = data.frame(tx = rowSums(moj.spp.tx),
                    habitat = c(rep("b.Oil palm plantation", 8),
                                rep("a.Primary forest", 8)))
par.tx = data.frame(tx = rowSums(par.spp.tx),
                    habitat = c(rep("b.Logged forest", 21),
                                rep("a.Primary forest", 21)))
tar.tx = data.frame(tx = rowSums(tar.spp.tx),
                    habitat = c(rep("b.Eucalypt plantation", 4),
                                rep("a.Primary forest", 6)))


# Almerim
alm.abund.graph =
  
  ggplot(data = alm.tx[order(alm.tx$tx), ],
         aes(x = habitat, y = tx, fill = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Secondary\nforest")) +
  scale_y_continuous(breaks = seq(3, 12, 3)) +
  scale_fill_manual(values = c("grey", "#34a853")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(f)")

#ggsave(alm.abund.graph,
#       filename = "./new_figures/Fig3f.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Moju
moj.abund.graph =
  
  ggplot(data = moj.tx[order(moj.tx$tx), ],
         aes(x = habitat, y = tx, fill = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Oil palm\nplantation")) +
  scale_fill_manual(values = c("grey", "#ea4335")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(h)")

#ggsave(moj.abund.graph,
#       filename = "./new_figures/Fig3h.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Paragominas
par.abund.graph =
  
  ggplot(data = par.tx[order(par.tx$tx), ],
         aes(x = habitat, y = tx, fill = habitat)) +
  
  labs(x = NULL,
       y = "Records per 10 km walked") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Logged\nforest")) +
  scale_y_continuous(breaks = seq(10, 60, 10)) +
  scale_fill_manual(values = c("grey", "#4285f4")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(e)")

#ggsave(par.abund.graph,
#       filename = "./new_figures/fig3e.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Tartarugalzinho + Porto_Grande
tar.abund.graph =
  
  ggplot(data = tar.tx[order(tar.tx$tx), ],
         aes(x = habitat, y = tx, fill = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Eucalypt\nplantation")) +
  scale_fill_manual(values = c("grey", "#fbbc04")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(g)")

#ggsave(tar.abund.graph,
#       filename = "./new_figures/Fig3g.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


##############################
### COMPOSICAO DE ESPECIES ###
##############################

# NMDS
# Almeirim
# Standardise trail-by-species abundance matrix
alm.spp.std = alm[names(alm.spp.tx)] / rowSums(alm[names(alm.spp.tx)])

set.seed(1487175758)
alm.nmds = metaMDS(alm.spp.std, distance = "bray", binary = FALSE, k = 2,
                   trymax = 1000, autotransform = FALSE)

alm.nmds.xy = data.frame(alm.nmds$points)
alm.nmds.xy$habitat = c(rep("a.Primary forest", 5),
                        rep("b.Secondary forest", 5))

# Moju
# Standardise trail-by-species abundance matrix
moj.spp.std = moj[names(moj.spp.tx)] / rowSums(moj[names(moj.spp.tx)])

set.seed(1487175758)
moj.nmds = metaMDS(moj.spp.std, distance = "bray", binary = FALSE, k = 2,
                   trymax = 1000, autotransform = FALSE)

moj.nmds.xy = data.frame(moj.nmds$points)
moj.nmds.xy$habitat = c(rep("d.Oil palm plantation", 8),
                        rep("a.Primary forest", 8))

# Paragominas
# Standardise trail-by-species abundance matrix
par.spp.std = par[names(par.spp.tx)] / rowSums(par[names(par.spp.tx)])

set.seed(1487175758)
par.nmds = metaMDS(par.spp.std, distance = "bray", binary = FALSE, k = 2,
                   trymax = 1000, autotransform = FALSE)

par.nmds.xy = data.frame(par.nmds$points)
par.nmds.xy$habitat = c(rep("b.Logged forest", 21),
                        rep("a.Primary forest", 21))

# Tartarugalzinho + Porto_Grande
# Standardise trail-by-species abundance matrix
tar.spp.std = tar[names(tar.spp.tx)] / rowSums(tar[names(tar.spp.tx)])

set.seed(1487175758)
tar.nmds = metaMDS(tar.spp.std, distance = "bray", binary = FALSE, k = 2,
                   trymax = 1000, autotransform = FALSE)

tar.nmds.xy = data.frame(tar.nmds$points)
tar.nmds.xy$habitat = c(rep("b.Eucalypt plantation", 4),
                        rep("a.Primary forest", 6))

#################
### PERMANOVA ###
#################

# Almerim
set.seed(1487175758)
alm.adonis = adonis(alm.spp.std ~ alm.nmds.xy$habitat, 
                    permutations = 1000,
                    method = "bray") # There is difference

# Moju
set.seed(1487175758)
moj.adonis = adonis(moj.spp.std ~ moj.nmds.xy$habitat, 
                    permutations = 1000,
                    method = "bray") # There is difference

# Paragominas
set.seed(1487175758)
par.adonis = adonis(par.spp.std ~ par.nmds.xy$habitat, 
                    permutations = 1000,
                    method = "bray") # No difference

# Tartarugalzinho + Porto_Grande
set.seed(1487175758)
tar.adonis = adonis(tar.spp.std ~ tar.nmds.xy$habitat,
                    permutations = 1000,
                    method = "bray") # There is difference


############################
### Graficos: composicao ###
############################

# Code for the polygons
find_hull = function(alm.nmds.xy) alm.nmds.xy[chull(alm.nmds.xy$MDS1, alm.nmds.xy$MDS2), ]

# Almerim
alm.hulls = ddply(alm.nmds.xy, "habitat", find_hull)

alm.nmds.graph =
  
  ggplot(data = alm.nmds.xy[order(alm.nmds.xy$MDS1, alm.nmds.xy$MDS2), ],
         aes(x = MDS1, y = MDS2, fill = habitat)) +
  
  labs(x = "NMDS axis 1",
       y = "") +
  
  scale_fill_manual(values = c("grey", "#33a02c")) +
  
  geom_polygon(data = alm.hulls, aes(colour = NULL), alpha = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  guides(fill = FALSE) +
  
  annotate("text", x = min(alm.nmds.xy$MDS1), y = min(alm.nmds.xy$MDS2),
           hjust = 0, vjust = 0, size = 5,
           label = paste("Stress: ", round(alm.nmds$stress, 3),
                         0, sep = "")) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(j)")

#ggsave(alm.nmds.graph,
#       filename = "./new_figures/Fig3j.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Moju
moj.hulls = ddply(moj.nmds.xy, "habitat", find_hull)

moj.nmds.graph =
  
  ggplot(data = moj.nmds.xy[order(moj.nmds.xy$MDS1, moj.nmds.xy$MDS2), ],
         aes(x = MDS1, y = MDS2, fill = habitat)) +
  
  labs(x = "NMDS axis 1",
       y = "") +
  
  scale_fill_manual(values = c("grey", "#ea4335")) +
  
  geom_polygon(data = moj.hulls, aes(colour = NULL), alpha = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  guides(fill = FALSE) +
  
  annotate("text", x = min(moj.nmds.xy$MDS1), y = min(moj.nmds.xy$MDS2),
           hjust = 0, vjust = 0, size = 5,
           label = paste("Stress:", round(moj.nmds$stress, 3))) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(l)")

#ggsave(moj.nmds.graph,
#       filename = "./new_figures/Fig3l.png", dpi = 600,
#       width = 20, height = 20, units = "cm")



# Paragominas
par.hulls = ddply(par.nmds.xy, "habitat", find_hull)

par.nmds.graph =
  
  ggplot(data = par.nmds.xy[order(par.nmds.xy$MDS1, par.nmds.xy$MDS2), ],
         aes(x = MDS1, y = MDS2, fill = habitat)) +
  
  labs(x = "NMDS axis 1",
       y = "NMDS axis 2") +
  
  scale_fill_manual(values = c("grey", "#4285f4")) +
  
  geom_polygon(data = par.hulls, aes(colour = NULL), alpha = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  guides(fill = FALSE) +
  
  annotate("text", x = min(par.nmds.xy$MDS1), y = min(par.nmds.xy$MDS2),
           hjust = 0, vjust = 0, size = 5,
           label = paste("Stress:", round(par.nmds$stress, 3))) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(i)")

#ggsave(par.nmds.graph,
#       filename = "./new_figures/Fig3i.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Tartarugalzinho + Porto_Grande
tar.hulls = ddply(tar.nmds.xy, "habitat", find_hull)

tar.nmds.graph =
  
  ggplot(data = tar.nmds.xy[order(tar.nmds.xy$MDS1, tar.nmds.xy$MDS2), ],
         aes(x = MDS1, y = MDS2, fill = habitat)) +
  
  labs(x = "NMDS axis 1",
       y = "") +
  
  scale_fill_manual(values = c("grey", "#fbbc04")) +
  
  geom_polygon(data = tar.hulls, aes(colour = NULL), alpha = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  guides(fill = FALSE) +
  
  annotate("text", x = min(tar.nmds.xy$MDS1), y = min(tar.nmds.xy$MDS2),
           hjust = 0, vjust = 0, size = 5,
           label = paste("Stress:", round(tar.nmds$stress, 3))) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(k)")

#ggsave(tar.nmds.graph,
#       filename = "./new_figures/Fig3k.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


#################################
### INTEGRIDADE DA COMUNIDADE ###
#################################

# calcula o community integrity index para dados de abundancia relativa (padronizados pela soma das linhas) das trilhas de cada regiao

# Almerim
# mean Bray-Curtis distance among control (primary forest) sites
alm.bray.PF = as.matrix(vegdist(alm.spp.std,
                                method = "bray",
                                binary = FALSE))[1:5, 1:5]
alm.int.PF = mean(1 - apply(alm.bray.PF, 2, mean))

# scaled Bray-Curtis index among 'control and treatment sites' and 'control and control'
alm.bray.all = as.matrix(vegdist(alm.spp.std,
                                 method = "bray",
                                 binary = FALSE))[1:5, ]
alm.int.all = ((1 - apply(alm.bray.all, 2, mean)) / alm.int.PF) * 100
alm.int.all = data.frame(alm.int = alm.int.all,
                         habitat = c(rep("a.Primary forest", 5),
                                     rep("b.Secondary forest", 5)))

# Data for t-test
alm.int.PF = subset(alm.int.all, habitat == "a.Primary forest")[, 1]
alm.int.SF = subset(alm.int.all, habitat != "a.Primary forest")[, 1]


# Moju
moj.bray.OP = as.matrix(vegdist(moj.spp.std,
                                method = "bray",
                                binary = FALSE))[9:16, 9:16]
moj.int.OP = mean(1 - apply(moj.bray.OP, 2, mean))

moj.bray.all = as.matrix(vegdist(moj.spp.std,
                                 method = "bray",
                                 binary = FALSE))[9:16, ]
moj.int.all = ((1 - apply(moj.bray.all, 2, mean)) / moj.int.OP) * 100
moj.int.all = data.frame(moj.int = moj.int.all,
                         habitat = c(rep("d.Oil palm plantation", 8),
                                     rep("a.Primary forest", 8)))

moj.int.PF = subset(moj.int.all, habitat == "a.Primary forest")[, 1]
moj.int.OP = subset(moj.int.all, habitat != "a.Primary forest")[, 1]


# Paragominas
par.bray.LF = as.matrix(vegdist(par.spp.std,
                                method = "bray",
                                binary = FALSE))[22:42, 22:42]
par.int.LF = mean(1 - apply(par.bray.LF, 2, mean))

par.bray.all = as.matrix(vegdist(par.spp.std,
                                 method = "bray",
                                 binary = FALSE))[22:42, ]
par.int.all = ((1 - apply(par.bray.all, 2, mean)) / par.int.LF) * 100
par.int.all = data.frame(par.int = par.int.all,
                         habitat = c(rep("b.Logged forest", 21),
                                     rep("a.Primary forest", 21)))

par.int.PF = subset(par.int.all, habitat == "a.Primary forest")[, 1]
par.int.LF = subset(par.int.all, habitat != "a.Primary forest")[, 1]


# Tartarugalzinho + Porto_Grande
tar.bray.EP = as.matrix(vegdist(tar.spp.std,
                                method = "bray",
                                binary = FALSE))[5:10, 5:10]
tar.int.EP = mean(1 - apply(tar.bray.EP, 2, mean))

tar.bray.all = as.matrix(vegdist(tar.spp.std,
                                 method = "bray",
                                 binary = FALSE))[5:10, ]
tar.int.all = ((1 - apply(tar.bray.all, 2, mean)) / tar.int.EP) * 100
tar.int.all = data.frame(tar.int = tar.int.all,
                         habitat = c(rep("b.Eucalypt plantation", 4),
                                     rep("a.Primary forest", 6)))

tar.int.PF = subset(tar.int.all, habitat == "a.Primary forest")[, 1]
tar.int.EP = subset(tar.int.all, habitat != "a.Primary forest")[, 1]


# t-test
t.test(alm.int.PF, alm.int.SF)
t.test(moj.int.PF, moj.int.OP)
t.test(par.int.PF, par.int.LF)
t.test(tar.int.PF, tar.int.EP)


####################################################################
### Community integrity difference in relation to Primary forest ###
####################################################################

# Almerim (PF vs. SF)
alm.int.SF.mean  = -(1 - mean(alm.int.SF) /
                       mean(alm.int.PF)) * 100
alm.int.SF.lowerCI = -(1 - t.test(alm.int.SF)$conf.int[1] /
                         mean(alm.int.PF)) * 100
alm.int.SF.upperCI = -(1 - t.test(alm.int.SF)$conf.int[2] /
                         mean(alm.int.PF)) * 100

alm.int.PF.mean  = -(1 - mean(alm.int.PF) /
                       mean(alm.int.PF)) * 100
alm.int.PF.lowerCI = -(1 - t.test(alm.int.PF)$conf.int[1] /
                         mean(alm.int.PF)) * 100
alm.int.PF.upperCI = -(1 - t.test(alm.int.PF)$conf.int[2] /
                         mean(alm.int.PF)) * 100


# Moju (PF vs. OP)
moj.int.OP.mean  = -(1 - mean(moj.int.OP) /
                       mean(moj.int.PF)) * 100
moj.int.OP.lowerCI = -(1 - t.test(moj.int.OP)$conf.int[1] /
                         mean(moj.int.PF)) * 100
moj.int.OP.upperCI = -(1 - t.test(moj.int.OP)$conf.int[2] /
                         mean(moj.int.PF)) * 100

moj.int.PF.mean  = -(1 - mean(moj.int.PF) /
                       mean(moj.int.PF)) * 100
moj.int.PF.lowerCI = -(1 - t.test(moj.int.PF)$conf.int[1] /
                         mean(moj.int.PF)) * 100
moj.int.PF.upperCI = -(1 - t.test(moj.int.PF)$conf.int[2] /
                         mean(moj.int.PF)) * 100


# Paragominas (PF vs. LF)
par.int.LF.mean  = -(1 - mean(par.int.LF) /
                       mean(par.int.PF)) * 100
par.int.LF.lowerCI = -(1 - t.test(par.int.LF)$conf.int[1] /
                         mean(par.int.PF)) * 100
par.int.LF.upperCI = -(1 - t.test(par.int.LF)$conf.int[2] /
                         mean(par.int.PF)) * 100

par.int.PF.mean  = -(1 - mean(par.int.PF) /
                       mean(par.int.PF)) * 100
par.int.PF.lowerCI = -(1 - t.test(par.int.PF)$conf.int[1] /
                         mean(par.int.PF)) * 100
par.int.PF.upperCI = -(1 - t.test(par.int.PF)$conf.int[2] /
                         mean(par.int.PF)) * 100

# Tartarugalzinho + Porto_Grande (PF vs. EP)
tar.int.EP.mean  = -(1 - mean(tar.int.EP) /
                       mean(tar.int.PF)) * 100
tar.int.EP.lowerCI = -(1 - t.test(tar.int.EP)$conf.int[1] /
                         mean(tar.int.PF)) * 100
tar.int.EP.upperCI = -(1 - t.test(tar.int.EP)$conf.int[2] /
                         mean(tar.int.PF)) * 100

tar.int.PF.mean  = -(1 - mean(tar.int.PF) /
                       mean(tar.int.PF)) * 100
tar.int.PF.lowerCI = -(1 - t.test(tar.int.PF)$conf.int[1] /
                         mean(tar.int.PF)) * 100
tar.int.PF.upperCI = -(1 - t.test(tar.int.PF)$conf.int[2] /
                         mean(tar.int.PF)) * 100


################################################################
### combina os resultados do t-test para community integrity ###
################################################################

ttest.int = data.frame(metric = rep("integrity", 8),
                       mean = c(alm.int.PF.mean, alm.int.SF.mean,
                                moj.int.PF.mean, moj.int.OP.mean,
                                par.int.PF.mean, par.int.LF.mean,
                                tar.int.PF.mean, tar.int.EP.mean),
                       lowerCI = c(alm.int.PF.lowerCI, alm.int.SF.lowerCI,
                                   moj.int.PF.lowerCI, moj.int.OP.lowerCI,
                                   par.int.PF.lowerCI, par.int.LF.lowerCI,
                                   tar.int.PF.lowerCI, tar.int.EP.lowerCI),
                       upperCI = c(alm.int.PF.upperCI, alm.int.SF.upperCI,
                                   moj.int.PF.upperCI, moj.int.OP.upperCI,
                                   par.int.PF.upperCI, par.int.LF.upperCI,
                                   tar.int.PF.upperCI, tar.int.EP.upperCI),
                       test = rep("ttest", 8),
                       habitat = c(4, 4.5, # Secondaty forest
                                   10, 10.5, # Oil palm plantation
                                   1, 1.5, # Logged forest
                                   7, 7.5)) # Eucalypt plantation

ttest.int


#############################
### Graficos: integridade ###
#############################

# Almerim
alm.int.graph = 
  
  ggplot(data = alm.int.all[order(alm.int.all$alm.int), ],
         aes(x = habitat, y = alm.int, fill = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Secondary\nforest")) +
  scale_y_continuous(limits = c(50, NA),
                     breaks = c(50, 75, 100)) +
  scale_fill_manual(values = c("grey", "#33a02c")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(n)")

#ggsave(alm.int.graph,
#       filename = "./new_figures/Fig3n.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Moju
moj.int.graph = 
  
  ggplot(data = moj.int.all[order(moj.int.all$moj.int), ],
         aes(x = habitat, y = moj.int, fill = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Oil palm\nplantation")) +
  scale_y_continuous(breaks = c(20, 60, 100)) +
  scale_fill_manual(values = c("grey", "#ea4335")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(p)")

#ggsave(moj.int.graph,
#       filename = "./new_figures/Fig3p.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Paragominas
par.int.graph = 
  
  ggplot(data = par.int.all[order(par.int.all$par.int), ],
         aes(x = habitat, y = par.int, fill = habitat)) +
  
  labs(x = NULL,
       y = "Community integrity (%)") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Logged\nforest")) +
  scale_y_continuous(breaks = c(60, 80, 100)) +
  scale_fill_manual(values = c("grey", "#4285f4")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(m)")

#ggsave(par.int.graph,
#       filename = "./new_figures/Fig3m.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


# Tartarugalzinho + Porto_Grande
tar.int.graph = 
  
  ggplot(data = tar.int.all[order(tar.int.all$tar.int), ],
         aes(x = habitat, y = tar.int, fill = habitat)) +
  
  labs(x = NULL,
       y = "") +
  
  scale_x_discrete(labels = c("Primary\nforest",
                              "Eucalypt\nplantation")) +
  scale_y_continuous(breaks = c(50, 75, 100)) +
  scale_fill_manual(values = c("grey", "#fbbc04")) +
  
  geom_boxplot(width = 0.5, outlier.shape = NA) +
  geom_point(shape = 21, colour = "black", size = 3, alpha = 0.5,
             position = position_jitter(width = 0.15, height = 0)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.text = element_text(size = 14),
        legend.position = c(0.05, 0.95),
        legend.justification = c(0.05, 0.95)) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(o)")

#ggsave(tar.int.graph,
#       filename = "./new_figures/Fig3o.png", dpi = 600,
#       width = 20, height = 20, units = "cm")


#############################################
### combina todos os graficos (par a par) ###
#############################################

ggsave(grid.arrange(par.raref.graph, alm.raref.graph, tar.raref.graph, moj.raref.graph,
                    par.abund.graph, alm.abund.graph, tar.abund.graph, moj.abund.graph,
                    par.nmds.graph, alm.nmds.graph, tar.nmds.graph, moj.nmds.graph,
                    par.int.graph, alm.int.graph, tar.int.graph, moj.int.graph,
                    ncol = 4),
       filename = "./new_figures/Fig3.pdf",
       width = 15.5*4, height = 15.5*4, units = "cm")


#################################################################
### combina os graficos de diferenca percentual de abundancia ###
#################################################################

# Abundance
abund.graph = 
  
  ggplot(data = ttest.abund,
         aes(x = habitat, y = mean,
             fill = as.factor(habitat))) +
  
  labs(x = NULL,
       y = "") +
  
  ggtitle("Abundance") +
  
  scale_x_continuous(limits = c(0, 11.5),
                     breaks = c(1.25, 4.25, 7.25, 10.25),
                     labels =   c("Logged\nforest",
                                  "Secondary\nforest",
                                  "Eucalypt\nplantation",
                                  "Oil palm\nplantation")) +
  scale_y_continuous(limits = c(-108.745285, 108.745285),
                     breaks = seq(-100, 100, 25)) +
  scale_fill_manual(values = c("grey", "#4285f4", # azul
                               "grey", "#34a853", # verde
                               "grey", "#fbbc04", # amarelo
                               "grey", "#ea4335")) + # vermelho
  
  geom_hline(yintercept = 0, colour = "black",
             size = 0.5, linetype = "dashed") +
  
  geom_errorbar(aes(ymin = lowerCI,
                    ymax = upperCI,
                    x = habitat),
                width = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(plot.title = element_text(hjust = 0.5,
                                  size = 20, face = "bold")) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(c)")

#ggsave(abund.graph,
#       filename = "./new_figures/Fig4c.png", dpi = 600,
#       w = 20, h = 20, units = "cm")


##########################################################################
### combina os graficos de diferenca percentual de community integrity ###
##########################################################################

# Community integrity
int.graph = 
  
  ggplot(data = ttest.int,
         aes(x = habitat, y = mean,
             fill = as.factor(habitat))) +
  
  labs(x = NULL,
       y = "") +
  
  ggtitle("Community integrity") +
  
  scale_x_continuous(limits = c(0, 11.5),
                     breaks = c(1.25, 4.25, 7.25, 10.25),
                     labels =   c("Logged\nforest",
                                  "Secondary\nforest",
                                  "Eucalypt\nplantation",
                                  "Oil palm\nplantation")) +
  scale_y_continuous(limits = c(-108.745285, 108.745285),
                     breaks = seq(-100, 100, 25)) +
  scale_fill_manual(values = c("grey", "#4285f4", # azul
                               "grey", "#34a853", # verde
                               "grey", "#fbbc04", # amarelo
                               "grey", "#ea4335")) + # vermelho
  
  geom_hline(yintercept = 0, colour = "black",
             size = 0.5, linetype = "dashed") +
  
  geom_errorbar(aes(ymin = lowerCI,
                    ymax = upperCI,
                    x = habitat),
                width = 0.2) +
  geom_point(shape = 21, colour = "black", size = 5) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(plot.title = element_text(hjust = 0.5,
                                  size = 20, face = "bold")) +
  guides(fill = FALSE) +
  
  annotate("text", x = -Inf, y = Inf,
           hjust = -0.5, vjust = 2, size = 10,
           label = "(d)")

#ggsave(int.graph,
#       filename = "./new_figures/Fig4d.png", dpi = 600,
#       w = 20, h = 20, units = "cm")


#########################################
### combina todos os graficos (geral) ###
#########################################

ggsave(grid.arrange(graphRichnessAllDiff,
                    graphRichnessRelictDiff,
                    abund.graph,
                    int.graph,
                    ncol = 4),
       filename = "./new_figures/Fig4.pdf",
       width = 15.5*4, height = 15.5, units = "cm")


################
### GGPONCHO ###
################

intactness = trilhas$ambiente
intactness[intactness == "PF"] = 1
intactness[intactness == "LF"] = 2
intactness[intactness == "SF"] = 3
intactness[intactness == "EP"] = 4
intactness[intactness == "OP"] = 5
intactness = as.numeric(intactness)

#poncho(trilhas[5:ncol(trilhas)], as.numeric(intactness),
#       forcePA = TRUE, col = as.numeric(intactness))

poncho = trilhas[5:ncol(trilhas)]
poncho$intactness = as.numeric(intactness)
poncho = poncho[order(poncho$intactness), ]
poncho$order = 1:nrow(poncho)

poncho.pa = decostand(poncho[1:46], method = "pa")
colnames(poncho.pa) = gsub("_", " ", colnames(poncho.pa))
spp.order = names(poncho.pa[order(poncho$intactness),
                            order(colSums(poncho.pa * poncho$intactness) / colSums(poncho.pa))])
poncho.pa = poncho.pa[spp.order]

longData = melt(t(poncho.pa))
longData = longData[longData$value != 0, ]
longData$Var3 = factor(as.factor(substring(longData$Var2, 1, 2)),
                       levels(as.factor(substring(longData$Var2, 1, 2)))[c(4, 2, 5, 1, 3)])

ggponcho = 
  
  ggplot(data = longData,
         aes(x = Var2, y = Var1, fill = Var3)) +
  
  labs(x = "Transect code", y = NULL, fill = NULL) +
  
  geom_tile(colour = "black") +
  
  scale_x_discrete(labels = as.factor(1:length(levels(longData$Var2)))) +
  scale_fill_manual(values = c("grey", "#4285f4", "#34a853", "#fbbc04", "#ea4335"),
                    labels = c("Primary forest",
                               "Logged forest",
                               "Secondary forest",
                               "Eucalypt plantation",
                               "Oil palm plantation")) +
  
  theme_minimal(base_size = 20) +
  theme(panel.grid = element_line(size = 0.1),
        axis.title = element_text(colour = "black", size = 14),
        axis.text.x = element_text(colour = "black", size = 8),
        axis.text.y = element_text(colour = "black", face = "italic", size = 10),
        axis.ticks = element_blank()) +
  theme(legend.text = element_text(size = 12)) +
  theme(legend.position = "bottom")

ggsave(ggponcho,
       filename = "./new_figures/Fig5.pdf",
       h = 20, w = 78/46*20, units = "cm")


######################
### EULER DIAGRAMS ###
######################

# Almerim
alm.spp.pf = alm[1:5, 5:ncol(alm)][colSums(alm[1:5, 5:ncol(alm)]) > 0]
alm.spp.sf = alm[6:10, 5:ncol(alm)][colSums(alm[6:10, 5:ncol(alm)]) > 0]

length(colnames(alm.spp.pf)) - length(table(match(colnames(alm.spp.pf), colnames(alm.spp.sf))))
length(colnames(alm.spp.sf)) - length(table(match(colnames(alm.spp.sf), colnames(alm.spp.pf))))
length(table(match(colnames(alm.spp.pf), colnames(alm.spp.sf))))

alm.euler = plot(euler(c(A = 5, B = 4, "A&B" = 10)),
                 legend = NULL, quantities = list(cex = 4),
                 fills = list(fill = c("grey", "#33a02c")))


# Moju
moj.spp.pf = moj[9:16, 5:ncol(moj)][colSums(moj[9:16, 5:ncol(moj)]) > 0]
moj.spp.op = moj[1:8, 5:ncol(moj)][colSums(moj[1:8, 5:ncol(moj)]) > 0]

length(colnames(moj.spp.pf)) - length(table(match(colnames(moj.spp.pf), colnames(moj.spp.op))))
length(colnames(moj.spp.op)) - length(table(match(colnames(moj.spp.op), colnames(moj.spp.pf))))
length(table(match(colnames(moj.spp.pf), colnames(moj.spp.op))))

moj.euler = plot(euler(c(A = 18, B = 2, "A&B" = 11)),
                 legend = NULL, quantities = list(cex = 4),
                 fills = list(fill = c("grey", "#ea4335")))


# Paragominas
par.spp.pf = par[22:42, 5:ncol(par)][colSums(par[22:42, 5:ncol(par)]) > 0]
par.spp.lf = par[1:22, 5:ncol(par)][colSums(par[1:22, 5:ncol(par)]) > 0]

length(colnames(par.spp.pf)) - length(table(match(colnames(par.spp.pf), colnames(par.spp.lf))))
length(colnames(par.spp.lf)) - length(table(match(colnames(par.spp.lf), colnames(par.spp.pf))))
length(table(match(colnames(par.spp.pf), colnames(par.spp.lf))))


par.euler = plot(euler(c(A = 4, B = 5, "A&B" = 15)),
                 legend = NULL, quantities = list(cex = 4),
                 fills = list(fill = c("grey", "#4285f4")))


# Tartarugalzinho + Porto_Grande
tar.spp.pf = tar[5:10, 5:ncol(tar)][colSums(tar[5:10, 5:ncol(tar)]) > 0]
tar.spp.ep = tar[1:4, 5:ncol(tar)][colSums(tar[1:4, 5:ncol(tar)]) > 0]

length(colnames(tar.spp.pf)) - length(table(match(colnames(tar.spp.pf), colnames(tar.spp.ep))))
length(colnames(tar.spp.ep)) - length(table(match(colnames(tar.spp.ep), colnames(tar.spp.pf))))
length(table(match(colnames(tar.spp.pf), colnames(tar.spp.ep))))

tar.euler = plot(euler(c(A = 8, B = 1, "A&B" = 7)),
                 legend = NULL, quantities = list(cex = 4),
                 fills = list(fill = c("grey", "#fbbc04")))


###########################################
### PROPORTIONAL OCCURRENCE PER HABITAT ###
###########################################

# Almerim
# prepara os dados
alm.prop = alm.spp.tx[colSums(alm.spp.tx) > 0]
alm.prop = as.data.frame(aggregate(alm.prop,
                                   by = list(habitat = substring(rownames(alm.spp.tx), 1, 2)), sum))
alm.prop = as.data.frame(t(alm.prop[2:ncol(alm.prop)]) / rowSums(t(alm.prop[2:ncol(alm.prop)])))

alm.prop.levels = rownames(alm.prop[order(-alm.prop$V1, alm.prop$V2), ])

alm.prop = t(alm.prop)
rownames(alm.prop) = unique(substring(rownames(alm.spp.tx), 1, 2))
alm.prop = melt(alm.prop)
alm.prop$Var2 = factor(alm.prop$Var2, levels = alm.prop.levels)

alm.records = colSums(alm[names(alm.spp.tx)])

# grafico
alm.prop.graph = 
  
  ggplot(data = alm.prop[order(alm.prop$Var1), ],
         aes(x = Var2, y = value * 100, fill = Var1)) +
  
  labs(x = NULL,
       y = "Records per 10 km walked (%)",
       fill = NULL) +
  
  scale_x_discrete(labels = unique(gsub("_", " ",
                                 paste0(alm.prop$Var2, " (",
                                        alm.records[match(alm.prop$Var2,
                                                          names(alm.records))], ")")))) +
  scale_fill_manual(values = c("grey", "#34a853"),
                    labels = c("Primary forest", "Secondary forest")) +
  
  geom_bar(stat = "identity") +
  
  theme_minimal(base_size = 20) +
  theme(panel.grid = element_blank(),
        axis.text.x = element_text(colour = "black"),
        axis.text.y = element_text(colour = "black", face = "italic"),
        axis.ticks = element_line(colour = "black", size = 0.5),
        axis.ticks.y = element_blank()) +
  theme(legend.position = "bottom")

#ggsave(alm.prop.graph + coord_flip(), filename = "./new_figures/alm.prop.pdf", width = 25, height = 20, units = "cm")


# Moju
# prepara os dados
moj.prop = moj.spp.tx[colSums(moj.spp.tx) > 0]
moj.prop = as.data.frame(aggregate(moj.prop,
                                   by = list(habitat = substring(rownames(moj.spp.tx), 1, 2)), sum))
moj.prop = as.data.frame(t(moj.prop[2:ncol(moj.prop)]) / rowSums(t(moj.prop[2:ncol(moj.prop)])))

moj.prop.levels = rownames(moj.prop[order(moj.prop$V1, -moj.prop$V2), ])

moj.prop = t(moj.prop)
rownames(moj.prop) = unique(substring(rownames(moj.spp.tx), 1, 2))
moj.prop = melt(moj.prop)
moj.prop$Var1 = factor(moj.prop$Var1, levels = c("PF", "OP"))
moj.prop$Var2 = factor(moj.prop$Var2, levels = moj.prop.levels)


# grafico
moj.prop.graph = 
  
  ggplot(data = moj.prop[order(moj.prop$Var1), ],
         aes(x = Var2, y = value * 100, fill = Var1)) +
  
  labs(x = NULL,
       y = "Records per 10 km walked (%)",
       fill = NULL) +
  
  scale_x_discrete(labels = gsub("_", " ", levels(moj.prop$Var2))) +
  scale_fill_manual(values = c("grey", "#ea4335"),
                    labels = c("Primary forest", "Oil palm plantation")) +
  
  geom_bar(stat = "identity") +
  
  theme_minimal(base_size = 20) +
  theme(panel.grid = element_blank(),
        axis.text.x = element_text(colour = "black", #face = "italic",
                                   #angle = 90,
                                   hjust = 1,
                                   vjust = 0.5,
                                   margin = margin(-10, 0, 0, 0)),
        axis.text.y = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5),
        axis.ticks.x = element_blank()) +
  theme(legend.position = "bottom")

#ggsave(moj.prop.graph, filename = "moj.prop.pdf", width = 20, height = 20, units = "cm")


# Paragominas
# prepara os dados
par.prop = par.spp.tx[colSums(par.spp.tx) > 0]
par.prop = as.data.frame(aggregate(par.prop,
                                   by = list(habitat = substring(rownames(par.spp.tx), 1, 2)), sum))
par.prop = as.data.frame(t(par.prop[2:ncol(par.prop)]) / rowSums(t(par.prop[2:ncol(par.prop)])))

par.prop.levels = rownames(par.prop[order(par.prop$V1, -par.prop$V2), ])

par.prop = t(par.prop)
rownames(par.prop) = unique(substring(rownames(par.spp.tx), 1, 2))
par.prop = melt(par.prop)
par.prop$Var1 = factor(par.prop$Var1, levels = c("PF", "LF"))
par.prop$Var2 = factor(par.prop$Var2, levels = par.prop.levels)


# grafico
par.prop.graph = 
  
  ggplot(data = par.prop[order(par.prop$Var1), ],
         aes(x = Var2, y = value * 100, fill = Var1)) +
  
  labs(x = NULL,
       y = "Records per 10 km walked (%)",
       fill = NULL) +
  
  scale_x_discrete(labels = gsub("_", " ", levels(par.prop$Var2))) +
  scale_fill_manual(values = c("grey", "#4285f4"),
                    labels = c("Primary forest", "Logged forest")) +
  
  geom_bar(stat = "identity") +
  
  theme_minimal(base_size = 20) +
  theme(panel.grid = element_blank(),
        axis.text.x = element_text(colour = "black", #face = "italic",
                                   #angle = 90,
                                   hjust = 1,
                                   vjust = 0.5,
                                   margin = margin(-10, 0, 0, 0)),
        axis.text.y = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5),
        axis.ticks.x = element_blank()) +
  theme(legend.position = "bottom")

#ggsave(par.prop.graph, filename = "par.prop.pdf", width = 20, height = 20, units = "cm")


# Tartarugalzinho + Porto_Grande
# prepara os dados
tar.prop = tar.spp.tx[colSums(tar.spp.tx) > 0]
tar.prop = as.data.frame(aggregate(tar.prop,
                                   by = list(habitat = substring(rownames(tar.spp.tx), 1, 2)), sum))
tar.prop = as.data.frame(t(tar.prop[2:ncol(tar.prop)]) / rowSums(t(tar.prop[2:ncol(tar.prop)])))

tar.prop.levels = rownames(tar.prop[order(tar.prop$V1, -tar.prop$V2), ])

tar.prop = t(tar.prop)
rownames(tar.prop) = unique(substring(rownames(tar.spp.tx), 1, 2))
tar.prop = melt(tar.prop)
tar.prop$Var1 = factor(tar.prop$Var1, levels = c("PF", "EP"))
tar.prop$Var2 = factor(tar.prop$Var2, levels = tar.prop.levels)


# grafico
tar.prop.graph =
  
  ggplot(data = tar.prop[order(tar.prop$Var1), ],
         aes(x = Var2, y = value * 100, fill = Var1)) +
  
  labs(x = NULL,
       y = "Records per 10 km walked (%)",
       fill = NULL) +
  
  scale_x_discrete(labels = gsub("_", " ", levels(tar.prop$Var2))) +
  scale_fill_manual(values = c("grey", "#fbbc04"),
                    labels = c("Primary forest", "Eucalypt plantation")) +
  
  geom_bar(stat = "identity") +
  
  theme_minimal(base_size = 20) +
  theme(panel.grid = element_blank(),
        axis.text.x = element_text(colour = "black", #face = "italic",
                                   #angle = 90,
                                   hjust = 1,
                                   vjust = 0.5,
                                   margin = margin(-10, 0, 0, 0)),
        axis.text.y = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5),
        axis.ticks.x = element_blank()) +
  theme(legend.position = "bottom")

#ggsave(tar.prop.graph, filename = "tar.prop.pdf", width = 20, height = 20, units = "cm")


ggsave(grid.arrange(par.euler, par.prop.graph, alm.euler, alm.prop.graph,
                    tar.euler, tar.prop.graph, moj.euler, moj.prop.graph,
                    ncol = 2),
       filename = "./new_figures/Fig2.pdf",
       w = 20 * 4, h = 20 * 4, units = "cm")


####################
### ELTON TRAITS ###
####################

elton = read.table("https://ndownloader.figshare.com/files/5631084",
                   header = TRUE,
                   sep = "\t")

speciesPaula = colnames(trilhas[5:ncol(trilhas)])
speciesPaula = gsub("_", " ", speciesPaula)

# Species not found in Elton Traits database
speciesPaula[is.na(elton$Scientific[match(speciesPaula, elton$Scientific)])]

# Change species name to match with those in Elton Traits database
speciesPaula[speciesPaula == "Mazama nemorivaga"] = "Mazama gouazoubira"
speciesPaula[speciesPaula == "Microsciurus sp."] = "Sciurus aestuans"
speciesPaula[speciesPaula == "Saguinus ursulus"] = "Saguinus niger"
speciesPaula[speciesPaula == "Saimiri collinsi"] = "Saimiri sciureus"
speciesPaula[speciesPaula == "Sapajus apella"] = "Cebus apella"
speciesPaula[speciesPaula == "Sapajus libidinosus"] = "Cebus libidinosus"

# Subset Elton Traits database
eltonSubset = cbind(elton[match(speciesPaula, elton$Scientific), ],
                    Scientific.Paula = colnames(trilhas[5:ncol(trilhas)]))

# Calculation of the trophic level
dietWeight = data.frame(diet = colnames(eltonSubset[4:13]),
                        weight = c(4, 5, 5, 5, 5, 5, 2, 2, 3, 1))

eltonSubset$Trophic.Level = (eltonSubset[, 4] * dietWeight[1, 2] +
                               eltonSubset[, 5] * dietWeight[2, 2] +
                               eltonSubset[, 6] * dietWeight[3, 2] +
                               eltonSubset[, 7] * dietWeight[4, 2] +
                               eltonSubset[, 8] * dietWeight[5, 2] +
                               eltonSubset[, 9] * dietWeight[6, 2] +
                               eltonSubset[, 10] * dietWeight[7, 2] +
                               eltonSubset[, 11] * dietWeight[8, 2] +
                               eltonSubset[, 12] * dietWeight[9, 2] +
                               eltonSubset[, 13] * dietWeight[10, 2])/100

# Select only relevant columns
eltonSubset = eltonSubset[c(2, 27, 16, 28, 24)]

# Add a column with a vulnerability index
eltonSubset$Vulnerability.Index = NA

# See the object
head(eltonSubset)


###########################
### VULNERABILITY INDEX ###
###########################

spp = list()

for (i in 5:ncol(trilhas)) {
  
  sp = tapply(trilhas[, i],
              paste(trilhas$municipio, trilhas$ambiente),
              sum)
  
  sp = as.data.frame(cbind(sp[which(grepl("PF", rownames(sp)) == "FALSE")],
                           sp[which(grepl("PF", rownames(sp)) == "TRUE")]))
  
  colnames(sp) = c("Treatment", "Control")
  rownames(sp) = c("SF", "OP", "LF", "EP")
  
  sp$Vulnerability.Index = log((sp$Treatment+1) / (sp$Control+1))
  
  sp$LandUseType = rownames(sp)
  
  sp$Species = colnames(trilhas)[i]
  
  rownames(sp) = NULL
  
  sp = sp[c(2, 4, 1, 3), ]
  
  spp[[i]] = sp
  
}

spp = do.call(rbind, spp)
head(spp)

eltonSubset = rbind(eltonSubset, eltonSubset, eltonSubset, eltonSubset)

eltonSubset$LandUseType = rep(c("Oil palm plantation",
                                "Eucalypt plantation",
                                "Secondary forest",
                                "Logged forest"), each = 46)
eltonSubset$LandUseType = factor(eltonSubset$LandUseType,
                                 levels = c("Logged forest",
                                            "Secondary forest",
                                            "Eucalypt plantation",
                                            "Oil palm plantation"))


eltonSubset$Vulnerability.Index = c(subset(spp, LandUseType == "OP")$Vulnerability.Index,
                                    subset(spp, LandUseType == "EP")$Vulnerability.Index,
                                    subset(spp, LandUseType == "SF")$Vulnerability.Index,
                                    subset(spp, LandUseType == "LF")$Vulnerability.Index)

head(eltonSubset)


eltonSubset$ForStrat.Value = factor(eltonSubset$ForStrat.Value,
                                    levels = c("G", "S", "Ar"))

# Graph
traits.plot = 
  ggplot(data = eltonSubset[order(eltonSubset$Vulnerability.Index), ],
         aes(x = -Vulnerability.Index, y = ForStrat.Value,
             size = BodyMass.Value/1000, fill = -Vulnerability.Index)) +
  
  labs(x = "Vulnerability index",
       y = "Foraging stratum",
       size = "Body mass (kg)",
       fill = "Vulnerability index") +

  geom_vline(xintercept = 0, size = 0.5,
             colour = "grey", linetype = "dashed") +
  geom_point(shape = 21, colour = "black", alpha = 0.5) +
  
  scale_x_continuous(limits = c(-4, 6)) +
  scale_y_discrete(labels = c("Ground", "Scansorial", "Arboreal")) +
  scale_fill_viridis_c() +
  scale_size_continuous(range = c(3, 14)) +
  
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank(),
        panel.border = element_rect(colour = "black", size = 0.5),
        axis.title = element_text(colour = "black"),
        axis.text = element_text(colour = "black"),
        axis.ticks = element_line(colour = "black", size = 0.5)) +
  theme(legend.title = element_text(size = 14),
        legend.text = element_text(size = 12)) +
  facet_wrap(. ~ LandUseType)

traits.plot

ggsave(traits.plot,
       filename = "./new_figures/Fig6.pdf",
       width = 30, height = 20, units = "cm")


### Table S1
transect.code = read.csv("./new_figures/!transect_code.csv")

colnames(transect.code)[2] = "habitat_transect"

transect.code$transect = substring(transect.code$habitat_transect, 4)

transect.code$municipality = trilhas$municipio[match(
  transect.code$habitat_transect, rownames(trilhas))]

transect.code$decimalLatitude = coordinates$decimalLatitude[match(
  transect.code$habitat_transect, rownames(coordinates))]

transect.code$decimalLongitude = coordinates$decimalLongitude[match(
  transect.code$habitat_transect, rownames(coordinates))]

transect.code$effort = trilhas$metros_percorridos[match(
  transect.code$habitat_transect, rownames(trilhas))]

# Salva a Table S1
write.csv(transect.code, "./new_figures/tables1.csv", row.names = FALSE)


### Table S3
tables2 = aggregate(trilhas[-c(1:4)],
                    by = list(paste(trilhas$municipio,
                                    trilhas$ambiente,
                                    sep = "_")),
                    FUN = sum)

row.names(tables2) = tables2$Group.1
tables2$Group.1 = NULL
tables2 = as.data.frame(t(tables2))

tables2$relative.abundance = round(rowSums(tables2)/sum(tables2)*100, 2)

# Salva a Table S2
write.csv(tables2, "./new_figures/tables2.csv")