---
title: "RhesusOSMCode"
author: "Joelle Hass"
date: "2025-02-08"
output:
  pdf_document: default
  html_document: default
---

# Dada2 Output Prep
```{r}
library(phyloseq)
library(phyloseqCompanion)
library(dada2)

#Load dada2 objects
dadaFsUofC1= readRDS("/Users/joellehass/Desktop/OSM23Downloads/dadaFs.RDS")
dadaRsUofC1= readRDS("/Users/joellehass/Desktop/OSM23Downloads/dadaRs.RDS")
mergersUofC1= readRDS("/Users/joellehass/Desktop/OSM23Downloads/mergers.RDS")
seqtab.nochimUofC1= readRDS("/Users/joellehass/Desktop/OSM23Downloads/seqtabUofC.nochim.RDS")
taxaUofC <- readRDS("/Users/joellehass/Desktop/RFiles/rObjects/taxaUofC.RDS")

#Repeat for Run 2
dadaFsUofC2= readRDS("/Users/joellehass/Desktop/OSM23Downloads/dadaFs2.RDS")
dadaRsUofC2= readRDS("/Users/joellehass/Desktop/OSM23Downloads/dadaRs2.RDS")
mergersUofC2= readRDS("/Users/joellehass/Desktop/OSM23Downloads/mergers2.RDS")
seqtab.nochimUofC2= readRDS("/Users/joellehass/Desktop/OSM23Downloads/seqtabUofC2.nochim.RDS")
taxaUofC2 <- readRDS("/Users/joellehass/Desktop/RFiles/rObjects/taxaUofC2.RDS")

#Merge Run 1 and Run 2 dada2 output
seqtabUofCBoth= dada2::mergeSequenceTables(seqtab.nochimUofC1, seqtab.nochimUofC2, repeats= "sum")
taxaUofCBoth= rbind(taxaUofC,taxaUofC2)
```

# Build Phyloseq Object
```{r}
seqtab= as.data.frame(seqtabUofCBoth)
seqtab$LibraryID= rownames(seqtabUofCBoth)

seqtab= seqtab %>% 
  dplyr::mutate(LibraryID= str_split(LibraryID, "_")) %>%
  mutate(LibraryID= sapply(LibraryID, '[', 1)) %>%
  dplyr::filter(LibraryID != "Undetermined")

rownames(seqtab)= seqtab$LibraryID
seqtab= seqtab %>%
  dplyr::select(-LibraryID)
rownames(Metadata_UofC)= Metadata_UofC$LibraryID
seqtab= as.matrix(seqtab)

setdiff(rownames(seqtab),Metadata_UofC$LibraryID)
setdiff(Metadata_UofC$LibraryID,rownames(seqtab))

duplicates <- duplicated(rownames(taxaUofCBoth))
rownames(taxaUofCBoth)[duplicates]
taxaUofCBoth <- taxaUofCBoth[!duplicated(rownames(taxaUofCBoth)), ]
setdiff(rownames(taxaUofCBoth),colnames(seqtab))

psUnfilt <- phyloseq(otu_table(seqtab, taxa_are_rows = FALSE),
               sample_data(Metadata_UofC),
               tax_table(taxaUofCBoth))
```

# Filter
```{r}
library(decontam)

sample_data(psUnfilt)$is.neg <- sample_data(psUnfilt)$SampleOrControl == "Blank"
contamdf.prev50 <- isContaminant(psUnfilt, method="prevalence", neg="is.neg", threshold=0.5)
table(contamdf.prev50$contaminant)

library(ggplot2)
library(dplyr)

ps.pa <- transform_sample_counts(psUnfilt, function(abund) 1*(abund>0))
ps.pa.neg <- prune_samples(sample_data(ps.pa)$SampleOrControl == "Blank", ps.pa) 
ps.pa.pos <- prune_samples(sample_data(ps.pa)$SampleOrControl == "Sample", ps.pa) 

df.pa <- data.frame(pa.pos=taxa_sums(ps.pa.pos), pa.neg=taxa_sums(ps.pa.neg),
                    contaminant=contamdf.prev50$contaminant)

ggplot(data=df.pa, aes(x=pa.neg, y=pa.pos, color=contaminant)) + geom_point() +
  xlab("Prevalence (Negative Controls)") + ylab("Prevalence (True Samples)")

#Remove prevalence-based contaminants
contamdf.prev50$contamSeq <- rownames(contamdf.prev50)
toKeepdf <- contamdf.prev50 %>% filter(contaminant == "FALSE")
toKeepList <- toKeepdf$contamSeq
psNoContam <- prune_taxa(toKeepList, psUnfilt)
psNoContam 

# Filter Blanks, Quality, Phyla, Chloroplasts, & Mitochondria
samplesKeep <- prune_samples(sample_data(psNoContam)$SampleOrControl == "Sample", psNoContam)
psNoBlank <- samplesKeep
psNoBlank

# Remove Low Read Samples
psKeep <- prune_samples(rowSums(otu_table(psNoBlank)) >= 1000, psNoBlank)
psKeep

# Remove Uncharacterized Phyla
psTaxa1 <- subset_taxa(psKeep, !is.na(Phylum) & !Phylum %in% c("", "uncharacterized"))
psTaxa1

# Remove Mitochondria and Choloroplasts
psTaxa2 <- subset_taxa(psTaxa1, !is.na(Class) & !Class %in% c("Chloroplast")) 
psTaxa2 

psTaxa3 <- subset_taxa(psTaxa2, !is.na(Family) & !Family %in% c("Mitochondria")) 
psTaxa3

##Visualize Library Size##
df <- data.frame(sample_data(psTaxa3))
df$LibrarySize <- sample_sums(psTaxa3)
df <- df[order(df$LibrarySize),]
df$Index <- seq(nrow(df))
head(df)
ggplot(data=df, aes(x=Index, y=LibrarySize, color=SITE)) + geom_point()

# Filter ASV Count Outliers
df <- data.frame(sample_data(psTaxa3))
df <- df %>%
  dplyr::filter(!Observed > 1000)
hist(df$Observed)
df <- df %>%
  dplyr::filter(!Observed > 800)
hist(df$Observed)
hist(df$Shannon) 
hist(df$Simpson)
hist(df$Chao1) 

setdiff(sample_data(psTaxa3)$LibraryID, df$LibraryID)
richnessOutliers= c("Li43318","Li43426","Li43437")
psAlphaDiv= subset_samples(psTaxa3, !LibraryID %in% richnessOutliers)
psAlphaDiv
View(sample_data(psAlphaDiv))
psdfalphadiv= data.frame(sample_data(psAlphaDiv))
psdfalphadiv$readcount= sample_sums(psAlphaDiv)
sample_data(psAlphaDiv)$readcount= psdfalphadiv$readcount
View(sample_data(psAlphaDiv))

ps_clean= psAlphaDiv

prevdf <- apply(X = otu_table(ps_clean),
                MARGIN = ifelse(taxa_are_rows(ps_clean), yes = 1, no = 2),
                FUN = function(x){sum(x > 0)})
prevdf1 <- data.frame(Prevalence = prevdf,
                      TotalAbundance = taxa_sums(ps_clean),
                      tax_table(ps_clean))
View(prevdf1)

plyr::ddply(prevdf1, "Phylum", function(df1){cbind(mean(df1$Prevalence),sum(df1$Prevalence))}) 
table(tax_table(ps_clean)[, "Phylum"], exclude = NULL)

filterPhyla = c("Halanaerobiaeota","Latescibacterota","Nanoarchaeota")
ps_prev1 <- subset_taxa(ps_clean, !Phylum %in% filterPhyla)
ps_prev1 
table(tax_table(ps_prev1)[, "Phylum"], exclude = NULL)

# Visualize the Abundance of Taxa
prevdf2 <- apply(X = otu_table(ps_prev1),
                 MARGIN = ifelse(taxa_are_rows(ps_prev1), yes = 1, no = 2),
                 FUN = function(x){sum(x > 0)})
prevdf2a <- data.frame(Prevalence = prevdf2,
                       TotalAbundance = taxa_sums(ps_prev1),
                       tax_table(ps_prev1))
prevdf2a = subset(prevdf2a, Phylum %in% get_taxa_unique(ps_prev1, "Phylum"))

ggplot(prevdf2a, aes(TotalAbundance, Prevalence / nsamples(ps_prev1),color=Phylum)) +
  geom_hline(yintercept = 0.02, alpha = 0.5, linetype = 2) +  geom_point(size = 2, alpha = 0.7) +
  scale_x_log10() +  xlab("Total Abundance") + ylab("Prevalence [Frac. Samples]") +
  facet_wrap(~Phylum) + theme(legend.position="none")

prevalenceThreshold <- 0.02 * nsamples(ps_prev1)

keepTaxa <- rownames(prevdf2a)[(prevdf2a$Prevalence >= prevalenceThreshold)]
ps_prev2 <- prune_taxa(keepTaxa, ps_prev1)
table(tax_table(ps_prev2)[, "Phylum"], exclude = NULL)
```

