
###################################################
##_________________________________________________
##
## R CODE FOR MANUSCRIPT
##
## "PRECIPITOUS DECLINES IN NORTHERN GULF OF 
##  MEXICO INVASIVE LIONFISH POPULATIONS
##  FOLLOWING THE EMERGENCE OF AN ULCERATIVE
##  SKIN DISEASE"
##
## LAST MODIFIED 20 AUGUST 2019
##
## WRITTEN BY HOLDEN EARL HARRIS
##
##_________________________________________________
###################################################

###################################################
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
##
## PART I -- LIONFISH RELATIVE CONDITION
##
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
###################################################

## CLEAN SLATE
rm(list=ls()) 

## WORKING LIBRARIES
library(dplyr)
library(car)
library(ggplot2)
library(agricolae)
library(FSA)

###################################################
##
## IA -- COMPUTE LENGTH-WEIGHTS 
##       FOR NR LIONFISH PRIOR TO 2013-2016

nr <- read.csv("./1_NR-Length-Weight-Prior2017.csv")

nr$Habitat = NULL; nr$Sample.ID = NULL; nr$Site_LF_count = NULL
nr$logTL = log(nr$TL)
nr$logWT = log(nr$WT)

## WEIGHT LENGTH LOG-LINEAR REGRESSION - ALL FISH
wt_length_reg <- lm(logWT ~ logTL, data = nr)
summary(wt_length_reg) ## a = 0.441, b = 3.44042
fitPlot(wt_length_reg)

###################################################
##
## IB -- COMPARE MALES AND FEMALES 
nrow(subset(nr, nr$Sex == "M")) ## n = 282 males
nrow(subset(nr, nr$Sex == "F")) ## n = 316 females

## WEIGHT LENGTH LOG-LINEAR REGRESSION
wl_reg_bysex <- lm(logWT ~ logTL * Sex, data = subset(nr, nr$Sex != "U"))
fitPlot(wl_reg_bysex, legend = "topleft", col = c("blue", "red"))
anova(wl_reg_bysex)
## Intercept (A) not different by sex:  F(1, 594) = 1.702, p = 0.196
## Sloppe (b) signif. diff. by sex:     F(1, 594) = 9.124, P = 0.003

## MALES WEIGHT LENGTH REGRESSION
m_wl_reg <- lm(logWT ~ logTL, data = subset(nr, nr$Sex == "M"))
a_m = exp(coef(m_wl_reg))[1]; a_m
b_m =     coef(m_wl_reg) [2]; b_m

## FEMALES WEIGHT LENGTH REGRESSION
f_wl_reg <- lm(logWT ~ logTL, data = subset(nr, nr$Sex == "F"))
a_f = exp(coef(f_wl_reg))[1]; a_f
b_f =     coef(f_wl_reg) [2]; b_f


###################################################
##
## IC -- COMPUTE RELATIVE CONDITION

## LIONFISH COLLECTED OCT AND NOV 2017
fish = read.csv("./2_Lionfish_TL_RelativeWeights.csv")

males <- subset(fish, fish$Sex == "M")
males$Ws = a_m * males$TL ^ b_m

females <- subset(fish, fish$Sex == "F")
females$Ws = a_f * females$TL ^ b_f

fish <- rbind(males, females)
fish$Kn <- fish$WT / fish$Ws 

## Summarize Kn
summ_relcond <- fish %>% 
  group_by(Sex, lesion.binary) %>% 
  summarise(Kn.mean = mean(Kn), 
            Kn.se = sd(Kn)/sqrt(n()),
            n = n(),
            n_string = paste("n =", n())) %>% 
  as.data.frame(); summ_relcond

summ_relcond$sex_disease <-  paste(summ_relcond$Sex, summ_relcond$lesion.binary, sep = "")
summ_relcond$sex_disease = factor(summ_relcond$sex_disease, levels = c("MH", "FH", "ML", "FL"))
summ_relcond$upCI = summ_relcond$Kn.mean + 1.96 * summ_relcond$Kn.se
summ_relcond$lowCI = summ_relcond$Kn.mean - 1.96 * summ_relcond$Kn.se
summ_relcond
#write.csv(summ_relcond, "./SUMMARY_Rel_Condition.csv", row.names = FALSE)


###################################################
## EXAMINE SIZES OF ULCERATED FISH

## HISTOGRAM SIZES
fish %>% filter(lesion.binary == "L") %>% 
  ggplot(aes(x=TL)) +
  geom_histogram()  +
  theme_bw()

## MIN AND MAX
ulcerated = fish %>% filter(lesion.binary == "L")
min(ulcerated$TL) ## 212 mm
max(ulcerated$TL) ## 352 mm

min(fish$TL) ## 118
max(fish$TL) ## 367

###################################################
##
## ID - ANALYSIS
## 2-WAY ANOVA: Kn ~ Sex * Disease
## TUKEY HSD MULTIPLE COMPARISONS

## ASSESS NORMALITY
hist(fish$Kn)
qqp(fish$Kn)

## ModelL Kn by Sex, Disease, and Interaction
lm_ulcer <- lm(Kn ~ Sex * lesion.binary, data = fish); summary(lm_ulcer)
plot(lm_ulcer$residuals); abline(h = 0) ## Residuals heterskedastic 
im <- influence.measures(lm_ulcer); colSums(im$is.inf)

aov_ulcer <- aov(Kn ~ Sex * lesion.binary, data = fish); summary(aov_ulcer)
## Sex insig.:           F(1,334) = 2.2270, p = 0.136560
## Disease signficicant: F(1,334) = 7.8063, p = 0.005507

