#Codes from:  
#Environment and biotic associations jointly shape cross-taxon aquatic communities 
#in southern South American ponds 

#These codes were adapted by LB Epele, from  R codes available on 
#https://www.helsinki.fi/en/researchgroups/statistical-ecology/software/hmsc 
#and Ovaskainen, O., & Abrego, N. (2020). Joint species distribution 
#modelling. With applications in R. Cambridge University Press. To fully understand
#the applied pipeline

#Contact: luisbepele@comahue-conicet.gob.ar
#Last update November 2025

#BEFORE STARTING####
#Load required packages
library(ape)
library(circlize)
library(colorspace)
library(corrplot)
library(ggplot2)
library(Hmsc)
library(reshape2)
library(vioplot)


#Make the script reproducible
set.seed(1)

###Set  working directory####
setwd(
  dirname(
    rstudioapi::callFun(
      'getActiveDocumentContext'
    )$path
  )
);getwd()

localDir = "."
dataDir = file.path(localDir, "data") #data file should be located in a folder named "data"
modelDir = file.path(localDir, "models")
resultDir = file.path(localDir, "results")
if(!dir.exists(modelDir)) dir.create(modelDir)
if (!dir.exists(resultDir)) dir.create(resultDir)

#Load data####
load(file=file.path(dataDir,"data.RData"))

#JSDM with Hmsc package####
###Set model####

#Environmental covariates
XData = data.frame(site = factor(df$site), pH = df$pH,  depth = df$depth, 
                   EC= log(df$EC), TP = df$TP, MAT=df$MAT, aridity=df$aridity, 
                   PSEAS = df$PSEAS, MTWQ = df$MTWQ)

#Set relationships among them
XFormula = ~  pH + depth + TP + EC + MAT + aridity + PSEAS +  MTWQ  

#Define taxonomic data (macroinvertebrates+macrophytes)
YData <- as.matrix(df[,-c(1:21)])
YData <- t(YData)
YData <- t(YData[sel.sp.hmsc %in% "S",])#remove non identified taxa

#Select more common taxa (taxa with more than 7 presence records)
sel.sp <- colSums(YData>0)>7
YData <- YData[,sel.sp]

#Define Y based only on presence-absence data
Y <- 1*(YData>0)

# Include traits data into the TrData dataframe
TrData = data.frame(Species = traits$species, FFG = as.factor(traits$FFG),
                    Dispersal = traits$Dispersion,
                    Life_cycle = traits$Life_cycle_duration,
                    Respiration = traits$Respiration,
                    Resistance_form = traits$Resistance_form)
#Select more common taxa
TrData = TrData[sel.sp.hmsc %in% "S",]#remove families
TrData = TrData[sel.sp,]

# The identities of wetlands are given by row names
rownames (TrData) <- colnames(YData)

# As trait formula we include:
TrFormula = ~ FFG + Dispersal + Life_cycle + Respiration + Resistance_form

#Calculation of the phylogenetic tree
#Select more common taxa
phylo = phylo[sel.sp.hmsc %in% "S",]#remove families
phylo = phylo[sel.sp,]
#Produce phylogenetic tree
phylo.tree = as.phylo(~kindom/phyllum/class/order/family/genus/species, data = phylo, collapse = FALSE) 
phylo.tree$edge.length = rep(1, length(phylo.tree$edge))
#Check it
plot.phylo(phylo.tree)


#Study desing
studyDesign = data.frame(site = XData$site) 

#Define a spatial random effect at the level of the wetland (site)
# Set x- and y-coordinates of the sites 
xy <- as.matrix(cbind(df$lon,df$lat))
rownames(xy)=df$site
colnames(xy)=c("x-coordinate","y-coordinate")

#Random effect
rL.space = HmscRandomLevel(sData = xy)


#Set the model
m = Hmsc(Y=Y, XData = XData, XFormula=XFormula, phyloTree = phylo.tree, 
         TrData = TrData, TrFormula = TrFormula, distr="probit", 
         studyDesign=studyDesign, ranLevels=list(site = rL.space))
                   
#Fit the model####
#Specify sampling parameters
thin = 1000 # thinning of sampling
samples = 250 # number of posterior samples per chain
transient = ceiling(0.5*samples*thin) # number of first iterations used as burn in after which sampling starts
nChains = 4 # number of MCMC chains sampled

####Fit JSDM model####
#WARNING! This would take a couple of days in personal CPUs
m = sampleMcmc(m, samples = samples, thin=thin,
               adaptNf=rep(ceiling(0.4*samples*thin),m$nr), 
               transient = transient,
               nChains = nChains,
               nParallel = nChains) 

####Evaluate model convergence####
post=convertToCodaObject(m) #covert to coda object

# Beta parameters (species-environment)
par(mfrow=c(1,2))
hist(effectiveSize(post$Beta), main="ess(beta)") # effective sample size
vioplot(gelman.diag(post$Beta, multivariate = FALSE)$psrf,main="psrf(beta)") #potential scale reduction factor

