############################################
# Requirements

# Libraries
library(copula)
library(corrplot)

############################################################
# Data preprocessing

# Construct structure of formula based on ecological prior knowledge
formulaInput <- BENT_MMI_COND ~ AGGR_ECO9_2015 + LRBS_USE + L_XFC_NAT + 
  L_XCMGW + W1_HALL +
  NHDWAT_NADP2009_MEAN_NO3 + NHDWAT_NADP2009_MEAN_SO4 +
  NHDWAT_ELEV + NHDWAT_SLOPE + NHDWAT_PCT_CANOPY+ NHDWAT_PCT_IMPERV +
  NHDWAT_PCT_SAND + TMAX_ANN + WSAREA_NARS+PCT_AG + PCT_WET + PCT_SHRUB_GRASS

# Load original data and structure variables
datFrame <- read.csv(file="CombinedNRSA0809.csv")
datFrame$BENT_MMI_COND <- relevel(factor(datFrame$BENT_MMI_COND), "Poor")
datFrame$AGGR_ECO9_2015 <- factor(datFrame$AGGR_ECO9_2015)

# Reduce data set to relevant variables
datFrame <- datFrame[, which(names(datFrame) %in% all.vars(formulaInput))]
save(datFrame, file="CombinedNRSA0809_datFrame")

########################
# Descriptive statistics

# Categorical covariates in percent
all.equal(sum(round(summary(datFrame$BENT_MMI_COND) / nrow(datFrame), 4) * 100 - 
                c(rep(0, 2), 0.01)), 100)
all.equal(sum(round(summary(datFrame$AGGR_ECO9_2015) / nrow(datFrame), 4)*100-
                c(0.01, rep(0, length(summary(datFrame$AGGR_ECO9_2015))-1))), 100)
round(summary(datFrame$BENT_MMI_COND) / nrow(datFrame), 4) * 100 - c(rep(0, 2), 0.01)
round(summary(datFrame$AGGR_ECO9_2015) / nrow(datFrame), 4)*100-
  c(0.01, rep(0, length(summary(datFrame$AGGR_ECO9_2015))-1))

# Continuous covariates
RES <- sapply(1:ncol(datFrame[, -c(1, 2)]), function(x) 
  round(quantile(datFrame[, -c(1, 2)] [, x]), 2))
colnames(RES) <- names(datFrame[, -c(1, 2)])
RES

#########################################
# Gaussian copula correlation matrix plot
# Supplemental material Figure S13

# Estimate gaussian copula correlation matrix
pobsDat <- pobs(datFrame[, all.vars(formulaInput)[-1] ])
normDat <- apply(pobsDat, 2, qnorm)
corGaussCopula <- cor(normDat)
# Save model
simDataGenPre <- list(formula=formulaInput, corGaussCopula=corGaussCopula,
                      trueCoef=seq(-2, 2, length.out=16)[-8])
save(simDataGenPre, file="simDataGenPre", compress="xz")

# Visualization
load("simDataGenPre")
codeConversion <- data.frame(varName=c("AGGR_ECO9_2015", "BENT_MMI_COND", "LRBS_USE", "L_XCMGW",
                                     "L_XFC_NAT", "NHDWAT_ELEV", "NHDWAT_NADP2009_MEAN_NO3",
                                     "NHDWAT_NADP2009_MEAN_SO4", "NHDWAT_PCT_CANOPY",
                                     "NHDWAT_PCT_IMPERV", "NHDWAT_PCT_SAND", "NHDWAT_SLOPE",
                                     "PCT_AG", "PCT_WET", "PCT_SHRUB_GRASS", "W1_HALL",
                                     "TMAX_ANN", "WSAREA_NARS"), 
                           newName=c("Ecoregion", 
                                     "Benthic MMI condition class", 
                                     "Bed \n stability",
                                     "Riparian \n vegetation \n condition", 
                                     "Fish \n cover", 
                                     "Elevation",
                                     "NO3 \n deposition", 
                                     "SO4 \n deposition", 
                                     "Tree \n canopy",
                                     "Impervious \n surface", 
                                     "Percent \n sandy \n soils", 
                                     "Catchment \n slope", 
                                     "Agriculture", 
                                     "Wetlands",
                                     "Shrub/Grass", 
                                     "Human \n Disturbance \n Index", 
                                     "Max \n Temperature",
                                     "Watershed \n area"))

inserNames <- rep(NA, length(dimnames(simDataGenPre$corGaussCopula)[[1]]) )
for(j in 1:length(dimnames(simDataGenPre$corGaussCopula)[[1]]) ){
  inserNames[j] <- gsub(" \n ", " ", 
                        codeConversion[
                          codeConversion$varName==
                            dimnames(simDataGenPre$corGaussCopula)[[1]][j], "newName"])
}

# Export graphics
dimnames(simDataGenPre$corGaussCopula)[[1]] <- inserNames
dimnames(simDataGenPre$corGaussCopula)[[2]] <- dimnames(simDataGenPre$corGaussCopula)[[1]]
pdf("GaussianCorrplot.pdf", height=7*1.2)
corrplot(simDataGenPre$corGaussCopula, method="ellipse", type="upper", tl.col = "black")
dev.off()