TukeyHSD(aov_ulcer)
## Females with disease 8.78% lower, p = 0.0248980

plot(TukeyHSD(aov_ulcer))
lesion_hsd <- HSD.test(mod.lesion, c('sex', 'lesion.binary'), group = TRUE); lesion_hsd
groups <- lesion_hsd$groups$groups; groups


###################################################
##
##  IC - PLOT RELATIVE CONDTION 

pal_relcond = c("navajowhite1", "darkseagreen1", "navajowhite1", "darkseagreen1")

plot_relative_condition_by_sex <- 
  summ_relcond %>% 
  ggplot(aes(x = factor(sex_disease, levels = c("MH","ML","FH","FL")),
             y = Kn.mean, group = sex_disease, fill = sex_disease)) +
  geom_bar(stat = "identity", alpha = 0.95,
           position = position_dodge(width = 1), 
           color = "black", width = 0.8) +
  geom_errorbar(aes(ymin = Kn.mean - (1.96 * Kn.se), 
                    ymax = Kn.mean + (1.96 * Kn.se)),
                position=position_dodge(width=1),
                width = 0.15, size = 0.4, color = "black") +
  coord_cartesian(ylim = c(0.80, 1.00)) +
  ylab (expression("Relative condition ( K" [n] ~ ")" )) +
  xlab ("") +
  scale_fill_manual(values = pal_relcond) +
  scale_x_discrete(labels = c("Non-ulcerated\nmale", 
                              "Ulcerated\nmale",     
                              "Non-ulcerated\nfemale",
                              "Ulcerated\nfemale")) +
  geom_text(data = summ_relcond, aes(label=n_string), position=position_dodge(width=0.9),
            hjust = -0.07, vjust= -0.4, size = 3.2) +
  theme_classic() +
  theme(
    legend.position = "none",
    legend.background = element_rect(colour = 'black', fill = NA, linetype='solid'),
    axis.text.y = element_text(size = 9, color = 'black'),
    axis.title = element_text(size = 10.5),
    axis.text.x = element_text(size = 9, color = 'black'),
    axis.ticks.x = element_blank(),
    panel.background = element_rect(fill = "grey100")); plot_relative_condition_by_sex

## Save plot
#tiff(filename = "./Relative_condition.tif", width = 90, height = 90, 
#     units = "mm", res = 350)
#plot_relative_condition_by_sex
#dev.off()

######################################################################################################

###################################################
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
##
## PART II -- SIZE COMPOSITION AND RECRUITMENT
##
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
###################################################

rm(list=ls()) ## Clean slate

## Working libraries
library(dplyr)
library(ggplot2)
library(car)
library(MASS)
library(lme4)
library(nlme)
library(cowplot)

###################################################
##
## IIA -- DETERMINE AGE 0 CUTOFF BASED ON
##        LENGTH-AT-AGE DATA FROM FOGG et al. 2019
##        and DAHL et al. 2019

###################################################
##  FOGG et al. 2019 LENGTH AT AGE

fogg <- read.csv("./4_Length-at-Age-FOGG.csv")

fogg$yearclass <- ifelse(fogg$age < 1, "Age 0", 
                         ifelse(fogg$age < 2, "Age 1", "Age 2+"))

## SUMMARIZE
fogg %>% group_by(yearclass) %>% 
  summarise(median = median(TL_mm), mu = mean(TL_mm), sd = sd(TL_mm),
            min = min(TL_mm), max = max(TL_mm), n = n()) %>% 
  as.data.frame()

## VISUALIZE FOGG LENGTH-AT-AGE
hist(fogg$TL_mm, breaks = 36, probability = TRUE, ylim = c(0,0.018))
lines(density(subset(fogg$TL_mm, fogg$yearclass == "Age 0")), 
      col="blue", lty=2, lwd=2)
lines(density(subset(fogg$TL_mm, fogg$yearclass != "Age 0")), 
      col="red", lty=2, lwd=2)


###################################################
##  DAHL et al. 2019 LENGTH AT AGE
dahl <- read.csv("./5_Length-at-Age_DAHL.csv")
dahl$Age_Int = floor(dahl$Age)

## SUMMARIZE
dahl %>% group_by(Age_Int) %>% 
  summarise(median = median(TL), mu = mean(TL), sd = sd(TL),
            min = min(TL), max = max(TL), n = n()) %>% 
  as.data.frame()

## VISUALIZE DAHL LENGTH-AT-AGE
hist(dahl$TL, breaks = 36, probability = TRUE, ylim = c(0, 0.02))
for(i in unique(dahl$Age_Int)){
  lines(density(subset(dahl$TL, dahl$Age_Int == i)),
        col = i, lty = i)
}


###################################################
##  II DETERMINE CUTOFF LENGTH FOR AGE-0 
##     AS MEAN OF 95th PERCENTILE
brk = 0.05
quantile(subset(fogg$TL_mm, fogg$yearclass == "Age 0"), probs = seq(0, 1, brk))
quantile(subset(dahl$TL, dahl$Age < 1), probs = seq(0, 1, brk))

## Define average 95% quantile as cutoff
mean95 = mean(c(quantile(subset(fogg$TL_mm, fogg$yearclass == "Age 0"), probs = 0.95),
                quantile(subset(dahl$TL, dahl$Age < 1), probs = 0.95)))

cutoff = mean95[[1]]; cutoff