# Calculating Alpha Diversity
```{r}
adivFilt <- estimate_richness(ps_prev2,measures=c("Observed","Shannon","Chao1","Simpson"))

sample_data(ps_prev2)$ShannonFilt= adivFilt$Shannon
hist(sample_data(ps_prev2)$ShannonFilt)

sample_data(ps_prev2)$ObservedFilt= adivFilt$Observed 
hist(sample_data(ps_prev2)$ObservedFilt)

sample_data(ps_prev2)$Chao1Filt= adivFilt$Chao1
hist(sample_data(ps_prev2)$Chao1Filt)

sample_data(ps_prev2)$SimpsonFilt= adivFilt$Simpson
hist(sample_data(ps_prev2)$SimpsonFilt)
```

# Read Count Normalization
```{r}
sample_sums(ps_prev2) 
sort(sample_sums(ps_prev2)) 
print(rowSums(otu_table(ps_prev2)))

ps.readCount= prune_samples(rowSums(otu_table(ps_prev2)) >= 1000, ps_prev2)
sample_sums(ps.readCount) 
sort(sample_sums(ps.readCount)) 

sample_data(ps.readCount)$ReadCounts= sample_sums(ps.readCount) 

psdf1= data.frame(sample_data(ps.readCount))

# Visualize Read Count and Richness/Diversity Relationships
readCountRichness <- ggplot(data = psdf1, aes(x = ReadCounts, y = Observed)) +
  geom_point() +
  geom_smooth(method = "lm"); readCountRichness

readCountShannon <- ggplot(data = psdf1, aes(x = ReadCounts, y = Shannon)) +
  geom_point() +
  geom_smooth(method = "lm"); readCountShannon

readCountSimpson <- ggplot(data = psdf1, aes(x = ReadCounts, y = Simpson)) +
  geom_point() +
  geom_smooth(method = "lm"); readCountSimpson

readCountShannonFilt <- ggplot(data = psdf1, aes(x = ReadCounts, y = ShannonFilt)) +
  geom_point() +
  geom_smooth(method = "lm"); readCountShannonFilt

m1 <- lm(Observed ~ ReadCounts, data = psdf1)
resid(m1)
plot(density(resid(m1))) 
qqnorm(resid(m1))
qqline(resid(m1))
psdf1$residObserved <- resid(m1)

m2 <- lm(Chao1 ~ ReadCounts, data = psdf1)
resid(m2)
plot(density(resid(m2))) 
qqnorm(resid(m2))
qqline(resid(m2))
psdf1$residChao1 <- resid(m2)

#Shannon--Unfiltered
m3 <- lm(Shannon ~ ReadCounts, data = psdf1)
resid(m3)
plot(density(resid(m3)))
qqnorm(resid(m3))
qqline(resid(m3))
psdf1$residShannon <- resid(m3)

#Simpson--Unfiltered
m4 <- lm(Simpson ~ ReadCounts, data = psdf1)
resid(m4)
plot(density(resid(m4)))
qqnorm(resid(m4))
qqline(resid(m4))
psdf1$residSimpson <- resid(m4)

#Observed-- Filtered
m1b <- lm(ObservedFilt ~ ReadCounts, data = psdf1) 
resid(m1b)
plot(density(resid(m1b))) 
qqnorm(resid(m1b)) 
qqline(resid(m1b))
psdf1$residObsFilt <- resid(m1b)

#Chao1-- Filtered
m2b <- lm(Chao1Filt ~ ReadCounts, data = psdf1)
resid(m2b)
plot(density(resid(m2b)))
qqnorm(resid(m2b))
qqline(resid(m2b))
psdf1$residChao1Filt <- resid(m2b)

#Shannon-- Filtered
m3b <- lm(ShannonFilt ~ ReadCounts, data = psdf1)
resid(m3b)
plot(density(resid(m3b)))
qqnorm(resid(m3b))
qqline(resid(m3b))
psdf1$residShanFilt <- resid(m3b)

#Simpson-- Filtered
m4b <- lm(SimpsonFilt ~ ReadCounts, data = psdf1)
resid(m4b)
plot(density(resid(m4b)))
qqnorm(resid(m4b))
qqline(resid(m4b))
psdf1$residSimpFilt <- resid(m4b)

psdf1= data.frame(sample_data(ps.readCount))
```