# Gamma parameters (fami-environment)
hist(effectiveSize(post$Gamma), main="ess(omega)")
vioplot(gelman.diag(post$Gamma,multivariate = FALSE)$psrf,main="psrf(omega)")

# Omega parameters (family-to-family associations)
for(k in 1:2){
  postOmega = post$Omega[[k]]
  z = dim(postOmega[[1]])[2]
  if(z > 50){
    sel = sample(1:z, size = 50)
    for(i in 1:length(postOmega)){
      postOmega[[i]] = postOmega[[i]][,sel]
    }
  }
}
hist(effectiveSize(postOmega), main="ess(gamma)")
vioplot(gelman.diag(postOmega,multivariate = FALSE)$psrf,main="psrf(gamma)")


#### Compute model fit (predictive power)####
#WARNING! this would take more than 20 days in personal computers
partition = createPartition(m, nfolds = 8)
#WARNING: you need 32 cores working at the same time
preds = pcomputePredictedValues(m, partition=partition, nParallel = 32)
MF = evaluateModelFit(m, predY = preds)

#plot discriminatory power Tjur R2
plot(colSums(m$Y)/m$ny,MF$TjurR2,
     main=paste("TjurR2 . Mean = ", round(mean(MF$TjurR2,na.rm = TRUE),2),
                ".", sep=""), xlab = "Prevalence")

#plot discriminatory power AUC
plot(colSums(m$Y)/m$ny,MF$AUC,
     main=paste("AUC . Mean = ", round(mean(MF$AUC,na.rm = TRUE),2),
                ".", sep=""), xlab = "Prevalence")

##Explore and plot parameter estimates####
# Variance partitioning of the model.
# We include the intercept in the local variables, and thus perform the variance partitioning
VP= computeVariancePartitioning(m)
rowSums(VP$vals)*100/48#proportion per factor

# Fig. S4
pdf(file = file.path(resultDir,"FigS3.pdf"), width = 10, height = 6)
plotVariancePartitioning(m, VP, las=2, 
                         cols= c("#440154FF", "#472D7BFF","#3B528BFF","#2C728EFF",
                                 "#21908CFF","#27AD81FF","#5DC863FF","#AADC32FF",
                                 "#FDE725FF"), args.leg=list(bg="white",cex=0.7))
dev.off()

#Beta-plot showing the estimates of species-environment relations (Fig.1)
postBeta = getPostEstimate(m, parName="Beta")

pdf(file = file.path(resultDir,"Figure1.pdf"), width = 8, height = 8)
plotBeta(m, post=postBeta, supportLevel = 0.95, param = "Sign", plotTree = T, 
         spNamesNumbers=c(T, F), split=0.4,
         colors = colorRampPalette(c("blue", "white", "red")))
dev.off()

#Bar plot (Figure 1)
supportLevel = 0.95
mbeta = postBeta$mean
betaP = postBeta$support
toPlot = 2 * betaP - 1
toPlot = toPlot * ((betaP > supportLevel) + (betaP < (1 - supportLevel)) > 0)
betaMat = matrix(toPlot, nrow = m$nc, ncol = ncol(m$Y))
rownames(betaMat) = m$covNames
colnames(betaMat) = m$spNames


bar.beta <- data.frame(positive=rowSums(betaMat > 0))
bar.beta$negative <- rowSums(betaMat < 0)
bar.beta <- bar.beta[-1,]
bar.beta$id <- rownames(bar.beta)
melt.bar.beta <- melt(bar.beta)
melt.bar.beta$id <- forcats::fct_inorder(as.factor(melt.bar.beta$id))

bar.species <- ggplot(melt.bar.beta, aes(id)) + 
  geom_bar(aes(weight = value, fill = variable)) +
  scale_fill_manual(values = c("blue","red")) +
  ggtitle("Species-environment relations") +
  xlab("Environmental variables") + ylab("Number of species") +
  theme(
    panel.background = element_rect(fill = "transparent", color = "black"), # bg of the panel
    plot.background = element_rect(fill = "transparent"), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    #legend.position="bottom",
    strip.background = element_blank(),
    strip.text.y = element_blank(),
    axis.text.x = element_text(angle=90,hjust=1, color="black"),
    axis.text.y = element_text(color="black"),
    axis.ticks = element_line(color="black"))
bar.species

pdf(file = file.path(resultDir,"Figure1a.pdf"), width = 8, height = 5)
bar.species
dev.off()

#Gamma-plot (Figure 2)
postGamma = getPostEstimate(m, parName="Gamma")

pdf(file= file.path(resultDir,"Figure2.pdf"), width = 6, height = 4)

plotGamma(m, post=postGamma, supportLevel = 0.95, param = "Sign",
          colors = colorRampPalette(c("blue", "white", "red")),
          main="Gamma (support: 0.95)")