## SENSITIVITY ANALYSIS
# cutoff = 120 ## Below here May 2018 becomes insignificant
# cutoff = 178 ## Above here June 2018 becomes significant

###################################################
##
## IIC -- SUBSET FISH AS AGE-0 or AGE-1+

match <- read.csv("./3_Lionfish-TL-2014-2018.csv")
ulcer <- subset(match, match$lesion.binary == 1)

## NOT IN ARTICLE: ARE ULCERATED FISH ON AVERAGE LARGER?
ulcer$TL
t.test(match$TL, ulcer$TL) ## Yes, but small sample size. Not in article but worth considering later.

## SUMMARIZE DATA
summ_match <- match %>% 
  group_by(Year, Month, Month_Name) %>% 
  summarise(mu = mean(TL, na.rm = TRUE),
            se = sd(TL, na.rm = TRUE)/sqrt(n()),
            min = min(TL),
            max = max(TL),
            n = n(),
            n_string = paste("n =", n())) %>% 
  as.data.frame(); summ_match


match$Age0     <- ifelse(match$TL < cutoff, 1, 0)
match$Age1plus <- ifelse(match$TL > cutoff, 1, 0)

## CREATE DATA SET OF SAMPLES BY REMOVAL EVENT; SEPARATE AGE0 & AGE1+ BY CUTOFF SIZE
samp <- match %>% 
  group_by(Year, Month, Month_Name, TeamDiver, DateShot) %>% 
  summarise(n = sum(TL>0),
            Age0 = sum(TL < cutoff),
            Age1plus = sum (TL >= cutoff),
            P_Age0 = mean(Age0) / n,
            P_1plus = mean(Age1plus) / n) %>% 
  as.data.frame(); head(samp)

## QAQC
samp <- subset(samp, samp$n >= 30) ## Remove samples < 30
samp <- samp[!samp$TeamDiver == "Non Tournament Extras",]
samp$Year = as.factor(samp$Year)
samp$Month = as.factor(samp$Month)

## SUMMARIZE BY SAMPLE
summ_samp <- samp %>% 
  group_by(Year, Month, Month_Name) %>% 
  summarise("SE" = sd(P_Age0)/sqrt(n()),
            "Mean_P" = mean(P_Age0),
            "n" = n()) %>% 
  as.data.frame(); summ_samp


## EXAMINE SIZES OF ULCERATED FISH
## HISTOGRAM SIZES
match %>% filter(lesion.binary == "1") %>% 
  ggplot(aes(x=TL)) +
  geom_histogram(bins = 20) +
  theme_bw()

## MIN AND MAX
ulcerated = match %>% filter(lesion.binary == "1")
nrow(ulcerated)   ## n = 32
min(ulcerated$TL) ## 249 mm
max(ulcerated$TL) ## 334 mm


#####################################################
##
## IID -- SIZE COMPOSITION ANALYSIS
##        ANALYSIS WITH BINOMIAL GLM
##        and OUTPUT FOR TABLE 1 

m.age0.logit <- glm(Age0 / n ~  Month / Year, data = samp, weights = log(n), 
                    family = binomial(link = "logit"))
summary(m.age0.logit)

## CREATE OUTPUT TABLE
mod = m.age0.logit
coefs = as.data.frame(coef(summary(mod)))
summ = summ_samp
dec_places = 2
out = data.frame(Year = summ$Year)
out$Month = summ$Month
out$n = summ$n
out$'Proportion Age 0' = round(summ$Mean_P, 2)
out$'Odds ratio'= round(exp(coefs$Estimate), dec_places)
lowCI = round(exp(coefs$Estimate - 1.96 * coefs$`Std. Error`),2)
upCI = round(exp(coefs$Estimate + 1.96 * coefs$`Std. Error`),2)
out$lowCI = lowCI
out$upCI = upCI
out$'95% CI' = paste(sprintf("%.2f", lowCI), "-", sprintf("%.2f", upCI), sep = "")
out$z = round(coefs$`z value`, dec_places)
P = sprintf("%.3f",round(coefs$`Pr(>|z|)`,3)); P[P<0.001] = "<0.001" 
out$P = P
out
##write.csv(out, "./OUTPUT_Model_SizeStructure_Logit.csv", row.names = FALSE)


###################################################
##
## IIE -- SIZE COMP DENSITY AND 
##        RECRUITMENT BAR PLOTS

###################################################
## MAY 2014-2018

pal_may <- c("coral", "coral1", "coral2", "coral3", "coral")
bar_ylab_txt = "Proportion fish age-0"

## MAY DENSITY PLOT
dens_may <- 
  match %>% filter(Month == 5) %>% 
  ggplot(aes(x = TL, fill = interaction(factor(Year), Month_Name))) +
  geom_density(stat = "density") +
  facet_grid(Month_Name ~ Year)  +
  geom_text(data=summ_match %>% filter(Month == 5), aes(x=365, y=.0107, label=n_string), 
            colour="black", inherit.aes=FALSE, parse=FALSE, size = 4) +
  coord_cartesian(ylim = c(0, 0.0125)) +
  xlab ("Lionfish total length (mm)") +
  ylab ("Density") +
  scale_fill_discrete(guide = FALSE) +
  scale_fill_manual(values=pal_may, guide = FALSE) +
  scale_y_continuous(expand = c(0,0),limits=c(0, 0.0125), breaks = c(seq(0,0.0125,0.005))) +
  theme(
    axis.title = element_text(size = 12),
    axis.text.x = element_text(angle=45, vjust=0.5),
    axis.text.y =  element_text(size = 9),
    strip.text = element_text(size = 12), 
    panel.background = element_rect(fill = "grey100"),
    panel.ontop = FALSE); dens_may