# PS Object MetaData
```{r}
ps.readCount.df= data.frame(sample_data(ps.readCount))
age_quartiles <- quantile(ps.readCount.df$AGE, probs = c(0, 0.25, 0.5, 0.75, 1))

sample_data(ps.readCount)$Run= ifelse(psdf1$SampleID < 45741, "Run1","Run2")
sample_data(ps.readCount)$residObserved= psdf1$residObserved
sample_data(ps.readCount)$residChao1= psdf1$residChao1
sample_data(ps.readCount)$residShannon= psdf1$residShannon
sample_data(ps.readCount)$residSimpson= psdf1$residSimpson
sample_data(ps.readCount)$residObsFilt= psdf1$residObsFilt
sample_data(ps.readCount)$residChao1Filt= psdf1$residChao1Filt
sample_data(ps.readCount)$residShanFilt= psdf1$residShanFilt
sample_data(ps.readCount)$residSimpFilt= psdf1$residSimpFilt
sample_data(ps.readCount)$OldvsYoung= ifelse(ps.readCount.df$AGE < 17, "Young","Old")


saveRDS(ps.readCount, "/Users/joellehass/Desktop/RFiles/rObjects/psMiSeqFiltMeta.RDS")
ps.readCount= readRDS("/Users/joellehass/Desktop/RFiles/rObjects/psMiSeqFiltMeta.RDS")
```

# Identify Top Taxa
```{r}
library(fantaxtic)

#Overall dataset:
table(tax_table(ps.readCount)[, "Phylum"], exclude = NULL)
table(tax_table(ps.readCount)[, "Genus"], exclude = NULL)
top_taxa(ps.readCount, n_taxa = 7, tax_level = "Phylum")
top_taxa(ps.readCount, n_taxa = 4, tax_level = "Phylum")
top_taxa(ps.readCount, n_taxa = 10, tax_level = "Genus")

#Sabana Seca Subset:
ps.SS= subset_samples(ps.readCount, SITE == "SSFS")
top_taxa(ps.SS, n_taxa = 4, tax_level = "Phylum")
top_taxa(ps.SS, n_taxa = 10, tax_level = "Genus")


#Cayo Subset:
ps.Cayo= subset_samples(ps.readCount, SITE == "Cayo")
top_taxa(ps.Cayo, n_taxa = 4, tax_level = "Phylum")
top_taxa(ps.Cayo, n_taxa = 10, tax_level = "Genus")
```

# Visualize Relative Abundance
```{r}
library(microbiome)
library(patchwork)

get_taxa_unique(ps.readCount, "Phylum")
ps.Phyla <- ps.readCount %>% aggregate_taxa(level = "Phylum") %>%
  microbiome::transform(transform = "compositional")

#Phyla All
plotAllTaxa= ps.Phyla %>%  plot_composition(average_by = "SampleOrControl")+ 
  scale_y_continuous(labels = percent) +
  scale_x_discrete(labels = c("Sample" = "All Individuals")) +
  labs(x = "", 
       y = "Relative Abundance of Phyla", 
       #title= "Top OSM Phyla in Rhesus Macaques",
       fill= "Phylum") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5))

#Phyla by SITE:
plotSiteTaxa= ps.Phyla %>%  plot_composition(average_by = "SITE")+ 
  scale_y_continuous(labels = percent) +
  scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  labs(x = "", 
       y = "Relative Abundance of Phyla", 
       fill= "Phylum") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5)); plotSiteTaxa

#Phyla by OldvsYoung:
plotAgeTaxa= ps.Phyla %>%  plot_composition(average_by = "OldvsYoung")+ 
  scale_y_continuous(labels = percent) +
  labs(x = "", 
       y = "Relative Abundance of Phyla", 
       fill= "Phylum") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),
        legend.position = "none")

#Phyla by SEX:
plotSexTaxa= ps.Phyla %>%  plot_composition(average_by = "SEX")+ 
  scale_y_continuous(labels = percent) +
  scale_x_discrete(labels = c("F" = "Female", "M" = "Male")) +
  labs(x = "", 
       y = "Relative Abundance of Phyla",
       fill= "Phylum") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5),
        legend.position = "none")

combined_plot <- plotAgeTaxa + plotSexTaxa +  plotSiteTaxa 
  plot_layout(ncol = 3); combined_plot 

#Genera by SITE:
ps.Genera <- ps.readCount %>% aggregate_taxa(level = "Genus") %>%
  microbiome::transform(transform = "compositional") 

plotSiteTaxa2= ps.Genera %>%  plot_composition(average_by = "SITE")+ 
  scale_y_continuous(labels = percent) +
  scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  labs(x = "", 
       y = "Relative Abundance of Genera", 
       title= "Genera",
       fill= "Genus") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5)); plotSiteTaxa2
  
combined_Plot_SITE= plotSiteTaxa + plotSiteTaxa2 
plot_layout(ncol = 3); combined_Plot_SITE
```