plotGamma(m, post=postGamma, supportLevel = 0.90, param = "Sign",
          colors = colorRampPalette(c("blue", "white", "red")),
          main="Gamma (support: 0.90)")

dev.off()

# Influence of traits, measured as the variation they
# explain among the responses of the species to environmental variables

VP.trait <- data.frame(beta = VP$R2T$Beta[2:9])
VP.trait$variable <- forcats::fct_inorder(as.factor(rownames(VP.trait)))

bar.trait <- ggplot(VP.trait, aes(variable)) + 
  geom_bar(aes(weight = beta), fill = c("darkblue")) +
  ggtitle("Species-environment relations") +
  xlab("Environmental variables") + ylab("Number of species") +
  theme(
    panel.background = element_rect(fill = "transparent", color = "black"), # bg of the panel
    plot.background = element_rect(fill = "transparent"), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    #legend.position="bottom",
    strip.background = element_blank(),
    strip.text.y = element_blank(),
    axis.text.x = element_text(angle=90,hjust=1, color="black"),
    axis.text.y = element_text(color="black"),
    axis.ticks = element_line(color="black"))
bar.trait
 
pdf(file = file.path(resultDir,"FigureS4.pdf"), width = 8, height = 7)
bar.trait
dev.off()

##Species associations order whit phylogeny (Figure 3)
OmegaCor = computeAssociations(m)

#plot function
plotChord <- function(plotOrder, threshold, filename) {
  toPlot <- ((OmegaCor[[1]]$support > threshold) +
               (OmegaCor[[1]]$support < (1 - threshold)) > 0) * OmegaCor[[1]]$mean
  toPlot <- sign(toPlot)
  toPlot <- toPlot[plotOrder, plotOrder]
  diag(toPlot) <- 0
  sel <- which(toPlot != 0 & upper.tri(toPlot), arr.ind = TRUE)
  if (nrow(sel) == 0) {
    warning("No associations at this threshold.")
    return(invisible(NULL))
  }
  
  edge_df <- data.frame(
    from  = rownames(toPlot)[sel[,1]],
    to    = colnames(toPlot)[sel[,2]],
    value = toPlot[sel],
    stringsAsFactors = FALSE
  )
  edge_df$col <- ifelse(edge_df$value > 0, "red", "blue")
  
  # Keep only species that actually appear in associations
  species_used <- unique(c(edge_df$from, edge_df$to))
  ord <- plotOrder[plotOrder %in% species_used]
  grid_cols <- setNames(rep("grey80", length(ord)), ord)
  
  # Make the plot
  pdf(file = filename, width = 6, height = 6)
  circos.clear()
  circos.par(cell.padding = c(0, 0, 0, 0))  
  
  chordDiagram(
    x = edge_df[, c("from", "to")],     
    order = ord,                        # only used species
    grid.col = grid_cols,               
    col = edge_df$col,                
    transparency = 0.3,
    directional = FALSE,
    annotationTrack = "grid",          
    preAllocateTracks = list(track.height = 0.08)  
  )
  
  # Draw labels OUTSIDE the grey border in the pre-allocated (outermost) track
  circos.trackPlotRegion(
    track.index = 1,
    bg.border = NA,
    panel.fun = function(x, y) {
      sector <- get.cell.meta.data("sector.index")
      if (sector %in% species_used) {
        xlim <- get.cell.meta.data("xlim")
        y_out <- get.cell.meta.data("ylim")[2] + convert_y(2.5, "mm", track.index = 1)
        circos.text(
          x = mean(xlim),
          y = y_out,
          labels = sector,
          facing = "downward",
          niceFacing = TRUE,
          cex = 0.65
        )
      }
    }
  )
  
  dev.off()
  circos.clear()
}

# Phylo order
plotOrder <- rev(phylo.tree$tip.label)

# 80% threshold
plotChord(plotOrder, threshold = 0.80,
          filename = file.path(resultDir, "Figure3_80.pdf"))
# 90% threshold
plotChord(plotOrder, threshold = 0.90,
          filename = file.path(resultDir, "Figure3_90.pdf"))




#Count relations#
supportLevel = 0.90
toPlot = ((OmegaCor[[1]]$support>supportLevel)
          + (OmegaCor[[1]]$support<(1-supportLevel))>0)*OmegaCor[[1]]$mean
toPlot = sign(toPlot)

supportLevel = 0.80
toPlot2 = ((OmegaCor[[1]]$support>supportLevel)
          + (OmegaCor[[1]]$support<(1-supportLevel))>0)*OmegaCor[[1]]$mean
toPlot2 = sign(toPlot2)


#Count species-to-species associations
#90% probability
(sum(toPlot > 0)- 48)/2  #positive
sum(toPlot < 0)/2 #negative
sum(toPlot == 0)/2 #non detected

#80% probability
(sum(toPlot2 > 0)- 48)/2  #positive
sum(toPlot2 < 0)/2 #negative
sum(toPlot2 == 0)/2 #non detected