## MAY BAR PLOT
bar_may <- 
  summ_samp %>% filter(Month == 5) %>% 
  ggplot(aes(x = Year, y = Mean_P, 
             fill = interaction(factor(Year), Month_Name))) + 
  geom_bar(stat = "identity", width = 0.6, 
           color = "black") +
  geom_errorbar(aes(ymin = Mean_P - 1.96 * SE, 
                    ymax = Mean_P + 1.96 * SE), size = 0.8, width = 0.12) +
  xlab ("") +
  ylab (bar_ylab_txt ) +
  scale_fill_manual(values=pal_may, guide = FALSE) +
  scale_y_continuous(expand = c(0,0),limits=c(0, 0.41), breaks = c(seq(0,0.5,0.1))) +
  theme(
    axis.title = element_text(size = 12),
    axis.text=element_text(size=12),
    strip.text = element_text(size = 12), 
    panel.background = element_rect(fill = "grey100"),
    panel.ontop = FALSE); bar_may


###################################################
## MONTHS MAY-OCT 2014 & 2018
pal_month <- c("coral", "coral", "orange", "orange", 
               "seagreen2", "seagreen2", "turquoise", "turquoise",
               "skyblue", "skyblue", "orchid", "orchid")

## DENSITY PLOT OCT-NOV 2014 & 2018
dens_month <-   
  match %>% filter(Year == "2014" | Year == "2018") %>% 
  ggplot(aes(x = TL, fill = interaction(factor(Year), Month_Name))) +
  geom_density(stat = "density") +
  facet_grid(Month_Name ~ Year)  +
  facet_grid(Year ~ Month_Name)  +
  geom_text(data=summ_match%>% filter(Year == "2014" | Year == "2018"), 
            aes(x=320, y=.011, label=n_string), 
            colour="black", inherit.aes=FALSE, parse=FALSE, size = 4) +
  coord_cartesian(ylim = c(0, 0.0125)) +
  xlab ("Lionfish total length (mm)") +
  ylab ("Density") +
  scale_fill_manual(values = pal_month, guide=FALSE) +
  scale_y_continuous(expand = c(0,0),limits=c(0, 0.0125), breaks = c(seq(0,0.0125,0.005))) +
  theme(
    axis.title = element_text(size = 12),
    axis.text=element_text(size=12),
    axis.text.x = element_text(angle=45, vjust=0.5),
    axis.text.y =  element_text(size = 9),
    strip.text = element_text(size = 12), 
    panel.background = element_rect(fill = "grey100"),
    panel.ontop = FALSE); dens_month

## BAR PLOT OCT-NOV 2014 & 2018
bar_month <- 
  summ_samp %>% filter(Year == "2014" | Year == "2018") %>% 
  ggplot(aes(x = Month_Name, y = Mean_P, group = factor(Year),
             fill = interaction(Year, Month_Name))) + 
  geom_bar(stat = "identity", width = 0.8, position = position_dodge(),
           color = "black") +
  geom_errorbar(aes(ymin = pmax(0, Mean_P - 1.96 * SE), 
                    ymax = Mean_P + 1.96 * SE), 
                position = position_dodge(width = 0.8), width = 0.25, size = 0.8) +
  
  xlab ("") +
  ylab (bar_ylab_txt ) +
  ylim(0,20) +
  scale_y_continuous(expand = c(0,0),limits=c(0, 0.410), breaks = c(seq(0,0.5,0.1))) +
  scale_fill_manual(values = pal_month, guide=FALSE) +
  theme(
    legend.position="none",
    axis.title = element_text(size = 12),
    axis.text=element_text(size=12),
    strip.text = element_text(size = 12), 
    panel.background = element_rect(fill = "grey100"),
    panel.ontop = FALSE); bar_month

## COMBINE PROPORTION AGE-0 PLOTS FOR FIGURE
plot_all <- plot_grid(dens_may, bar_may, dens_month, bar_month, labels = "auto", ncol = 1, 
                      rel_heights =  c(4, 7, 6, 7)); plot_all

#tiff(filename = "./Size_compostion_recruitment.tiff", 
#     width = 8, height = 11.5, units = "in", res = 300)
#plot_all 
#dev.off()

######################################################################################################

###################################################
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
##
## PART III -- ROV surveys of lionfish densities
##   OKALOOSA ARTIFICIAL REEFS,
##   ESCAMBIA ARTIFICIAL REEFS,
##   NGOM NATURAL REEFS
##
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
###################################################


###################################################
##
## IIIA -- DATA MANAGMENT

rm(list=ls()) 

## Working libraries
library(dplyr)
library(ggplot2)
library(lme4)
library(cowplot)
library(MASS)
library(car)
library(stringr)


## FUNCTION TO NOTE SIGNIFICANCE

sig_stars <- function(P){
  stars = P
  stars[P>0.1] = "" 
  stars[P<=0.1] = "." 
  stars[P<=0.05] = "*" 
  stars[P<=0.01] = "**" 
  stars[P<=0.001] = "***" 
  return(stars)
}