# Testing Alpha Diversity
```{r}
library(ggpubr)
library(ggplot2)

#Shannon Index
#SS vs Cayo:
wilcox.test(ps.readCount.df$residShanFilt[ps.readCount.df$SITE=="Cayo"],ps.readCount.df$residShanFilt[ps.readCount.df$SITE=="SSFS"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Male vs Female:
wilcox.test(ps.readCount.df$residShanFilt[ps.readCount.df$SEX=="M"],ps.readCount.df$residShanFilt[ps.readCount.df$SEX=="F"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Young vs Old:
wilcox.test(ps.readCount.df$residShanFilt[ps.readCount.df$OldvsYoung=="Young"],ps.readCount.df$residShanFilt[ps.readCount.df$OldvsYoung=="Old"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#CJ vs EL
wilcox.test(ps.readCount.df$residShanFilt[ps.readCount.df$ConjunOrEyelid=="Conjunctiva"],ps.readCount.df$residShanFilt[ps.readCount.df$ConjunOrEyelid=="Eyelid"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Right vs Left
wilcox.test(ps.readCount.df$residShanFilt[ps.readCount.df$RightOrLeft=="Right"],ps.readCount.df$residShanFilt[ps.readCount.df$RightOrLeft=="Left"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Run 1 vs Run 2
wilcox.test(ps.readCount.df$residShanFilt[ps.readCount.df$Run=="Run1"],ps.readCount.df$residShanFilt[ps.readCount.df$Run=="Run2"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)

# Chao1
#SS vs Cayo:
wilcox.test(ps.readCount.df$residChao1Filt[ps.readCount.df$SITE=="Cayo"],ps.readCount.df$residChao1Filt[ps.readCount.df$SITE=="SSFS"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Male vs Female:
wilcox.test(ps.readCount.df$residChao1Filt[ps.readCount.df$SEX=="M"],ps.readCount.df$residChao1Filt[ps.readCount.df$SEX=="F"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Young vs Old:
wilcox.test(ps.readCount.df$residChao1Filt[ps.readCount.df$OldvsYoung=="Young"],ps.readCount.df$residChao1Filt[ps.readCount.df$OldvsYoung=="Old"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#CJ vs EL
wilcox.test(ps.readCount.df$residChao1Filt[ps.readCount.df$ConjunOrEyelid=="Conjunctiva"],ps.readCount.df$residChao1Filt[ps.readCount.df$ConjunOrEyelid=="Eyelid"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Right vs Left
wilcox.test(ps.readCount.df$residChao1Filt[ps.readCount.df$RightOrLeft=="Right"],ps.readCount.df$residChao1Filt[ps.readCount.df$RightOrLeft=="Left"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Run 1 vs Run 2
wilcox.test(ps.readCount.df$residChao1Filt[ps.readCount.df$Run=="Run1"],ps.readCount.df$residChao1Filt[ps.readCount.df$Run=="Run2"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)

# Simpson Diversity Index
#SS vs Cayo:
wilcox.test(ps.readCount.df$residSimpFilt[ps.readCount.df$SITE=="Cayo"],ps.readCount.df$residSimpFilt[ps.readCount.df$SITE=="SSFS"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Male vs Female:
wilcox.test(ps.readCount.df$residSimpFilt[ps.readCount.df$SEX=="M"],ps.readCount.df$residSimpFilt[ps.readCount.df$SEX=="F"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Young vs Old:
wilcox.test(ps.readCount.df$residSimpFilt[ps.readCount.df$OldvsYoung=="Young"],ps.readCount.df$residSimpFilt[ps.readCount.df$OldvsYoung=="Old"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#CJ vs EL:
wilcox.test(ps.readCount.df$residSimpFilt[ps.readCount.df$ConjunOrEyelid=="Conjunctiva"],ps.readCount.df$residSimpFilt[ps.readCount.df$ConjunOrEyelid=="Eyelid"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Right vs Left:
wilcox.test(ps.readCount.df$residSimpFilt[ps.readCount.df$RightOrLeft=="Right"],ps.readCount.df$residSimpFilt[ps.readCount.df$RightOrLeft=="Left"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)
#Run 1 vs Run 2
wilcox.test(ps.readCount.df$residSimpFilt[ps.readCount.df$Run=="Run1"],ps.readCount.df$residSimpFilt[ps.readCount.df$Run=="Run2"], 
            paired=FALSE, mu=0, exact=F, conf.int = T, conf.level = 0.95)

#Visualizations
residShanSITE <-ggplot(ps.readCount.df, aes(SITE, residShanFilt, fill= SITE)) +
  geom_boxplot() +
  #geom_jitter() +
  scale_fill_manual(values = c("lightblue", "orange")) +
  xlab("Living Condition") + 
  ylab("Shannon Index Alpha Diversity (Residual)") + 
  ggtitle("Rhesus Macaque OSM Shannon Diversity by Living Condition")+
  theme_minimal() +
  theme(legend.position = "none"); residShanSITE

residShanSITE2= ggviolin(ps.readCount.df, x = "SITE", y = "residShanFilt",
         add = "boxplot", fill = "SITE", palette = c("lightblue", "orange")) +
  #ggtitle("Shannon Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Shannon Index") +
  scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residShanSITE2

residChao1SITE= ggviolin(ps.readCount.df, x = "SITE", y = "residChao1Filt",
                           add = "boxplot", fill = "SITE", palette = c("lightblue", "orange")) +
  #ggtitle("Chao1 Richness Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Chao1 Richness") +
  scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residChao1SITE

residShanSEX <-ggplot(ps.readCount.df, aes(SEX, residShanFilt, fill= SEX)) +
  geom_boxplot() +
  #geom_jitter() +
  scale_fill_manual(values = c("blue", "lightgreen")) +
  xlab("Sex") + ylab("Shannon Index Alpha Diversity (Residual)") + ggtitle("Rhesus Macaque OSM Shannon Diversity by Sex")+
  theme_minimal() +
  theme(legend.position = "none"); residShanSEX

residShanSEX2= ggviolin(ps.readCount.df, x = "SEX", y = "residShanFilt",
                         add = "boxplot", fill = "SEX", palette = c("blue", "lightgreen")) +
  #ggtitle("Shannon Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Shannon Index") +
  scale_x_discrete(labels = c("F" = "Female", "M" = "Male")) +
  theme_minimal() +
  theme(legend.position = "none"); residShanSEX2

residSimpSEX= ggviolin(ps.readCount.df, x = "SEX", y = "residSimpFilt",
                        add = "boxplot", fill = "SEX", palette = c("blue", "lightgreen")) +
  #ggtitle("Simpson Index Alpha Diversity by Sex") + 
  xlab("") + 
  ylab("Simpson Index") +
  scale_x_discrete(labels = c("F" = "Female", "M" = "Male")) +
  theme_minimal() +
  theme(legend.position = "none"); residSimpSEX

residChao1SEX= ggviolin(ps.readCount.df, x = "SEX", y = "residChao1Filt",
                       add = "boxplot", fill = "SEX", palette = c("blue", "lightgreen")) +
  #ggtitle("Chao1 Richness Alpha Diversity by Sex") + 
  xlab("") + 
  ylab("Chao1 Richness") +
  scale_x_discrete(labels = c("F" = "Female", "M" = "Male")) +
  theme_minimal() +
  theme(legend.position = "none"); residChao1SEX

residShanAGE <-ggplot(ps.readCount.df, aes(OldvsYoung, residShanFilt, fill= OldvsYoung)) +
  geom_boxplot() +
  #geom_jitter() +
  scale_fill_manual(values = c("pink", "purple")) +
  xlab("Age Group") + ylab("Shannon Index Alpha Diversity (Residual)") + ggtitle("Rhesus Macaque OSM Shannon Diversity by Age Group")+
  theme_minimal() +
  theme(legend.position = "none"); residShanAGE

residShanAGE2= ggviolin(ps.readCount.df, x = "OldvsYoung", y = "residShanFilt",
                        add = "boxplot", fill = "OldvsYoung", palette = c("pink", "purple")) +
  #ggtitle("Shannon Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Shannon Index") +
  #scale_x_discrete(labels = c("F" = "Female", "M" = "Male")) +
  theme_minimal() +
  theme(legend.position = "none"); residShanAGE2

residSimpAGE= ggviolin(ps.readCount.df, x = "OldvsYoung", y = "residSimpFilt",
                        add = "boxplot", fill = "OldvsYoung", palette = c("pink", "purple")) +
  #ggtitle("Shannon Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Simpson Index") +
  #scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residSimpAGE

residChao1AGE= ggviolin(ps.readCount.df, x = "OldvsYoung", y = "residChao1Filt",
                           add = "boxplot", fill = "OldvsYoung", palette = c("pink", "purple")) +
  #ggtitle("Shannon Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Chao1 Richness") +
  #scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residChao1AGE

residChao1AGE <-ggplot(ps.readCount.df, aes(OldvsYoung, residChao1Filt, fill= OldvsYoung)) +
  geom_boxplot() +
  #geom_jitter() +
  scale_fill_manual(values = c("pink", "purple")) +
  xlab("Age Group") + ylab("Chao1 Alpha Diversity (Residual)") + ggtitle("Rhesus Macaque OSM Chao1 Diversity by Age Group")+
  theme_minimal() +
  theme(legend.position = "none"); residChao1AGE

residChao1CJEL <-ggplot(ps.readCount.df, aes(ConjunOrEyelid, residChao1Filt, fill= ConjunOrEyelid)) +
  geom_boxplot() +
  #geom_jitter() +
  scale_fill_manual(values = c("orange", "yellow")) +
  xlab("Sample Site") + ylab("Chao1 Alpha Diversity (Residual)") + ggtitle("Rhesus Macaque OSM Chao1 Diversity by Sample Site")+
  theme_minimal() +
  theme(legend.position = "none"); residChao1CJEL

residSimpSITE <-ggplot(ps.readCount.df, aes(SITE, residSimpFilt, fill= SITE)) +
  geom_boxplot() +
  #geom_jitter() +
  scale_fill_manual(values = c("lightblue", "orange")) +
  xlab("Living Condition") + ylab("Simpson Diversity Index (Residual)") + ggtitle("Rhesus Macaque OSM Simpson Diversity by Living Condition")+
  theme_minimal() +
  theme(legend.position = "none"); residSimpSITE

residSimpSITE2= ggviolin(ps.readCount.df, x = "SITE", y = "residSimpFilt",
                         add = "boxplot", fill = "SITE", palette = c("lightblue", "orange")) +
  #ggtitle("Simpson Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Simpson Index") +
  scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residSimpSITE2

residChao1CJvsEL= ggviolin(ps.readCount.df, x = "ConjunOrEyelid", y = "residChao1Filt",
                         add = "boxplot", fill = "ConjunOrEyelid", palette = c("darkgreen", "red")) +
  #ggtitle("Shannon Index Alpha Diversity by Living Condition") + 
  xlab("") + 
  ylab("Chao1 Richness") +
  #scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residChao1CJvsEL

residShanCJvsEL= ggviolin(ps.readCount.df, x = "ConjunOrEyelid", y = "residShanFilt",
                           add = "boxplot", fill = "ConjunOrEyelid", palette = c("darkgreen", "red")) +
  #ggtitle("Shannon Index Alpha Diversity by Sampled Site") + 
  xlab("") + 
  ylab("Shannon Index") +
  #scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residShanCJvsEL

residSimpCJvsEL= ggviolin(ps.readCount.df, x = "ConjunOrEyelid", y = "residSimpFilt",
                          add = "boxplot", fill = "ConjunOrEyelid", palette = c("darkgreen", "red")) +
  #ggtitle("Simpson Index Alpha Diversity by Sampled Site") + 
  xlab("") + 
  ylab("Simpson Index") +
  #scale_x_discrete(labels = c("Cayo" = "Free-ranging", "SSFS" = "Captive")) +
  theme_minimal() +
  theme(legend.position = "none"); residSimpCJvsEL

#Combined Figure for Alpha Diversity:
combined.alpha.plot= residChao1CJvsEL +
  residShanAGE2 + 
  residSimpSITE2; 
combined.alpha.plot

#Combined alpha div figure SITE
combined.alpha.SITE= residShanSITE2 + residSimpSITE2 + residChao1SITE+
  plot_annotation(tag_levels = "A"); combined.alpha.SITE

#Combined alpha div figure AGE
combined.alpha.AGE= residShanAGE2 + residSimpAGE + residChao1AGE; combined.alpha.AGE

#Combined alpha div figure SEX
combined.alpha.SEX= residShanSEX2 + residSimpSEX + residChao1SEX; combined.alpha.SEX

#Combined alpha div figure Sampled Site
combined.alpha.CJvsEL= residShanCJvsEL + residSimpCJvsEL + residChao1CJvsEL; combined.alpha.CJvsEL
```