###################################################
## DENSITY MODEL OUTPUT TABLE 
coeftab_dens <- function(mod, region, dec_places = 2){
  coefs = as.data.frame(coef(summary(mod)))
  coefs$'Odds Ratio'=exp(coefs$Estimate)
  summ = subset(summ_ngom, summ_ngom$Region == region)
  out = data.frame(Reefs = summ$Region)
  out$'Sampling date' = format(summ$Trip, format = "%Y-%m")
  out$Treatment = summ$Treatment
  out$n = summ$n
  out$'Mean density' = round(summ$mean, dec_places)
  out$'Odds ratio'= round(exp(coefs$Estimate), dec_places)
  upCI = round(exp(coefs$Estimate + 1.96 * coefs$`Std. Error`), dec_places)
  lowCI = round(exp(coefs$Estimate - 1.96 * coefs$`Std. Error`), dec_places)
  out$lowCI = lowCI
  out$upCI = upCI
  out$'95% CI' = paste(sprintf("%.2f", lowCI), "-", sprintf("%.2f", upCI), sep = "")
  out$z = round(coefs$`z value`, dec_places)
  P = sprintf("%.3f",round(coefs$`Pr(>|z|)`,3)); P[P<0.001] = "<0.001" 
  out$'Pr(>z)' = P
  out$Sig = sig_stars(P)
  #  out <- out[order(out$'Sampling date'),] ## Order by date
  return(out)
}

###################################################
## READ DATA
ngom <- read.csv("./6_ROV_Counts_2016-2018.csv")
ngom$Date = NULL
ngom$Trip = as.Date(ngom$Trip, format = "%m/%d/%Y")

summ_ngom <- ngom %>% 
  group_by(Reef_type, Region, Treatment, Trip) %>% 
  summarise(mean = mean(Dens_100),
            se = sd(Dens_100) / sqrt(n()),
            n = n()) %>%
  as.data.frame(); summ_ngom

ngom$Trip <- as.factor(ngom$Trip)


###################################################
##
## IIIB -- GLMMMs

###################################################
## GLMM OKALOOSA
region = "Okaloosa"

## VISUALIZE ERROR STRUCTURE
xx <- na.omit(subset(ngom$LF_count / ngom$Site_area * 1000, ngom$Region == region))
qqp(xx, "norm")  
qqp(xx, "lnorm")
poisson <- fitdistr(as.integer(xx), "Poisson"); qqp(xx, "pois", lambda = poisson$estimate) 
nbinom <- fitdistr(as.integer(xx), "Negative Binomial"); qqp(xx, "nbinom", size = nbinom$estimate[[1]], mu = nbinom$estimate[[2]]) ## BEST FIT DUE TO OVERDISPERSION

## MODEL
mm.oka <- glmer.nb(LF_count ~  Trip / Treatment + (1|Site) + offset(log(Site_area/100)),
                   data = subset(ngom, ngom$Region == region),
                   optCtrl=list(maxfun=2e4),
                   control=glmerControl(optimizer="bobyqa"))
summary(mm.oka)
plot(mm.oka) ## PLOT RESIDUALS
table_out_oka = coeftab_dens(mm.oka, "Okaloosa"); table_out_oka


###################################################
## GLMM ESCAMBIA
region = "Escambia"

## VISUALIZE ERROR STRUCTURE
xx <- na.omit(subset(ngom$LF_count / ngom$Site_area * 100, ngom$Region == region))
qqp(xx, "norm")  
qqp(xx, "lnorm")
poisson <- fitdistr(as.integer(xx), "Poisson"); qqp(xx, "pois", lambda = poisson$estimate) 
nbinom <- fitdistr(as.integer(xx), "Negative Binomial"); qqp(xx, "nbinom", size = nbinom$estimate[[1]], mu = nbinom$estimate[[2]]) ## BEST FIT DUE TO OVERDISPERSION

## ESCAMBIA MODEL
mm.esc <- glmer.nb(LF_count ~ Trip / Treatment  + (1|Site) + offset(log(Site_area/100)),
                   data = subset(ngom, ngom$Region == region),
                   control=glmerControl(optimizer="bobyqa"))
summary(mm.esc)
plot(mm.esc) ## PLOT RESIDUALS
table_out_esc = coeftab_dens(mm.esc, region); table_out_esc


###################################################
## GLMM NATURAL REEFS
region = "nGOM"

## VISUALIZE ERROR STRUCTUTRE
xx <- na.omit(subset(ngom$LF_count / ngom$Site_area * 1000, ngom$Region == region))
qqp(xx, "norm")  
qqp(xx, "lnorm")
poisson <- fitdistr(as.integer(xx), "Poisson"); qqp(xx, "pois", lambda = poisson$estimate) 
nbinom <- fitdistr(as.integer(xx), "Negative Binomial"); qqp(xx, "nbinom", size = nbinom$estimate[[1]], mu = nbinom$estimate[[2]]) ## BEST FIT DUE TO OVERDISPERSION


## NATURAL REEFS MODEL
mm.nat.pois <- glmer(LF_count ~ Trip + (1|Site) + offset(log(Site_area/100)),
                    family = poisson(link = log),
                    data = subset(ngom, ngom$Region == region))
summary(mm.nat.pois)
plot(mm.nat.pois) ## PLOT RESIDS
table_out_nat = coeftab_dens(mm.nat.pois, region); table_out_nat

## COMBINE AND EXPORT OUTPUT TABLES
dens_mod_out_tables <- rbind(table_out_oka, table_out_esc, table_out_nat); dens_mod_out_tables
##write.csv(dens_mod_out_tables, "./OUTPUT_ROV_density_GLMMs", row.names = FALSE)