# Linear Modelling
```{r}
library(lme4)
library(lmerTest)
library(sjPlot)

ShanModel1= lmer(residShanFilt~
                  SITE+
                  OldvsYoung+
                  SEX+
                  (1|ID),
                data= ps.readCount.df)
summary(ShanModel1)
tab_model(ShanModel1)
plot_model(ShanModel1, 
           dot.size = 0.75, 
           line.size= 0.35,
  ylim(-0.3,0.3) +
  theme_light()

ShanModel2= lmer(residShanShift~
                   SITE+
                   OldvsYoung+
                   SEX+
                   Run+
                   ConjunOrEyelid+
                   RightOrLeft+
                   (1|ID),
                 data= ps.readCount.df)
summary(ShanModel2)

Chao1Model1= lmer(residChao1Filt~
                    SITE+
                    OldvsYoung+
                    SEX+
                    Run+
                    ConjunOrEyelid+
                    RightOrLeft+
                    (1|ID),
                  data= ps.readCount.df)
summary(Chao1Model1)
tab_model(Chao1Model1)
plot_model(Chao1Model1, 
           dot.size = 0.75, 
           line.size= 0.35,
  theme_light()

SimpModel1= lmer(residSimpFilt~
                   SITE+
                   OldvsYoung+
                   SEX+
                   Run+
                   ConjunOrEyelid+
                   RightOrLeft+
                   (1|ID),
                 data= ps.readCount.df)
summary(SimpModel1)
```