###################################################
##
##  IIIC -- PLOT ROV DENSITIES

## LABELS FIRST LETTERS OF THE MONTH FOR X-AXIS
set.seed(2)
df = data.frame(Date=seq(as.Date(" 2016-06-01"),as.Date("2018-12-25"), by="1 day"))
df$value = cumsum(rnorm(nrow(df)))
year_labels <- rep(c('A','M','J','J','A','S','O','N','D','J','F','M'),3)

## COLORS AND WIDTHS
w = 15
pal = c("violetred4", "violetred3", "royalblue4", "royalblue3", "darkgreen")
leg.pos.x = 0.83
leg.pox.y = 0.90
ax.tit.y = 11
leg.txt  = 9.5
ax.txt.x = 9
ax.txt.y = 10

## PLOT OKALOOSA
plot_Oka <- 
  summ_ngom %>% 
  filter(Region == "Okaloosa") %>% 
  ggplot(aes(x = Trip, y = mean, 
             shape = Treatment, color = Treatment)) +
  geom_point(position=position_dodge(width=w), size = 3) + 
  geom_line(position=position_dodge(width=w), linetype = "longdash") +
  geom_errorbar(aes(ymin = pmax(0, mean - (se)),
                    ymax = mean + (se),
                    color = Treatment),
                position=position_dodge(width=w),
                width = 25, size = 0.5) +
  ylab (expression("Lionfish density ( fish per 100 " ~ m^-2 ~")" )) +
  xlab ("") +
  scale_x_date(limits = as.Date(c("2016-06-05", "2018-12-25")),  
               date_breaks = "1 month", date_minor_breaks = "1 month", 
               date_labels = year_labels) +
  scale_y_continuous(limits = c(0,45), breaks = c(seq(0,45,5)), expand = c(0, 0)) +
  scale_shape_manual(values = c(16,1)) +
  scale_color_manual(values = c(pal[3], pal[4])) +
  guides(color=guide_legend(title=""), shape=guide_legend(title="")) +
  theme(
    panel.border = element_blank(), 
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.position = c(leg.pos.x, leg.pox.y), 
    legend.title = element_blank(),
    legend.text = element_text(size = leg.txt),
    legend.background = element_rect(colour = 'black', fill = NA, linetype='solid'),
    axis.title.y = element_text(size = ax.tit.y),
    axis.text.x = element_text(size=ax.txt.x),
    axis.text.y = element_text(size=ax.txt.y)); plot_Oka

## PLOT ESCAMBIA
plot_EE <- 
  summ_ngom %>% 
  filter(Region == "Escambia") %>% 
  ggplot(aes(x = Trip, y = mean, 
             shape = Treatment, color = Treatment)) +
  geom_point(position=position_dodge(width=w), size = 3) + 
  geom_line(position=position_dodge(width=w), linetype = "longdash") +
  geom_errorbar(aes(ymin = pmax(0, mean - (se)),
                    ymax = mean + (se),
                    color = Treatment),
                position=position_dodge(width=w),
                width = 25, size = 0.5) +
  ylab (expression("Lionfish density ( fish per 100 " ~ m^-2 ~")" )) +
  xlab ("") +
  scale_x_date(limits = as.Date(c("2016-06-05", "2018-12-25")),  
               date_breaks = "1 month", date_labels = year_labels) +
  scale_y_continuous(limits = c(0,45), breaks = c(seq(0,45,5)), expand = c(0, 0)) +
  scale_shape_manual(values = c(16,1)) +
  scale_color_manual(values = c(pal[1], pal[2])) +
  guides(color=guide_legend(title=""), shape=guide_legend(title="")) +
  theme(
    panel.border = element_blank(), 
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.position = c(leg.pos.x, leg.pox.y), 
    legend.title = element_blank(),
    legend.text = element_text(size = leg.txt),
    legend.background = element_rect(colour = 'black', fill = NA, linetype='solid'),
    axis.title.y = element_text(size = ax.tit.y),
    axis.text.x = element_text(size=ax.txt.x),
    axis.text.y = element_text(size=ax.txt.y)); plot_EE

## PLOT NATURAL REEFS
plot_NR <- 
  summ_ngom %>% 
  filter(Region == "nGOM") %>% 
  ggplot(aes(x = Trip, y = mean)) +
  geom_point(size = 3, , shape = 17, color = pal[5]) + 
  geom_line(color = pal[5], linetype = "longdash") +
  geom_errorbar(aes(ymin = pmax(0, mean - (se)),
                    ymax = mean + (se)),
                width = 25, size = 0.5, color = pal[5]) +
  ylab (expression("Lionfish density ( fish per 100 " ~ m^-2 ~")" )) +
  xlab ("") +
  scale_x_date(limits = as.Date(c("2016-06-05", "2018-12-25")),  
               date_breaks = "1 month", date_minor_breaks = "1 month", 
               date_labels = year_labels) +
  scale_y_continuous(limits = c(0,0.45), breaks = c(seq(0,0.45,0.05)), expand = c(0, 0)) +
  scale_shape_manual(values = c(17)) +
  guides(color=guide_legend(title=""), shape=guide_legend(title="")) +
  theme(
    panel.border = element_blank(), 
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.position = "none", 
    axis.title.y = element_text(size = ax.tit.y),
    axis.text.x = element_text(size=ax.txt.x),
    axis.text.y = element_text(size=ax.txt.y)); plot_NR

plot_three <- plot_grid(plot_Oka, plot_EE, plot_NR, labels = "auto", nrow= 2, align = 'v'); plot_three