# Visualize Beta Diversity
```{r}
library(microbiome)
library(vegan)

# Bray-Curtis Disimilarity
bray <- ordinate(physeq = ps.readCount,
                 method = "PCoA", 
                 distance = "bray")
brayNMDS= ordinate(physeq = ps.readCount,
                   method = "NMDS", 
                   distance = "bray")

#Cayo vs SSFS: PCoA
custom_colors <- c("Cayo" = "lightblue", "SSFS" = "orange")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = bray)+                                                
  geom_point(aes(color = SITE), size = 2) +
  stat_ellipse(aes(color = SITE), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Living Condition (PCoA)")+
  theme_minimal()

#Cayo vs SSFS: NMDS
custom_colors <- c("Cayo" = "lightblue", "SSFS" = "orange")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = brayNMDS)+                                                
  geom_point(aes(color = SITE), size = 2) +
  stat_ellipse(aes(color = SITE), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Living Condition (NMDS)") +
  theme_minimal()

#Male vs Female: PCoA
custom_colors <- c("M" = "red", "F" = "green")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = bray)+                                                
  geom_point(aes(color = SEX), size = 2) +
  stat_ellipse(aes(color = SEX), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Sex (PCoA)")+
  theme_minimal()

#Male vs Female: NMDS
custom_colors <- c("M" = "red", "F" = "green")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = brayNMDS)+                                                
  geom_point(aes(color = SEX), size = 2) +
  stat_ellipse(aes(color = SEX), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Sex (NMDS)") +
  theme_minimal()

#Young vs Old: PCoA
custom_colors <- c("Young" = "pink", "Old" = "purple")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = bray)+                                                
  geom_point(aes(color = OldvsYoung), size = 2) +
  stat_ellipse(aes(color = OldvsYoung), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Age (PCoA)")+
  theme_minimal()

#Young vs Old: NMDS
custom_colors <- c("Young" = "pink", "Old" = "purple")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = brayNMDS)+                                                
  geom_point(aes(color = OldvsYoung), size = 2) +
  stat_ellipse(aes(color = OldvsYoung), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Age (NMDS)") +
  theme_minimal()

#CJ vs EL: PCoA
custom_colors <- c("Conjunctiva" = "orange", "Eyelid" = "yellow")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = bray)+                                                
  geom_point(aes(color = ConjunOrEyelid), size = 2) +
  stat_ellipse(aes(color = ConjunOrEyelid), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Sample Site (PCoA)")+
  theme_minimal()

#CJ vs EL: NMDS
custom_colors <- c("Conjunctiva" = "orange", "Eyelid" = "yellow")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = brayNMDS)+                                                
  geom_point(aes(color = ConjunOrEyelid), size = 2) +
  stat_ellipse(aes(color = ConjunOrEyelid), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Sample Site (NMDS)") +
  theme_minimal()

#Right vs Left: PCoA
custom_colors <- c("Right" = "lightgreen", "Left" = "darkblue")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = bray)+                                                
  geom_point(aes(color = RightOrLeft), size = 2) +
  stat_ellipse(aes(color = RightOrLeft), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Eye Laterality (PCoA)")+
  theme_minimal()

#Right vs Left: NMDS
custom_colors <- c("Right" = "lightgreen", "Left" = "darkblue")
plot_ordination(physeq = ps.readCount,                                                        
                ordination = brayNMDS)+                                                
  geom_point(aes(color = RightOrLeft), size = 2) +
  stat_ellipse(aes(color = RightOrLeft), type = "norm", linetype = "dashed") +
  scale_color_manual(values = custom_colors) +
  ggtitle("Bray Curtis Beta Diversity by Eye Laterality (NMDS)") +
  theme_minimal()

# Aitchison
ps_clr <- microbiome::transform(ps.readCount, "clr")
ord_clr <- phyloseq::ordinate(physeq= ps_clr, 
                              method= "RDA")
phyloseq::plot_scree(ord_clr) + 
  geom_bar(stat="identity", fill = "blue") +
  labs(x = "\nAxis", y = "Proportion of Variance\n")
clr1 <- ord_clr$CA$eig[1] / sum(ord_clr$CA$eig)
clr2 <- ord_clr$CA$eig[2] / sum(ord_clr$CA$eig)

#Cayo vs SSFS: PCA
custom_colors <- c("Cayo" = "lightblue", "SSFS" = "orange")
phyloseq::plot_ordination(physeq= ps.readCount, 
                          ordination= ord_clr, 
                          type="samples", 
                          color="SITE") + 
  scale_color_manual(values = custom_colors) +
  ggtitle("Aitchison Beta Diversity by Living Condition (PCA)") +
  geom_point(size = 2) +
  coord_fixed(clr2 / clr1) +
  stat_ellipse(aes(group = SITE), linetype = 2) + 
  theme_minimal() +
  labs(color = "SITE")

#Male vs Female:
custom_colors <- c("M" = "red", "F" = "green")
phyloseq::plot_ordination(physeq= ps.readCount, 
                          ordination= ord_clr, 
                          type="samples", 
                          color="SEX") + 
  scale_color_manual(values = custom_colors) +
  ggtitle("Aitchison Beta Diversity by Sex (PCA)") +
  geom_point(size = 2) +
  coord_fixed(clr2 / clr1) +
  stat_ellipse(aes(group = SEX), linetype = 2) + 
  theme_minimal() +
  labs(color = "SEX")

#Young vs Old:
custom_colors <- c("Young" = "pink", "Old" = "purple")
phyloseq::plot_ordination(physeq= ps.readCount, 
                          ordination= ord_clr, 
                          type="samples", 
                          color="OldvsYoung") + 
  scale_color_manual(values = custom_colors) +
  ggtitle("Aitchison Beta Diversity by Sex (PCA)") +
  geom_point(size = 2) +
  coord_fixed(clr2 / clr1) +
  stat_ellipse(aes(group = OldvsYoung), linetype = 2) + 
  theme_minimal() +
  labs(color = "OldvsYoung")

#CJ vs EL:
custom_colors <- c("Conjunctiva" = "orange", "Eyelid" = "yellow")
phyloseq::plot_ordination(physeq= ps.readCount, 
                          ordination= ord_clr, 
                          type="samples", 
                          color="ConjunOrEyelid") + 
  scale_color_manual(values = custom_colors) +
  ggtitle("Aitchison Beta Diversity by Sample Site (PCA)") +
  geom_point(size = 2) +
  coord_fixed(clr2 / clr1) +
  stat_ellipse(aes(group = ConjunOrEyelid), linetype = 2) + 
  theme_minimal() +
  labs(color = "ConjunOrEyelid")

#Right vs Left:
custom_colors <- c("Right" = "lightgreen", "Left" = "darkblue")
phyloseq::plot_ordination(physeq= ps.readCount, 
                          ordination= ord_clr, 
                          type="samples", 
                          color="RightOrLeft") + 
  scale_color_manual(values = custom_colors) +
  ggtitle("Aitchison Beta Diversity by Eye Laterality (PCA)") +
  geom_point(size = 2) +
  coord_fixed(clr2 / clr1) +
  stat_ellipse(aes(group = RightOrLeft), linetype = 2) + 
  theme_minimal() +
  labs(color = "RightOrLeft")

#Run 1 vs Run 2
custom_colors <- c("Run1" = "pink", "Run2" = "green")
phyloseq::plot_ordination(physeq= ps.readCount, 
                          ordination= ord_clr, 
                          type="samples", 
                          color="Run") + 
  scale_color_manual(values = custom_colors) +
  ggtitle("Aitchison Beta Diversity by Run (PCA)") +
  geom_point(size = 2) +
  coord_fixed(clr2 / clr1) +
  stat_ellipse(aes(group = Run), linetype = 2) + 
  theme_minimal() +
  labs(color = "Run")
```

# PERMANOVA Models
```{r}
# PERMANOVA Aitchison
clr_dist_matrix <- phyloseq::distance(ps_clr, method = "euclidean")
vegan::adonis2(clr_dist_matrix ~  SITE +
                 SEX +
                 OldvsYoung +
                 RightOrLeft +
                 ConjunOrEyelid +
                 Run +
                 ID, data = ps.readCount.df)

# PERMANOVA Bray Curtis
ps_rel = transform_sample_counts(ps.readCount, function(x) x / sum(x) * 100) 
bray.dist.rel <- phyloseq::distance(ps_rel, method = "bray")
vegan::adonis2(bray.dist.rel ~  SITE +
                 SEX +
                 OldvsYoung +
                 RightOrLeft +
                 ConjunOrEyelid +
                 Run +
                 ID, data = ps.readCount.df)

```