## SAVE PLOT
#tiff("./ROV_Densities.tif", units = "mm", res = 350,
#     height = 255, width = 255)
#plot_three
#dev.off()


######################################################################################################

###################################################
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
##
## PART IV -- LIONFISH CATCHES AND CPUE FROM
##   FWC COMMERCIAL LANDINGS,
##   LIONFISH REMOVAL TOURNAMENTS
##
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
###################################################

rm(list=ls()) 

library(dplyr)
library(ggplot2)
library(cowplot)
library(MASS)
library(car)
library(agricolae)
library(lme4)

########################################################
## COMMERCIAL SPEARFISHING LANDINGS
gulf <- read.csv("./7_Lionfish-Commercial-Spearfishing-Landings.csv")

summ_year <- 
  gulf %>% 
  group_by(year) %>% 
  summarise(landings = sum(units),
            mean_landings = mean(units),
            SE_landings = sd(units)/sqrt(n()),
            trips = n()) %>% 
  as.data.frame(); summ_year

########################################################
## TOURNAMENT CATCHES 
tourn <- read.csv("./8_Lionfish-Tournament-Catches.csv")

tourn$CPUE = tourn$Lionfish_catch / tourn$Sites
tourn$CPUE_Dive = tourn$Lionfish_catch / tourn$Dives
tourn$Year = as.factor(tourn$Year)

summ_tourn <- tourn %>% group_by(Year) %>% 
  summarise(mean_CPUE = mean (CPUE, na.rm = TRUE), 
            se_CPUE = sd(CPUE, na.rm = TRUE)/sqrt(n()), 
            lionfish_catch = sum (Lionfish_catch),
            sites = sum (Sites),
            teams = n()) %>% 
  as.data.frame(); summ_tourn

########################################################
##
## IVB -- LIONFISH CPUE MODELS 

########################################################
## COMMERCIAL SPEARFISHING CPUE

## EXAMINE ERROR STRUCTURE
ggplot(data = gulf, aes(x = units, fill = area_name)) + 
  geom_histogram(bins = 15) + 
  facet_grid(area_name ~ year) +
  theme(legend.position = "none")

dens1 = gulf$units
qqp(dens1, "norm")
qqp(dens1, "lnorm")
poisson <- fitdistr(as.integer(dens1), "Poisson"); qqp(dens1, "pois", lambda = poisson$estimate) 
nbinom <- fitdistr(as.integer(dens1), "Negative Binomial"); qqp(dens1, "nbinom", size = nbinom$estimate[[1]], mu = nbinom$estimate[[2]]) 

## LOGNORMAL GLM
lnorm.land.glm <- glm(units ~ as.factor(year), data = subset(gulf, year>=2015), 
                      family = gaussian(link = "log"))
summary(lnorm.land.glm)


## CREATE OUTPUT TABLE
mod = lnorm.land.glm
coefs = as.data.frame(coef(summary(mod)))
summ = subset(summ_year, summ_year$year >= 2015)
dec_places = 2
out = data.frame(Year = summ$year)
out$n = summ$trips
out$'Catch (kg)'= round(summ$landings)
out$'Mean CPUE' = round(summ$mean,2)
out$'Odds ratio'= round(exp(coefs$Estimate), dec_places)
upCI = round(exp(coefs$Estimate + 1.96 * coefs$`Std. Error`),2)
lowCI = round(exp(coefs$Estimate - 1.96 * coefs$`Std. Error`),2)
out$lowCI = lowCI
out$upCI = upCI
out$'95% CI' = paste(sprintf("%.2f", lowCI), "-", sprintf("%.2f", upCI), sep = "")
out$t = round(coefs$`t value`, dec_places)
P = sprintf("%.3f",round(coefs$`Pr(>|t|)`,3)); P[P<0.001] = "<0.001" 
out$P = P
out
#write.csv(out, "./OUTPUT_Model_CommLandings.csv", row.names = FALSE)


###################################################
## ANALYSIS TOURNAMENT CPUE

##QQ-PLOTS
dens1 <- tourn$CPUE
qqp(dens1, "norm")
qqp(dens1, "lnorm")
poisson <- fitdistr(as.integer(dens1), "Poisson"); qqp(dens1, "pois", lambda = poisson$estimate); poisson$estimate 
nbinom <- fitdistr(as.integer(dens1), "Negative Binomial"); qqp(dens1, "nbinom", size = nbinom$estimate[[1]], mu = nbinom$estimate[[2]])

## LOGNORMAL MIXED MODEL
mm.tourn.lnorm <- glmer(CPUE ~ Year + (1|Team), data = tourn, family = "gaussian" (link = "log"))
summary(mm.tourn.lnorm)
plot(mm.tourn.lnorm)

mod = mm.tourn.lnorm
coefs = as.data.frame(coef(summary(mod)))
summ = subset(summ_tourn)
dec_places = 2
out = data.frame(Year = summ$Year)
out$Sites = summ$sites
out$'Catch (#lionfish)'= round(summ$lionfish_catch)
out$'Mean CPUE' = round(summ$mean_CPUE,dec_places )
out$'Odds ratio'= round(exp(coefs$Estimate), dec_places)
upCI = round(exp(coefs$Estimate + 1.96 * coefs$`Std. Error`),dec_places )
lowCI = round(exp(coefs$Estimate - 1.96 * coefs$`Std. Error`),dec_places )
out$lowCI = lowCI
out$upCI = upCI
out$'95% CI' = paste(sprintf("%.2f", lowCI), "-", sprintf("%.2f", upCI), sep = "")
out$t = round(coefs$`t value`, dec_places)
P = sprintf("%.3f",round(coefs$`Pr(>|z|)`,3)); P[P<0.001] = "<0.001" 
out$P = P
out
#write.csv(out, "./OUTPUT_Model_Tournament.csv", row.names = FALSE)


########################################################
##
## PLOT COMMERICAL LANDINGS, COMMERCIAL CPUE, 
## and TOURNAMENT CPUE
ax.tit.y = 10
leg.txt  = 9
ax.txt.x = 9
ax.txt.y = 9


########################################################
## PLOT STACKED AREA TOTAL LANDINGS 
summ_gulf_byArea <- 
  gulf %>% 
  group_by(area_name, year) %>% 
  summarise(landings = sum(units),
            mean_landings = mean(units),
            SE_landings = sd(units)/sqrt(n()),
            trips = n()) %>% 
  arrange(landings) %>% 
  as.data.frame(); summ_gulf_byArea
droplevels(summ_gulf_byArea)

region_names = c("Pensacola","Destin","Panama City", "Apalachicola","Tarpon Springs","Tampa")

stack_landings <- 
  summ_gulf_byArea %>% 
  ggplot(aes(x = year, y = landings, 
             fill = factor(area_name, levels = region_names))) +
  geom_area(colour="black", size=.2, alpha=.4) +
  scale_fill_brewer(palette="Dark2", breaks=region_names, name = "Region",
                    labels = region_names) +
  xlab ("") +
  scale_y_continuous(name = "Commercial landings (kg lionfish)", expand = c(0, 0),
                     limits = c(0, 20000), breaks = c(seq(0, 20000, 5000))) +
  theme(
    panel.border = element_blank(), 
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.title = element_text(size = ax.tit.y + 1),
    legend.background = element_rect(colour = 'black', fill = NA, linetype='solid'),
    legend.position = 'right',
    axis.title.y = element_text(size = ax.tit.y),
    legend.text = element_text(size = leg.txt,
                               margin = margin(l = 5, r = 10, unit = "pt")),
    axis.text.x = element_text(size=ax.txt.x),
    axis.text.y = element_text(size=ax.txt.y)); stack_landings

########################################################
## PLOT MEAN COMMERCIAL CPUE 
pal = c("darkslategray4", "coral4", "darkorchid4")
w = 0
summ_year$region = "All"
plot_mean_landings <- 
  summ_year %>% 
  ggplot(aes(x = as.factor(year), y = mean_landings, group = region)) +
  geom_point(size = 3, color = pal[3], shape = 15) + 
  geom_line(linetype = "longdash", color = pal[3]) +
  geom_errorbar(aes(ymin = mean_landings - (1.96 * SE_landings), 
                    ymax = mean_landings + (1.96 * SE_landings)),
                position=position_dodge(width=w),
                width = 0.12, size = 0.6, color = pal[3]) +
  xlab ("") +
  scale_y_continuous(name = "Commercial CPUE (kg lionfish / trip)",  expand = c(0, 0), limits = c(0,40), breaks = c(seq(0,40,5))) +
  theme(
    panel.border = element_blank(), 
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.text = element_text(size = leg.txt),
    axis.title.y = element_text(size = ax.tit.y),
    axis.text.x = element_text(size=ax.txt.x),
    axis.text.y = element_text(size=ax.txt.y)); plot_mean_landings

########################################################
## PLOT MEAN TOURNAMENT 
colourCount = length(unique(tourn$Team))
getPalette = colorRampPalette(brewer.pal(9, "Set1"))
cols = terrain.colors(n = 29)

pointsbox_tourn_CPUE <- ggplot(tourn, aes(y = CPUE, x = Year, fill = Year)) +
  geom_violin(alpha = 0.2)+
  geom_boxplot(alpha = 0.4, width = 0.2) +
  geom_dotplot(aes(fill = Team), color = "black", 
               binpositions="all", stackgroups=TRUE,
               binwidth = 1, binaxis='y', stackdir='center', dotsize=2.2, alpha = 1) +
  geom_line(aes(color = Team, group = Team),  color = "black", 
            linetype = "longdash") +
  scale_fill_manual(values=cols) +
  scale_y_continuous(name = "Tournament CPUE (# lionfish / reef)",  
                     expand = c(0, 0), limits = c(0,70), breaks = c(seq(0,70,10))) +
  xlab ("") +
  theme(
    panel.border = element_blank(), 
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black"),
    legend.position= "none",
    legend.text = element_text(size = leg.txt),
    axis.title.y = element_text(size = ax.tit.y),
    axis.text.x = element_text(size=ax.txt.x),
    axis.text.y = element_text(size=ax.txt.y)); pointsbox_tourn_CPUE

########################################################
## COMPILE PLOTS
plots <- align_plots(plot_mean_landings, stack_landings, align = 'v', axis = 'l')
bottom_row <- plot_grid(plots[[1]], pointsbox_tourn_CPUE,
                        nrow = 1, labels = c('b','c'), align = 'v', rel_widths = c(1,0.8))
plot_catches <- plot_grid(plots[[2]], bottom_row, 
                          labels = c('a', ''), ncol = 1, rel_heights = c(1, 1.2)); plot_catches


#tiff("./Fisheries_CPUE.tiff", res = 350, height = 169, width = 169, units = "mm")
#plot_catches
#dev.off()