# Differential Adbundance
```{r}
# DESeq2
library(DESeq2)

psPseudo= ps.readCount
psData= phyloseq::otu_table(psPseudo)
psData <- psData + 1
phyloseq::otu_table(psPseudo) <- psData

sample_data(psPseudo)$SITE <- as.factor(sample_data(psPseudo)$SITE)
levels(sample_data(psPseudo)$SITE)

sample_data(psPseudo)$OldvsYoung <- as.factor(sample_data(psPseudo)$OldvsYoung)
levels(sample_data(psPseudo)$OldvsYoung)

sample_data(psPseudo)$OldvsYoung <- relevel(sample_data(psPseudo)$OldvsYoung, ref = "Old")
levels(sample_data(psPseudo)$OldvsYoung)

sample_data(psPseudo)$SEX <- as.factor(sample_data(psPseudo)$SEX)
levels(sample_data(psPseudo)$SEX)

sample_data(psPseudo)$ConjunOrEyelid <- as.factor(sample_data(psPseudo)$ConjunOrEyelid)
levels(sample_data(psPseudo)$ConjunOrEyelid)

#DESeq2: SITE
Deseq2data = phyloseq_to_deseq2(psPseudo, ~ OldvsYoung + SEX + ConjunOrEyelid + SITE)
Deseq2data = DESeq(Deseq2data, 
                      test="Wald", 
                      fitType="parametric")
resultDESeq2 <- results(Deseq2data)
df.resultDESeq2 <- as.data.frame(resultDESeq2)
df.resultDESeq2$taxon <- rownames(df.resultDESeq2)
df.resultDESeq2 <- df.resultDESeq2 %>% arrange(log2FoldChange, padj)

ASVlabels <- paste0("ASV", seq_len(ntaxa(psPseudo))) 
tax_table(psPseudo) <- cbind(tax_table(psPseudo), ASV = ASVlabels)

taxa_info <- as.data.frame(tax_table(psPseudo))
rownames(taxa_info) <- rownames(tax_table(psPseudo))
if(!all(rownames(df.resultDESeq2) %in% rownames(taxa_info))) {
  stop("Mismatch in OTU IDs between DESeq2 results and taxonomy table.")
}
df.resultDESeq2.taxa <- merge(df.resultDESeq2, taxa_info, by="row.names")
View(df.resultDESeq2.taxa)

sig.taxa_Deseq= df.resultDESeq2.taxa %>% 
  filter(log2FoldChange >= 2.5 | log2FoldChange <= -2.5) %>%
  filter(padj < 0.05) %>%
  filter(!is.na(Genus)) %>%
  arrange(Genus)
sig.taxa_Deseq$taxon <- as.factor(sig.taxa_Deseq$taxon)

DESeqPlotSITE= ggplot(sig.taxa_Deseq, aes(y = reorder(ASV, log2FoldChange), x = log2FoldChange, fill = Genus)) +
  geom_col() +
  labs(
    x = "Log2 Fold Change",
    y = "Differentially Abundant ASVs",
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); DESeqPlotSITE

#DESeq2: OldvsYoung
Deseq2dataAGE = phyloseq_to_deseq2(psPseudo, ~ SITE + SEX + ConjunOrEyelid + OldvsYoung)
Deseq2dataAGE = DESeq(Deseq2dataAGE, 
                   test="Wald", 
                   fitType="parametric")
resultDESeq2AGE <- results(Deseq2dataAGE)
df.resultDESeq2AGE <- as.data.frame(resultDESeq2AGE)
df.resultDESeq2AGE$taxon <- rownames(df.resultDESeq2AGE)
df.resultDESeq2AGE <- df.resultDESeq2AGE %>% arrange(log2FoldChange, padj)

if(!all(rownames(df.resultDESeq2AGE) %in% rownames(taxa_info))) {
  stop("Mismatch in OTU IDs between DESeq2 results and taxonomy table.")
}
df.resultDESeq2AGE.taxa <- merge(df.resultDESeq2AGE, taxa_info, by="row.names")
View(df.resultDESeq2AGE.taxa)

sig.taxa_DeseqAGE= df.resultDESeq2AGE.taxa %>% 
  filter(log2FoldChange >= 2.5 | log2FoldChange <= -2.5) %>%
  filter(padj < 0.05) %>%
  filter(!is.na(Genus)) %>%
  arrange(Genus)
sig.taxa_Deseq$taxon <- as.factor(sig.taxa_Deseq$taxon)

DESeqPlotAGE= ggplot(sig.taxa_DeseqAGE, aes(y = reorder(ASV, log2FoldChange), x = log2FoldChange, fill = Genus))+
  geom_col() +
  labs(
    x = "Log2 Fold Change",
    y = "Differentially Abundant ASVs") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); DESeqPlotAGE

#DESeq2: Male vs Female
Deseq2dataSEX = phyloseq_to_deseq2(psPseudo, ~ OldvsYoung+ SITE + ConjunOrEyelid + SEX)
Deseq2dataSEX = DESeq(Deseq2dataSEX, 
                      test="Wald", 
                      fitType="parametric")
resultDESeq2SEX <- results(Deseq2dataSEX)
df.resultDESeq2SEX <- as.data.frame(resultDESeq2SEX)
df.resultDESeq2SEX$taxon <- rownames(df.resultDESeq2SEX)
df.resultDESeq2SEX <- df.resultDESeq2SEX %>% arrange(log2FoldChange, padj)
df.resultDESeq2SEX.taxa <- merge(df.resultDESeq2SEX, taxa_info, by="row.names")

sig.taxa_DeseqSEX= df.resultDESeq2SEX.taxa %>% 
  filter(log2FoldChange >= 2.5 | log2FoldChange <= -2.5) %>%
  filter(padj < 0.05) %>%
  filter(!is.na(Genus)) %>%
  arrange(Genus)
sig.taxa_Deseq$taxon <- as.factor(sig.taxa_Deseq$taxon)

DESeqPlotSEX= ggplot(sig.taxa_DeseqSEX, aes(y = reorder(ASV, log2FoldChange), x = log2FoldChange, fill = Genus))+
  geom_col() +
  labs(
    x = "Log2 Fold Change",
    y = "Differentially Abundant ASVs",
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); DESeqPlotSEX

#DESeq2: CJ vs EL
Deseq2dataCJEL = phyloseq_to_deseq2(psPseudo, ~ SEX + OldvsYoung+ SITE + ConjunOrEyelid)
Deseq2dataCJEL = DESeq(Deseq2dataCJEL, 
                      test="Wald", 
                      fitType="parametric")
resultDESeq2CJEL <- results(Deseq2dataCJEL)
df.resultDESeq2CJEL <- as.data.frame(resultDESeq2CJEL)
df.resultDESeq2CJEL$taxon <- rownames(df.resultDESeq2CJEL)
df.resultDESeq2CJEL <- df.resultDESeq2CJEL %>% arrange(log2FoldChange, padj)

df.resultDESeq2CJEL.taxa <- merge(df.resultDESeq2CJEL, taxa_info, by="row.names")

sig.taxa_DeseqCJEL= df.resultDESeq2CJEL.taxa %>% 
  filter(log2FoldChange >= 2.5 | log2FoldChange <= -2.5) %>%
  filter(padj < 0.05) %>%
  filter(!is.na(Genus)) %>%
  arrange(Genus)
sig.taxa_Deseq$taxon <- as.factor(sig.taxa_Deseq$taxon)

DESeqPlotCJEL= ggplot(sig.taxa_DeseqCJEL, aes(y = reorder(ASV, log2FoldChange), x = log2FoldChange, fill = Genus)) +
  geom_col() +
  labs(
    x = "Log2 Fold Change (Effect Size)",
    y = "Differentially Abundant ASVs",
    #title = "Differentially Abundant OSM Genera By Sample Site (DESeq2)"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); DESeqPlotCJEL

# ANCOM-BC:
library(ANCOMBC)

ancomOut= ancombc2(
  ps.readCount,
  rank = "Genus",
  tax_level = "Genus",
  fix_formula = "OldvsYoung + SEX + ConjunOrEyelid + SITE",
  p_adj_method = "holm",
  prv_cut = 0.02,
  s0_perc = 0.05,
  group = "SITE",
  struc_zero = TRUE,
  neg_lb = TRUE,
  alpha = 0.05,
  n_cl = 1,
  verbose = FALSE,
  global = FALSE,
  pairwise = FALSE,
  dunnet = TRUE,
  trend = TRUE,
  iter_control = list(tol = 0.01, max_iter = 20, verbose = FALSE),
  em_control = list(tol = 1e-05, max_iter = 100),
  lme_control = lme4::lmerControl(),
  mdfdr_control = list(fwer_ctrl_method = "holm", B = 100),
  trend_control = list(contrast = NULL, node = NULL, solver = "ECOS", B = 100)
)
output_ancombc= ancomOut$res

#Taxa significant & resilient: SITE
sig.tax.ancomSITE= ancomOut$res %>% 
  filter(diff_SITESSFS == TRUE) %>% 
  filter(passed_ss_SITESSFS == TRUE) %>% 
  filter(q_SITESSFS < 0.05) %>% 
  filter(str_starts(taxon, "Genus:")) %>% 
  filter(lfc_SITESSFS >= 0.25 | lfc_SITESSFS <= -0.25) %>%
  arrange(desc(W_SITESSFS))
sig.tax.ancomSITE$taxon <- as.factor(sig.tax.ancomSITE$taxon)
ANCOMPlotSITE= ggplot(sig.tax.ancomSITE, aes(y = reorder(taxon, -lfc_SITESSFS), x = lfc_SITESSFS, fill = factor(lfc_SITESSFS > 0))) +
  geom_col() +
  labs(
    x = "Log Fold Change",
    y = "Differentially Abundant Taxa",
    title = "Living Condition"
  ) +
  theme_minimal(base_size = 14) +
  scale_fill_manual(values = c("TRUE" = "orange", "FALSE" = "lightblue"),  
                    name = "Direction", labels = c("Negative", "Positive")) +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); ANCOMPlotSITE

#Taxa significant & resilient: SEX
sig.tax.ancomSEX= ancomOut$res %>% 
  filter(diff_SEXM == TRUE) %>% 
  filter(passed_ss_SEXM == TRUE) %>% 
  filter(q_SEXM < 0.05) %>% 
  filter(str_starts(taxon, "Genus:")) %>% 
  filter(lfc_SEXM >= 0.25 | lfc_SEXM <= -0.25) %>% 
  arrange(desc(W_SEXM))
sig.tax.ancomSEX$taxon <- as.factor(sig.tax.ancomSEX$taxon)
ANCOMPlotSEX= ggplot(sig.tax.ancomSEX, aes(y = reorder(taxon, -lfc_SEXM), x = lfc_SEXM, fill= factor(lfc_SEXM > 0))) +
  geom_col() +
  labs(
    x = "Log Fold Change",
    y = "Differentially Abundant Taxa",
    title = "Sex"
  ) +
  theme_minimal(base_size = 14) +
  scale_fill_manual(values = c("TRUE" = "blue", "FALSE" = "lightgreen"),
                    name = "Direction", labels = c("Negative", "Positive")) +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); ANCOMPlotSEX

#Taxa significant & resilient: Old vs Young
sig.tax.ancomAGE= ancomOut$res %>% 
  filter(diff_OldvsYoungYoung == TRUE) %>% 
  filter(passed_ss_OldvsYoungYoung == TRUE) %>% 
  filter(q_OldvsYoungYoung < 0.05) %>%
  filter(str_starts(taxon, "Genus:")) %>%
  filter(lfc_OldvsYoungYoung >= 0.25 | lfc_OldvsYoungYoung <= -0.25) %>% 
  arrange(desc(W_OldvsYoungYoung))
sig.tax.ancomAGE$taxon <- as.factor(sig.tax.ancomAGE$taxon)
ANCOMPlotAGE= ggplot(sig.tax.ancomAGE, aes(y = reorder(taxon, -lfc_OldvsYoungYoung), x = lfc_OldvsYoungYoung, fill = factor(lfc_OldvsYoungYoung > 0))) +
  geom_col() +
  labs(
    x = "Log Fold Change",
    y = "Differentially Abundant Taxa",
    title = "Age"
  ) +
  theme_minimal(base_size = 14) +
  scale_fill_manual(values = c("TRUE" = "lightpink", "FALSE" = "purple"), 
                    name = "Direction", labels = c("Negative", "Positive")) +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); ANCOMPlotAGE

#Taxa significant & resilient: CJ vs EL
sig.tax.ancomCJEL= ancomOut$res %>% 
  filter(diff_ConjunOrEyelidEyelid == TRUE) %>% 
  filter(passed_ss_ConjunOrEyelidEyelid == TRUE) %>% 
  filter(q_ConjunOrEyelidEyelid < 0.05) %>% 
  filter(str_starts(taxon, "Genus:")) %>% 
  filter(lfc_ConjunOrEyelidEyelid >= 0.25 | lfc_ConjunOrEyelidEyelid <= -0.25) %>% 
  arrange(desc(W_ConjunOrEyelidEyelid))
sig.tax.ancomCJEL$taxon <- as.factor(sig.tax.ancomCJEL$taxon)

ANCOMPlotCJEL= ggplot(sig.tax.ancomCJEL, aes(y = reorder(taxon, -lfc_ConjunOrEyelidEyelid), x = lfc_ConjunOrEyelidEyelid, fill = taxon)) +
  geom_col() +
  labs(
    x = "Log Fold Change",
    y = "Differentially Abundant Taxa",
    title = "Sample Site"+
  )+
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 55, hjust = 1, vjust = 1)); ANCOMPlotCJEL

CombinedPlotANCOM= ANCOMPlotAGE + ANCOMPlotSEX + ANCOMPlotSITE +
  plot_annotation(tag_levels = "A") &
  theme(plot.tag.position = c(0,0)); CombinedPlotANCOM
```
