---
title: "Statistical analyses for *Influence of management practice on the microbiota of a critically endangered species: a longitudinal study of k\u101k\u101p\u14d chick faeces and associated nest litterr*"
author: "A.G. West"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Load packages into session, and print package version.

```{r results='hide'}
library(ggplot2); packageVersion("ggplot2")
library(Manu); packageVersion("Manu")
library(phyloseq); packageVersion("phyloseq")
library(gridExtra); packageVersion("gridExtra")
library(ggsignif); packageVersion("ggsignif")
library(ggrepel); packageVersion("ggrepel")
library(ggsci); packageVersion("ggsci")
library(hrbrthemes); packageVersion("hrbrthemes")
library(tidyverse); packageVersion("tidyverse")
library(viridis); packageVersion("viridis")
library(dplyr); packageVersion("dplyr")
library(extrafont); packageVersion("extrafont")
library(vegan); packageVersion("vegan")
library(ggpubr); packageVersion("ggpubr")
library(data.table); packageVersion("data.table")

set.seed(100)
```

##Import data

```{r}
seqtab.nochim <- data.frame(fread("16S_ASV_table_kakapo_BioC.txt"), row.names=1)
sum(rowSums(seqtab.nochim))
mean(rowSums(seqtab.nochim))
sd(rowSums(seqtab.nochim))
```

```{r}
taxa <- readRDS("16S_taxa_table_NC.rds")
Ptree <- readRDS("phylo_tree_NC.rds")

map <- read.table("mapping_file.txt",header = T, sep = '\t')
row.names(map) <- map$SAMPLE.ID

identical(rownames(seqtab.nochim), rownames(map))
```

```{r}
taxa <- data.frame(taxa)
taxa$Family[is.na(taxa$Family)]="Unclassified"
taxa$Genus[is.na(taxa$Genus)]="Unclassified"
taxa$Species[is.na(taxa$Species)]="unclassified"
taxa$Taxonomy <- paste(taxa$Genus, taxa$Species, sep=" ")

taxmatrix <- as.matrix(taxa) 
```

#Phyloseq
Create a phyloseq object for downstream analyses:

```{r}
ps <- phyloseq(tax_table(taxmatrix),sample_data(map),
               otu_table(seqtab.nochim, taxa_are_rows = F), 
               phy_tree(Ptree$tree))
ps

psF = subset_samples(ps, Type != "Litter") 
psF

psN = subset_samples(ps, Type != "Faeces") 
psN
```


##Filtering with phyloseq

####Taxonomic filtering 

Use to filter out non-target taxa e.g. mitochondria etc. 

```{r}
rank_names(ps)

ps_tax_table <- as.data.frame(tax_table(ps))
sum(is.na(ps_tax_table$Phylum)) 
str(ps_tax_table$Phylum)
sapply(ps_tax_table, n_distinct)
levels(factor(ps_tax_table$Kingdom))

plyr::count(ps_tax_table$Kingdom) 

archaea = subset_taxa(ps, Kingdom == "Archaea")
archaea
sum(rowSums(data.frame(otu_table(archaea))))
```

```{r}
ps_tax_table[is.na(ps_tax_table)]="Unclassified"
asv_table_ps<-as.data.frame(t(otu_table(ps)))
asv_table_wTax_ps <- cbind(asv_table_ps, ps_tax_table)

Phyla.sum.ps<-aggregate(asv_table_wTax_ps[,1:420], list(asv_table_wTax_ps$Phylum),sum)
row.names(Phyla.sum.ps)<- Phyla.sum.ps$Group.1
Phyla.sum.ps$Group.1 <- NULL
sum(rowSums(Phyla.sum.ps))
rowSums(Phyla.sum.ps != 0) #number of samples that phylum occurs in

P_rowsum.ps <- rowSums(Phyla.sum.ps)
P_rowsum.ps                         
dir.create("tables")
write.csv(P_rowsum.ps, "tables/P_rowsum_ps.csv")

#1300 / 19117949 = 0.007% of reads unassigned at phylum level
```

```{r}
table(tax_table(psF)[, "Phylum"], exclude = NULL)

psF0 <- subset_taxa(psF, !is.na(Phylum) & !Phylum %in% c("", "uncharacterized"))

phyla2Filter = c("<NA>")
psF1 = subset_taxa(psF0, !Phylum %in% phyla2Filter)#4% not assigned

phyla2Filter = c("Chloroplast","Rickettsiales")
psF1 = subset_taxa(psF1, !Order %in% phyla2Filter)
psF1
rank_names(psF1)
table(tax_table(psF1)[,"Phylum"], exclude = NULL)


rank_names(psN)
table(tax_table(psN)[, "Phylum"], exclude = NULL)

psN0 <- subset_taxa(psN, !is.na(Phylum) & !Phylum %in% c("", "uncharacterized"))

phyla2Filter = c("<NA>")
psN1 = subset_taxa(psN0, !Phylum %in% phyla2Filter)#4% not assigned

phyla2Filter = c("Chloroplast","Rickettsiales")
psN1 = subset_taxa(psN1, !Order %in% phyla2Filter)
psN1 #25914 taxa
rank_names(psN1)
table(tax_table(psN1)[,"Phylum"], exclude = NULL)
```

```{r}
# Transform to relative abundance
minTotRelAbun = 1e-5

x = taxa_sums(psF1)
keepTaxa = (x / sum(x)) > minTotRelAbun  
psF2 = prune_taxa(keepTaxa, psF1)
psF2

NtaxaF <- tax_table(psF2)



x = taxa_sums(psN1)
keepTaxa = (x / sum(x)) > minTotRelAbun  
psN2 = prune_taxa(keepTaxa, psN1)
psN2

NtaxaN <- tax_table(psN2)
```


#Rarefaction curves
```{r}
source('ggrarefaction_curves.R')

rcurves <- ggrare(psF2, step = 500, se = FALSE)
ggsave("rcurves_16S_chicks.png", rcurves, height = 10, width = 20)
```


#SRS
```{r}
library(SRS); packageVersion("SRS")
##Samples should be arranged columnwise
###Faecal###
srs.otuF = data.frame(t(otu_table(psF2)))
#SRS.shiny.app(srs.otuF)

# SRScurve.F <- SRScurve(srs.otuF, metric="richness", step = 100, 
#          ylab = "Faecal sample ASVs", col = "#6b2643", xlim = c(0,3000))
# SRScurve.F.line <- SRScurve.F + geom_vline(xintercept = 1200) 

SRS_outputF <- SRS(srs.otuF, Cmin = 1200) #4 samples discarded
SRS_outputF.df = data.frame(t(SRS_outputF))
colnames(SRS_outputF.df) = row.names(srs.otuF)
SRS_outputF.df = SRS_outputF.df[,order(colSums(SRS_outputF.df),decreasing = T)]
rownames(SRS_outputF.df) <- gsub(x = rownames(SRS_outputF.df), pattern = "\\.", replacement = "-") 

#For GUniFrac
psF_SRS_GUF <- phyloseq(otu_table(SRS_outputF.df, taxa_are_rows = F),
                        sample_data(psF2),
                        tax_table(NtaxaF),
                        phy_tree(psF2))


#For renaming ASVs
NtaxaF.df = as.data.frame(NtaxaF)
to.remove <- setdiff(rownames(NtaxaF.df), colnames(SRS_outputF.df))
NtaxaF.df = NtaxaF.df[!row.names(NtaxaF.df) %in% to.remove,]
setdiff(rownames(NtaxaF.df), colnames(SRS_outputF.df))
identical(rownames(NtaxaF.df), colnames(SRS_outputF.df))
NtaxaF.df = NtaxaF.df[colnames(SRS_outputF.df),]
identical(rownames(NtaxaF.df), colnames(SRS_outputF.df))
NtaxaF.df$ASV_ID <- paste("ASV_", 1:nrow(NtaxaF.df), sep="")
NtaxaF.df$concat = paste(NtaxaF.df$ASV_ID, NtaxaF.df$Taxonomy, sep = "_")
rownames(NtaxaF.df) = NtaxaF.df$concat
colnames(SRS_outputF.df) = rownames(NtaxaF.df)
NtaxaF.df$ASV_ID = NULL
NtaxaF.df$concat = NULL
NtaxaF.df = as.matrix(NtaxaF.df)


rownames(SRS_outputF.df) <- gsub(x = rownames(SRS_outputF.df), pattern = "\\.", replacement = "-") 



###Nest###
srs.otuN = data.frame(t(otu_table(psN2)))

# SRScurve.N <- SRScurve(srs.otuN[1:100], metric="richness", step = 100, 
#          ylab = "Litter sample ASVs", col = "#7D9D33", xlim = c(0,3000)) 
# SRScurve.N.line <- SRScurve.N + + geom_vline(xintercept = 1850)

SRS_outputN <- SRS(srs.otuN, Cmin = 1850) #5 samples discarded
SRS_outputN.df = data.frame(t(SRS_outputN))
colnames(SRS_outputN.df) = row.names(srs.otuN)
SRS_outputN.df = SRS_outputN.df[,order(colSums(SRS_outputN.df),decreasing = T)]
rownames(SRS_outputN.df) <- gsub(x = rownames(SRS_outputN.df), pattern = "\\.", replacement = "-")

#For GUniFrac
psN_SRS_GUF <- phyloseq(otu_table(SRS_outputN.df, taxa_are_rows = F),
                        sample_data(psN2),
                        tax_table(NtaxaN),
                        phy_tree(psN2))

#For renaming ASVs

NtaxaN.df = as.data.frame(NtaxaN)
to.remove <- setdiff(rownames(NtaxaN.df), colnames(SRS_outputN.df))
NtaxaN.df = NtaxaN.df[!row.names(NtaxaN.df) %in% to.remove,]
setdiff(rownames(NtaxaN.df), colnames(SRS_outputN.df))
identical(rownames(NtaxaN.df), colnames(SRS_outputN.df))
NtaxaN.df = NtaxaN.df[colnames(SRS_outputN.df),]
identical(rownames(NtaxaN.df), colnames(SRS_outputN.df))
NtaxaN.df$ASV_ID <- paste("ASV_", 1:nrow(NtaxaN.df), sep="")
NtaxaN.df$concat = paste(NtaxaN.df$ASV_ID, NtaxaN.df$Taxonomy, sep = "_")
rownames(NtaxaN.df) = NtaxaN.df$concat
colnames(SRS_outputN.df) = rownames(NtaxaN.df)
NtaxaN.df$ASV_ID = NULL
NtaxaN.df$concat = NULL
NtaxaN.df = as.matrix(NtaxaN.df)


rownames(SRS_outputN.df) <- gsub(x = rownames(SRS_outputN.df), pattern = "\\.", replacement = "-")
```

```{r}
write.csv(SRS_outputF.df, "tables/SRS_asv_table_F.csv")
write.csv(SRS_outputN.df, "tables/SRS_asv_table_N.csv")
```


```{r}
map.ps2.F <- data.frame(sample_data(psF2))
f.to.delete <- setdiff(rownames(map.ps2.F), rownames(SRS_outputF.df))
map.ps2.F = map.ps2.F[!row.names(map.ps2.F) %in% f.to.delete,]
map.ps2.F$Date <- as.Date(map.ps2.F$Date, format = "%d/%m/%Y")
map.ps2.F.sort <- dplyr::arrange(map.ps2.F, Name, Date)
SRS_outputF.df.sort <- SRS_outputF.df[map.ps2.F.sort$SAMPLE.ID,]

psF_SRS = phyloseq(otu_table(SRS_outputF.df.sort, taxa_are_rows = F), 
                sample_data(map.ps2.F.sort),
                tax_table(NtaxaF.df))

psF_SRS     
psF_SRS_otu = data.frame(otu_table(psF_SRS))
avg_ASV_F <- data.frame(rowSums(psF_SRS_otu != 0))
prev_ASV_F <- data.frame(colSums(psF_SRS_otu != 0))


sample_data(psF_SRS)$Age <- factor(sample_data(psF_SRS)$Age, 
                                        level = c("<14 days","15-28 days","29-42 days","43-56 days","57-70 days","71-120 days","200+ days"),
                          label = c("<14 days","15 - 28 days","29 - 42 days","43 - 56 days","57 - 70 days","71 - 120 days","200+ days"))

map.ps2.N <- data.frame(sample_data(psN2))
n.to.delete <- setdiff(rownames(map.ps2.N), rownames(SRS_outputN.df))
map.ps2.N = map.ps2.N[!row.names(map.ps2.N) %in% n.to.delete,]
map.ps2.N$Date <- as.Date(map.ps2.N$Date, format = "%d/%m/%Y")
map.ps2.N.sort <- dplyr::arrange(map.ps2.N, Name, Date)
SRS_outputN.df.sort <- SRS_outputN.df[map.ps2.N.sort$SAMPLE.ID,]

psN_SRS = phyloseq(otu_table(SRS_outputN.df.sort, taxa_are_rows = F), 
                sample_data(map.ps2.N.sort),
                tax_table(NtaxaN.df))

psN_SRS     
psN_SRS_otu = data.frame(otu_table(psN_SRS))
avg_ASV_N <- data.frame(rowSums(psN_SRS_otu != 0))
prev_ASV_N <- data.frame(colSums(psN_SRS_otu != 0))


sample_data(psN_SRS)$Age <- factor(sample_data(psN_SRS)$Age, 
                                        levels = c("<14 days","15-28 days","29-42 days","43-56 days","57-70 days","71-120 days"),
                                        labels = c("<14 days","15 - 28 days","29 - 42 days","43 - 56 days","57 - 70 days","71 - 90 days"))

sample_data(psN_SRS)$Name <- factor(sample_data(psN_SRS)$Name, 
                                          levels = c("Alice_Nest","Aranga_Nest","Atareta_Nest","Awarua_Nest","Bella_Nest",
                                                     "Boomer_Nest","Cyndy_Nest","Esperance_Nest","Evohe_Nest","Hauturu_Nest",
                                                     "Hinemoa_Nest","Hinetaumai_Nest","Hoki_Nest","Huhana_Nest","Ihi_Nest",
                                                     "Jemma_Nest","Kuia_Nest","Kuihi_Nest","Marama_Nest",
                                                     "Margaretmaree_Nest","Nora_Nest","Pounamu_Nest","Pura_Nest",
                                                     "Queenie_Nest","Ra_Nest","Rakiura_Nest","Roha_Nest","Sue_Nest",
                                                     "Suzanne_Nest","Tumeke_Nest","Waa_Nest","Waikawa_Nest",
                                                     "Wehepo_Nest","Zephyr_Nest"),
                                          labels = c("Alice","Aranga","Atareta","Awarua","Bella","Boomer",
                                                     "Cyndy","Esperance","Evohe","Hauturu","Hinemoa","Hine Taumai",
                                                     "Hoki","Huhana","Ihi","Jemma","Kuia","Kuihi",
                                                     "Marama","Margaret-Maree","Nora","Pounamu","Pura","Queenie",
                                                     "Ra","Rakiura","Roha","Sue","Suzanne","Tumeke","Waa","Waikawa",
                                                     "Weheruatanga-o-te-po","Zephyr"))
```


#Compare SRS to Rarefaction
```{r}
rASVF <- rarefy_even_depth(otu_table(psF2, taxa_are_rows = F), sample.size = 1200,replace = FALSE)

rASVN <- rarefy_even_depth(otu_table(psN2, taxa_are_rows = F), sample.size = 1850,replace = FALSE)

psRF <- phyloseq(otu_table(rASVF, taxa_are_rows = F),
                sample_data(psF2),
                tax_table(NtaxaF))

psRN <- phyloseq(otu_table(rASVN, taxa_are_rows = F),
                sample_data(psN2),
                tax_table(NtaxaN))
```

###Mantel test
```{r}
rASVF.df = data.frame(rASVF)
rASVN.df = data.frame(rASVN)

psRF.dist = vegan::vegdist(rASVF.df, method = "bray")
srsF.dist = vegan::vegdist(SRS_outputF.df, method = "bray")

mantel(psRF.dist, srsF.dist, method = "spearman", permutations = 9999)

psRN.dist = vegan::vegdist(rASVN.df, method = "bray")
srsN.dist = vegan::vegdist(SRS_outputN.df, method = "bray")

mantel(psRN.dist, srsN.dist, method = "spearman", permutations = 9999)

```

#Data summaries
```{r}
map.f <- data.frame(sample_data(psF_SRS))
map.n <- data.frame(sample_data(psN_SRS))

pool = c("POOL")
map.f.np = map.f[!(map.f$Group %in% pool),]

summary_data <- map.f.np %>%
    group_by(Nest, Name) %>%
    dplyr::summarise(Count = n()) 
summary_data

map.f %>% dplyr::count(Group)
map.f %>% dplyr::count(Name)
map.f.np %>% dplyr::count(Name)
map.f %>% dplyr::count(Age)
map.f %>% dplyr::count(Aspergillosis)
map.f %>% dplyr::count(Nest)
map.f %>% dplyr::count(Movement)
map.f %>% dplyr::count(Faecal_experiment)
map.f %>% dplyr::count(Location)
map.f %>% dplyr::count(Nest_type)
map.f %>% dplyr::count(Hand_rearing)
map.f %>% dplyr::count(Born_in_nest)

map.n %>% dplyr::count(Age)
map.n %>% dplyr::count(Aspergillosis)
map.n %>% dplyr::count(Nest)
map.n %>% dplyr::count(Movement)
map.n %>% dplyr::count(Faecal_experiment)
map.n %>% dplyr::count(Location)
map.n %>% dplyr::count(Nest_type)
```

```{r}
SRS_asv_tableF<-as.data.frame(t(otu_table(psF_SRS)))
SRS_taxo_tableF<-as.data.frame(tax_table(psF_SRS))
SRS_asv_table_wTaxF <- cbind(SRS_asv_tableF, SRS_taxo_tableF)

SRS_asv_tableN<-as.data.frame(t(otu_table(psN_SRS)))
SRS_taxo_tableN<-as.data.frame(tax_table(psN_SRS))
SRS_asv_table_wTaxN <- cbind(SRS_asv_tableN, SRS_taxo_tableN)
```

```{r}
#Phylum
Phyla.sumF<-aggregate(SRS_asv_table_wTaxF[,1:287], list(SRS_asv_table_wTaxF$Phylum),sum)
row.names(Phyla.sumF)<- Phyla.sumF$Group.1
Phyla.sumF$Group.1 <- NULL
P_rowsumF <- rowSums(Phyla.sumF)
write.csv(Phyla.sumF, "tables/Phyla_sumF_per_sample_NC_kakapo.csv")
write.csv(P_rowsumF, "tables/P_rowsumF_NC_kakapo_fungi.csv")


Phyla.sumN<-aggregate(SRS_asv_table_wTaxN[,1:124], list(SRS_asv_table_wTaxN$Phylum),sum)
row.names(Phyla.sumN)<- Phyla.sumN$Group.1
Phyla.sumN$Group.1 <- NULL
P_rowsumN <- rowSums(Phyla.sumN)
write.csv(Phyla.sumN, "tables/Phyla_sumN_per_sample_NC_kakapo.csv")
write.csv(P_rowsumN, "tables/P_rowsumN_NC_kakapo.csv")


sum(rowSums(Phyla.sumF)) #344400
rowSums(Phyla.sumF != 0)

sum(rowSums(Phyla.sumN)) #229400
rowSums(Phyla.sumN != 0)
```

```{r}
Genus.sumF <- aggregate(SRS_asv_table_wTaxF[,1:287], list(SRS_asv_table_wTaxF$Genus),sum)
row.names(Genus.sumF)<- Genus.sumF$Group.1
Genus.sumF$Group.1 <- NULL
G_rowsumF <- rowSums(Genus.sumF) 
write.csv(G_rowsumF, "tables/genus_rowsumF_NC_kakapo.csv")
write.csv(Genus.sumF, "tables/Genus_sumF_per_sample_NC_kakapo.csv")

Genus.sumN <- aggregate(SRS_asv_table_wTaxN[,1:124], list(SRS_asv_table_wTaxN$Genus),sum)
row.names(Genus.sumN)<- Genus.sumN$Group.1
Genus.sumN$Group.1 <- NULL
G_rowsumN <- rowSums(Genus.sumN) 
write.csv(G_rowsumN, "tables/genus_rowsumN_NC_kakapo.csv")
write.csv(Genus.sumN, "tables/Genus_sumN_per_sample_NC_kakapo.csv")
```


```{r}
taxa.sumF <- aggregate(SRS_asv_table_wTaxF[,1:287], list(SRS_asv_table_wTaxF$Taxonomy),sum)
row.names(taxa.sumF)<- taxa.sumF$Group.1
taxa.sumF$Group.1 <- NULL
t_rowsumF <- rowSums(taxa.sumF) 
write.csv(t_rowsumF, "tables/taxa_rowsumF_NC_kakapo.csv")
write.csv(taxa.sumF, "tables/taxa_sumF_per_sample_NC_kakapo.csv")

taxa.sumN <- aggregate(SRS_asv_table_wTaxN[,1:124], list(SRS_asv_table_wTaxN$Taxonomy),sum)
row.names(taxa.sumN)<- taxa.sumN$Group.1
taxa.sumN$Group.1 <- NULL
t_rowsumN <- rowSums(taxa.sumN) 
write.csv(t_rowsumN, "tables/taxa_rowsumN_NC_kakapo.csv")
write.csv(taxa.sumN, "tables/taxa_sumN_per_sample_NC_kakapo.csv")
```

#PERMANOVA
###Poo Removal
```{r}
library(dunn.test); packageVersion("dunn.test")
#Faecal
psF_UKsubset <- subset_samples(psF_SRS, Faecal_experiment != "Unknown")
permanova.dis.F.UK <- distance(psF_UKsubset, "bray")
map.F.UK <- data.frame(sample_data(psF_UKsubset))
adonis2(permanova.dis.F.UK ~ Nest + Faecal_experiment, map.F.UK, by = "term", 
        permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=map.F.UK$Name)))

beta.pooR <- vegan::betadisper(permanova.dis.F.UK, map.F.UK$Faecal_experiment)
beta.pooR
vegan::permutest(beta.pooR,permutations = how(nperm = 9999))
beta.pooR.df <- data.frame(beta.pooR$distances)
beta.pooR.df$Group = beta.pooR$group
dunn.test::dunn.test(beta.pooR.df$beta.pooR.distances, beta.pooR.df$Group, method = "bh")


psF_UK_HRsubset <- subset_samples(psF_SRS, Faecal_experiment != "Unknown" & Faecal_experiment != "Hand rearing")
permanova.dis.F.UK.HR <- distance(psF_UK_HRsubset, "bray")
map.F.UK.HR <- data.frame(sample_data(psF_UK_HRsubset))
adonis2(permanova.dis.F.UK.HR ~ Nest + Faecal_experiment, map.F.UK.HR, by = "term", 
        permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=map.F.UK.HR$Name)))

#Nest
psN_UKsubset <- subset_samples(psN_SRS, Faecal_experiment != "Unknown")
map.N.UK <- data.frame(sample_data(psN_UKsubset))
permanova.dis.N.UK <- phyloseq::distance(psN_UKsubset, "bray")
adonis2(permanova.dis.N.UK ~ Faecal_experiment, map.N.UK, 
        permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=map.N.UK$Name)))

beta.pooR.N <- vegan::betadisper(permanova.dis.N.UK, map.N.UK$Faecal_experiment)
beta.pooR.N
vegan::permutest(beta.pooR.N)
beta.pooR.N.df <- data.frame(beta.pooR.N$distances)
beta.pooR.N.df$Group = beta.pooR.N$group
dunn.test::dunn.test(beta.pooR.N.df$beta.pooR.N.distances, beta.pooR.N.df$Group, method = "bh")
```

#####BC boxplots

```{r}
boxplot_theme <- theme_ipsum() + theme(plot.title = element_text(size = 26),
  
          plot.subtitle = element_text(size = 24),
          
          axis.text.x = element_blank(),

          axis.title.x = element_text(size=20),

          axis.ticks.x = element_blank(),

          axis.text.y=element_text(size=18),

          axis.title.y=element_text(size=20),

          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_line(color="black",size=1.0,linetype=1),

          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),

          legend.box.background = element_rect(),

          legend.box.margin = margin(5, 5, 5, 5),

          legend.position="bottom",

          legend.title = element_text(face = "bold", size = 24),
          
          legend.text = element_text(size = 20))
```



```{r fig.height= 10, fig.width=12}
library(reshape2); packageVersion("reshape2")
library(pairwiseAdonis); packageVersion("pairwiseAdonis")

otu_split.F <- data.frame(otu_table(psF_UKsubset))
rownames(otu_split.F) <- map.F.UK$Date_Name
otu_split.F1.BC <- split(otu_split.F, map.F.UK$Faecal_experiment)

dist.list.f.bc<- c() 

for (i in 1:length(otu_split.F1.BC)) {
     dist.list.f.bc[[i]] <- as.matrix(vegdist(otu_split.F1.BC[[i]], method = "bray"))
}

names(dist.list.f.bc) = names(otu_split.F1.BC)
df.f.bc <- melt(dist.list.f.bc)
names(df.f.bc) <- c("Sample1", "Sample2", "BCdistance","Faecal_experiment")

df.f.bc$match = df.f.bc$Sample1 == df.f.bc$Sample2
df.f.bc.2 = df.f.bc[-which(df.f.bc$match == "TRUE"),]


source('pairwiseAdonis3.R')
## Permutes within check and also uses "series" permutation
pairwise.adonis3(permanova.dis.F.UK ~ Faecal_experiment, data = map.F.UK,  p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series")


faecal.bc <- data.frame(start=c("Faeces in","Faeces removed","Hand rearing"), 
                            end=c("Hand rearing","Hand rearing","Mixed"),
                            y=c(1.3,1.15,1.1),
                            label=c("0.002**","0.02*","0.009**"))

faecal.bc.boxplot <- ggplot(df.f.bc.2,aes(x = Faecal_experiment, y = BCdistance)) + 
  geom_jitter(position = position_jitter(0.3), aes(color = Faecal_experiment), alpha = 0.75) +
  geom_boxplot(size=1.0, fill='transparent') + 
  boxplot_theme +
  guides(colour = guide_legend(override.aes = list(size=6))) +
  labs(x = "Faecal experiment", y = "Bray-Curtis dissimilarity") +
  ggtitle("Faecal samples", subtitle =  "PERMANOVA p < 0.0001") +
  scale_color_manual(name = "Bray-Curtis distances",values= get_pal("Kakapo")) +
  geom_signif(data=faecal.bc,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 6)
faecal.bc.boxplot


faecal.bc.boxplot.nojitter <- ggplot(df.f.bc.2,aes(x = Faecal_experiment, y = BCdistance)) + 
  geom_boxplot(size=1.0, aes(fill = Faecal_experiment)) + 
  boxplot_theme +
  labs(x = "Faecal experiment groups", y = "Bray-Curtis dissimilarity") +
  ggtitle("Faecal samples", subtitle =  "PERMANOVA p < 0.001") +
  scale_fill_manual(name = "Bray-Curtis distances",values= get_pal("Kakapo")) +
  geom_signif(data=faecal.bc,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 6)
faecal.bc.boxplot.nojitter
ggsave("boxplots/bc_faecal_pooR_nojitter.png", faecal.bc.boxplot.nojitter, height = 10, width = 12, dpi = 400)
```


```{r fig.height= 10, fig.width=12}
otu_split.N <- data.frame(otu_table(psN_UKsubset))
rownames(otu_split.N) <- map.N.UK$Date_Name
otu_split.N1.BC <- split(otu_split.N, map.N.UK$Faecal_experiment)

dist.list.n.bc<- c() 

for (i in 1:length(otu_split.N1.BC)) {
     dist.list.n.bc[[i]] <- as.matrix(vegdist(otu_split.N1.BC[[i]], method = "bray"))
}

names(dist.list.n.bc) = names(otu_split.N1.BC)
df.n.bc <- melt(dist.list.n.bc)
names(df.n.bc) <- c("Sample1", "Sample2", "BCdistance","Faecal_experiment")

df.n.bc$match = df.n.bc$Sample1 == df.n.bc$Sample2
df.n.bc.2 = df.n.bc[-which(df.n.bc$match == "TRUE"),]

litter.bc.boxplot <- ggplot(df.n.bc.2,aes(x = Faecal_experiment, y = BCdistance)) + 
  geom_jitter(position = position_jitter(0.3), aes(color = Faecal_experiment), alpha = 0.75) +
  geom_boxplot(size=1.0, fill='transparent') + 
  boxplot_theme +
  guides(colour = guide_legend(override.aes = list(size=6))) +
  labs(x = "Faecal experiment", y = "Bray-Curtis dissimilarity distances") +
  ggtitle("Litter samples", subtitle =  "PERMANOVA p = 1") +
  scale_color_manual(name = "Faecal removal",values= get_pal("Kakapo")) 
litter.bc.boxplot

litter.bc.boxplot.nojitter <- ggplot(df.n.bc.2,aes(x = Faecal_experiment, y = BCdistance)) + 
  geom_boxplot(size=1.0, aes(fill = Faecal_experiment)) + 
  boxplot_theme +
  labs(x = "Faecal experiment groups", y = "Bray-Curtis dissimilarity") +
  ggtitle("Litter samples", subtitle =  "PERMANOVA p = 1") +
  scale_fill_manual(name = "Bray-Curtis distances",values= get_pal("Kakapo")) 
litter.bc.boxplot.nojitter
ggsave("boxplots/bc_litter_pooR_nojitter.png", litter.bc.boxplot.nojitter, height = 10, width = 12, dpi = 400)
```

```{r fig.height= 10, fig.width=24}
bc.boxplots.combined = ggarrange(faecal.bc.boxplot.nojitter, litter.bc.boxplot.nojitter, labels = c("A","B"), font.label = list(size = 30), 
          ncol=2, nrow=1)
bc.boxplots.combined
ggsave("boxplots/bc_boxplots_combined_nojitter.png", bc.boxplots.combined, width = 24, height = 10, dpi = 400)
```

```{r fig.height= 13, fig.width=24}
bc.boxplots.combined = ggarrange(faecal.bc.boxplot.nojitter, litter.bc.boxplot.nojitter, labels = c("B"), font.label = list(size = 30), 
          ncol=2, nrow=1, common.legend = T, legend = c("bottom"))
bc.boxplots.combined
```


###Faecal
```{r}
###FAECAL###
permanova.dis.F <- distance(psF_SRS, "bray")
adonis.map.F <- data.frame(sample_data(psF_SRS))

#Faecal removal including Hand-rearing + Unknown
vegan::adonis2(permanova.dis.F ~ Faecal_experiment, adonis.map.F,
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

pairwise.adonis3(permanova.dis.F ~ Faecal_experiment, data = adonis.map.F,  p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series") 

#Movement
vegan::adonis2(permanova.dis.F ~ Nest + Movement, adonis.map.F,by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

beta.m <- vegan::betadisper(permanova.dis.F, adonis.map.F$Movement)
beta.m
vegan::permutest(beta.m, permutations = how(nperm = 9999))

#Location
vegan::adonis2(permanova.dis.F ~ Nest + Location, adonis.map.F, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

vegan::adonis2(permanova.dis.F ~ Location, adonis.map.F, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

pairwise.adonis3(permanova.dis.F ~ Location, data = adonis.map.F, p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series")

beta.l <- vegan::betadisper(permanova.dis.F, adonis.map.F$Location)
beta.l
vegan::permutest(beta.l, permutations = how(nperm = 9999))

beta.l.df <- data.frame(beta.l$distances)
beta.l.df$Group = beta.l$group
dunn.test::dunn.test(beta.l.df$beta.l.distances, beta.l.df$Group, method = "bh")

####Without hand rearing samples
psF_sub.L <- subset_samples(psF_SRS, Location != "Hand rearing")
disF.sub.L <- distance(psF_sub.L, "bray")
mapF.sub.L <- data.frame(sample_data(psF_sub.L))
vegan::adonis2(disF.sub.L ~ Nest + Location, mapF.sub.L, by = "term", 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.L$Name)))

#Rearing
vegan::adonis2(permanova.dis.F ~ Hand_rearing, adonis.map.F, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

#Chick age
vegan::adonis2(permanova.dis.F ~ Nest + Age, adonis.map.F, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

vegan::adonis2(permanova.dis.F ~ Nest + Days, adonis.map.F, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

vegan::adonis2(disF.sub.L ~ Nest + Age, mapF.sub.L, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.L$Name)))

vegan::adonis2(disF.sub.L ~ Nest + Days, mapF.sub.L, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.L$Name)))

pairwise.adonis3(permanova.dis.F ~ Age, data = adonis.map.F, p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series")

beta.age <- vegan::betadisper(permanova.dis.F, adonis.map.F$Age)
beta.age
vegan::permutest(beta.age)  

beta.age.df <- data.frame(beta.age$distances)
beta.age.df$Group = beta.age$group
dunn.test::dunn.test(beta.age.df$beta.age.distances, beta.age.df$Group, method = "bh")
                          
#Aspergillosis
vegan::adonis2(permanova.dis.F ~ Nest + Aspergillosis, adonis.map.F, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))

beta.asp <- vegan::betadisper(permanova.dis.F, adonis.map.F$Aspergillosis)
beta.asp
vegan::permutest(beta.asp, permutations = how(nperm = 9999))

#Nest type
##No sub-adult samples 
psF_sub_NT_HR <- subset_samples(psF_SRS, Nest_type != "Sub-adult samples") 
disF.sub.NT_HR <- distance(psF_sub_NT_HR, "bray")
mapF.sub.NT_HR <- data.frame(sample_data(psF_sub_NT_HR))
vegan::adonis2(disF.sub.NT_HR ~ Nest_type, mapF.sub.NT_HR, 
              permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.NT_HR$Name)))

pairwise.adonis3(disF.sub.NT_HR ~ Nest_type, data = mapF.sub.NT_HR, p.adjust.m = "BH", strata = "Name", nperm = 9999, within_type = "series")

beta.nt <- vegan::betadisper(disF.sub.NT_HR, mapF.sub.NT_HR$Nest_type)
beta.nt
vegan::permutest(beta.nt, permutations = how(nperm = 9999)) 

##No sub-adult or hand-rearing samples
psF_sub_NT <- subset_samples(psF_SRS, Nest != "Sub-adult samples" & Nest != "Hand rearing")
disF.sub.NT <- distance(psF_sub_NT, "bray")
mapF.sub.NT <- data.frame(sample_data(psF_sub_NT))
vegan::adonis2(disF.sub.NT ~ Nest + Nest_type, mapF.sub.NT, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.NT$Name)))

pairwise.adonis3(disF.sub.NT ~ Nest_type, data = mapF.sub.NT, p.adjust.m = "BH", strata = "Name", nperm = 9999, within_type = "series")

#Nest
##No sub-adult samples
vegan::adonis2(disF.sub.NT_HR ~ Nest, mapF.sub.NT_HR, by = "term",
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.NT_HR$Name)))

nest.pairwise.noHR.nosubAdult <- pairwise.adonis3(disF.sub.NT_HR ~ Nest, data = mapF.sub.NT_HR, p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series")
nest.pairwise.noHR.nosubAdult.subset <- within(nest.pairwise.noHR.nosubAdult, rm(Ihi_vs_Esperance,Ihi_vs_Yasmine,Esperance_vs_Yasmine))
write.table(nest.pairwise.noHR.nosubAdult.subset, "tables/faecal_nest_noSubAdult_adonis_pairwise_comparisons.csv") 

beta.n <- vegan::betadisper(disF.sub.NT_HR, mapF.sub.NT_HR$Nest)
beta.n
vegan::permutest(beta.n, permutations = how(nperm = 9999)) 

##No sub-adult samples or hand-rearing samples
vegan::adonis2(disF.sub.NT ~ Nest, mapF.sub.NT, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=mapF.sub.NT$Name)))

nest.pairwise.nosubadult <- pairwise.adonis3(disF.sub.NT ~ Nest, data = mapF.sub.NT, p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series")
nests.null = Filter(is.null, nest.pairwise.nosubadult) 
nest.pairwise.nosubadult.subset <- within(nest.pairwise.nosubadult, rm(Ihi_vs_Esperance,Ihi_vs_Yasmine,Esperance_vs_Yasmine))
write.table(nest.pairwise.nosubadult.subset, "tables/faecal_nest_noHRorsubAdult_adonis_pairwise_comparisons.csv") 



#Chick
vegan::adonis2(permanova.dis.F ~ Nest + Name, adonis.map.F, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.F$Name)))


```

```{r}
p.f.perm.hr <- c("0.0001","0.99","0.0001","0.04","0.0001","0.26","0.0001","0.0001","1")
p.f.perm <- c("0.87","0.99","0.01","0.003","0.006")


p.adjust(p.f.perm.hr, method = "BH")
p.adjust(p.f.perm, method = "BH")


p.beta.f <- c("0.0001","0.005","0.0001","0.0001","0.0001","0.04")
p.adjust(p.beta.f, method = "BH")
```


```{r fig.height= 15, fig.width=25}
otu_split.F.nest <- data.frame(otu_table(psF_sub_NT))
rownames(otu_split.F.nest) <- mapF.sub.NT$Date_Name
otu_split.F.nest.BC <- split(otu_split.F.nest, mapF.sub.NT$Nest)

dist.list.f.nest.bc<- c() 

for (i in 1:length(otu_split.F.nest.BC)) {
     dist.list.f.nest.bc[[i]] <- as.matrix(vegdist(otu_split.F.nest.BC[[i]], method = "bray"))
}

names(dist.list.f.nest.bc) = names(otu_split.F.nest.BC)
df.f.nest.bc <- melt(dist.list.f.nest.bc)
names(df.f.nest.bc) <- c("Sample1", "Sample2", "BCdistance","Nest")

df.f.nest.bc$match = df.f.nest.bc$Sample1 == df.f.nest.bc$Sample2
df.f.nest.bc.2 = df.f.nest.bc[-which(df.f.nest.bc$match == "TRUE"),]


source('pairwiseAdonis3.R')
## Permutes within check and also uses "series" permutation
nest.pairwise.nosubadult <- pairwise.adonis3(disF.sub.NT ~ Nest, data = mapF.sub.NT, p.adjust.m = 'BH', strata = "Name", nperm = 999, within_type = "series")
nests.null = Filter(is.null, nest.pairwise.nosubadult) #$Ihi_vs_Esperance $Ihi_vs_Yasmine $Esperance_vs_Yasmine
nest.pairwise.nosubadult.subset <- within(nest.pairwise.nosubadult, rm(Ihi_vs_Esperance,Ihi_vs_Yasmine,Esperance_vs_Yasmine))

nest.pairwise.list <- melt(nest.pairwise.nosubadult.subset)
nest.pairwise.list[which(nest.pairwise.list$value < 0.05 & nest.pairwise.list$variable == 'Pr..F.'),]


faecal.nest.bc.boxplot <- ggplot(df.f.nest.bc.2,aes(x = Nest, y = BCdistance)) + 
  geom_boxplot(size=1.0, aes(fill = Nest)) + 
  boxplot_theme +
  guides(colour = guide_legend(override.aes = list(size=6))) +
  labs(x = "Nest", y = "Bray-Curtis dissimilarity") +
  ggtitle("Faecal samples", subtitle =  "PERMANOVA p < 0.001") +
  #scale_color_manual(name = "Bray-Curtis distances",values= get_pal("Kakapo")) +
  geom_signif()
faecal.nest.bc.boxplot

```


###Litter
```{r}
###NEST###
adonis.map.N <- data.frame(sample_data(psN_SRS))
permanova.dis.N <- phyloseq::distance(psN_SRS, "bray")

#Movement
vegan::adonis2(permanova.dis.N ~ Movement, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

beta.M.L <- vegan::betadisper(permanova.dis.N, adonis.map.N$Movement)
beta.M.L
vegan::permutest(beta.M.L) 

#Island
vegan::adonis2(permanova.dis.N ~ Location, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

beta.I.L <- vegan::betadisper(permanova.dis.N, adonis.map.N$Location)
beta.I.L
vegan::permutest(beta.I.L) 

#Days since first chick
vegan::adonis2(permanova.dis.N ~ Days, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

vegan::adonis2(permanova.dis.N ~ Age, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

pairwise.adonis3(permanova.dis.N ~ Age, data = adonis.map.N, p.adjust.m = 'BH', strata = "Name", nperm = 9999, within_type = "series")

beta.age.L <- vegan::betadisper(permanova.dis.N, adonis.map.N$Age)
beta.age.L
vegan::permutest(beta.age.L, permutations = how(nperm = 9999)) #0.001

beta.age.L.df <- data.frame(beta.age.L$distances)
beta.age.L.df$Group = beta.age.L$group
dunn.test::dunn.test(beta.age.L.df$beta.age.L.distances, beta.age.L.df$Group, method = "bh")

#Aspergillosis
vegan::adonis2(permanova.dis.N ~ Aspergillosis, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

beta.asp.L <- vegan::betadisper(permanova.dis.N, adonis.map.N$Aspergillosis)
beta.asp.L
vegan::permutest(beta.asp.L, permutations = how(nperm = 9999))

#Nest type
vegan::adonis2(permanova.dis.N ~ Nest_type, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

beta.NT.L <- vegan::betadisper(permanova.dis.N, adonis.map.N$Nest_type)
beta.NT.L
vegan::permutest(beta.NT.L, permutations = how(nperm = 9999))

#Nest
vegan::adonis2(permanova.dis.N ~ Nest, adonis.map.N, 
               permutations = how(nperm = 9999, within=Within(type="series"), plots=Plots(strata=adonis.map.N$Name)))

```


```{r}
p.beta.L <- c("0.79","0.0001","0.001","0.49","0.38","0.03")
p.adjust(p.beta.L, method = "BH")
```


#Taxa plots


```{r}
taxaplot_theme <-  theme_ipsum() + theme(plot.title = element_text(size = 35),
  
          axis.text.x = element_blank(),

          axis.ticks.x = element_blank(),

          axis.text.y=element_text(size=25),

          axis.title.y=element_text(size=35),
          
          axis.title.x = element_text(size=35),
          
          strip.text.x = element_text(size = 28),

          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),

          legend.box.background = element_rect(),

          legend.box.margin = margin(5, 5, 5, 5),

          legend.position="bottom",

          legend.title = element_text(face = "bold", size = 35),
          
          legend.text = element_text(size = 30))

```


```{r fig.height = 8, fig.width = 12, dpi=300}
library(plyr); packageVersion("plyr")
psF_RA <- transform_sample_counts(psF_SRS, function(x) x/sum(x))
psN_RA <- transform_sample_counts(psN_SRS, function(x) x/sum(x))
```
```{r}
glom_f <- tax_glom(psF_RA, taxrank = 'Taxonomy')

df_f <- psmelt(glom_f)
df_f$Taxonomy <- as.character(df_f$Taxonomy)
means_f <- ddply(df_f, ~Taxonomy, function(x) c(mean=mean(x$Abundance)))
remainder_f <- means_f[means_f$mean <= 0.003,]$Taxonomy 
df_f[df_f$Taxonomy %in% remainder_f,]$Taxonomy <- 'Other species <0.3%' 

print(levels(factor(df_f$Taxonomy)))
```

```{r fig.height = 20, fig.width = 40, dpi=300}
og.nest.taxa.col <- c("#402060","#882E72","#D6C1DE","#54809D","#77b6b1","#85CA95","#33605d","#CAE0AB","#F9ECA0","#f3a833","#de5d3a","#9a4d76","#fa6e79","#ffa2ac","#ffd1d5","#6dead6","#e2dfdf","#767676")


faecal.taxa.col <- c("#8c78a5","#9a4d76","#deceed","#F9ECA0","#f4de58","#85CA95","#33605d","#CAE0AB","#F6C141","#FF0F39","#ffb7c3","#ac2847","#7f5156","#e2dfdf","#b0fff1","#7BAFDE","#4f7190","#9f9f9f")


df_f$New_name <- paste(df_f$Hand_rearing, "_", df_f$Sample_Name)
# df_f$Age <- factor(df_f$Age, level = c("<14 days","15-28 days","29-42 days","43-56 days","57-70 days","71-120 days","200+ days"),
#                           label = c("<14 days","15 - 28 days","29 - 42 days","43 - 56 days","57 - 70 days","71 - 120 days","200+ days"))

faecal_taxa <- ggplot(data=df_f, aes(x=New_name, y=Abundance,  
                                         fill = factor(Taxonomy, 
                                                       c("Acinetobacter bouvetii","Acinetobacter lwoffii","Clostridium sensu stricto 1 baratii",
                                                         "Clostridium sensu stricto 1 perfringens","Clostridium sensu stricto 1 unclassified",
                                                         "Curvibacter lanceolatus","Enterococcus faecalis","Escherichia-Shigella coli",
                                                         "Escherichia-Shigella unclassified","Lactobacillus gasseri","Lactobacillus pontis",
                                                         "Pseudomonas putida","Pseudomonas unclassified","Rahnella1 unclassified",
                                                         "Rhodanobacter unclassified","Streptococcus gallolyticus","Tyzzerella unclassified","Other species <0.3%"))))

faecal_taxa_plotbar <- faecal_taxa + geom_bar(aes(), stat="identity", position="fill", width = 1)  + 
    guides(fill=guide_legend(title="Species", nrow = 6)) + taxaplot_theme + 
    theme(axis.title.y = element_blank(), axis.text.y = element_blank()) + 
    labs(x="K\u101k\u101p\u14d faecal samples") + 
    facet_grid(.~Age, scales = "free_x", space='free') +
    scale_fill_manual(values = faecal.taxa.col)
faecal_taxa_plotbar

faecal_taxa_plotbar.L <- faecal_taxa + geom_bar(aes(), stat="identity", position="fill", width = 1)  + 
    guides(fill=guide_legend(title="Species", nrow = 6)) + taxaplot_theme + 
    labs(y="Relative sequence abundance      ", x = "K\u101k\u101p\u14d faecal samples") + 
    facet_grid(.~Location, scales = "free_x", space='free') +
    scale_fill_manual(values = faecal.taxa.col)
faecal_taxa_plotbar.L
ggsave("faecal_taxa_plotbar_location.png", faecal_taxa_plotbar.L, height = 15, width = 28, dpi = 400)


faecal_taxa_plotbar_age <- ggplot(data=df_f, 
                                  aes(x=Age, y=Abundance,  
                                      fill = factor(Taxonomy, 
                                                  c("Acinetobacter bouvetii","Acinetobacter lwoffii","Clostridium sensu stricto 1 baratii",
                                                    "Clostridium sensu stricto 1 perfringens","Clostridium sensu stricto 1 unclassified",
                                                    "Curvibacter lanceolatus","Enterococcus faecalis","Escherichia-Shigella coli",
                                                    "Escherichia-Shigella unclassified","Lactobacillus gasseri","Lactobacillus pontis",
                                                    "Pseudomonas putida","Pseudomonas unclassified","Rahnella1 unclassified",
                                                    "Rhodanobacter unclassified","Streptococcus gallolyticus","Tyzzerella unclassified",
                                                    "Other species <0.3%")))) + 
    geom_bar(aes(), stat="identity", position="fill", width = 3)  + 
    guides(fill=guide_legend(title="Species", nrow = 6)) + taxaplot_theme +
     theme(strip.text.x = element_blank()) +
    #cale_x_discrete(position = "top") +
    #theme(axis.text.x = element_text(size  = 18)) +
    ggtitle("Faecal samples by k\u101k\u101p\u14d chick age") +
    labs(y="Relative sequence abundance      ", x = "Age groups") +  
    facet_grid(.~Age, scales = "free_x", space='free') +
    scale_fill_manual(values = faecal.taxa.col)
faecal_taxa_plotbar_age
```


```{r fig.height = 20, fig.width = 40, dpi=300}
glom_nest.T <- tax_glom(psN_RA, taxrank = 'Taxonomy')

df_nest.T <- psmelt(glom_nest.T)
df_nest.T$Taxonomy <- as.character(df_nest.T$Taxonomy)
means_nest.T <- ddply(df_nest.T, ~Taxonomy, function(x) c(mean=mean(x$Abundance)))
remainder_nest.T <- means_nest.T[means_nest.T$mean <= 0.005,]$Taxonomy 
df_nest.T[df_nest.T$Taxonomy %in% remainder_nest.T,]$Taxonomy <- 'Other species <0.5%' 

print(levels(factor(df_nest.T$Taxonomy)))
```

```{r fig.cap = "K\u101k\u101p\u14d species others taxonomic plot", fig.height = 15, fig.width = 40, dpi=300}
nest.taxa.col <- c("#402751","#a593a5","#666092","#429058","#8fde5d","#0b5e65","#414c15","#CAE0AB","#F6C141","#c09473","#fbff86","#E8601C","#ffb570","#b0305c","#c878af","#ffd1d5","#6b2643","#ac2847","#ffa2ac","#7f5156","#e2dfdf","#3c9f9c","#253a5e","#b0fff1","#168fea","#1321d3","#b1d8d7","#7BAFDE","#9f9f9f")



taxa_plot_nest <- ggplot(data=df_nest.T, 
                         aes(x=Sample_Name, y=Abundance,  
                             fill = factor(Taxonomy, 
                                           c("Acidipila unclassified","Acidisoma unclassified","Acidocella unclassified",
                                             "Acinetobacter pragensis","Arachidicoccus unclassified",
                                             "Burkholderia-Caballeronia-Paraburkholderia unclassified",
                                             "Dyella unclassified","Escherichia-Shigella coli","Escherichia-Shigella unclassified",
                                             "Flavobacterium unclassified","Granulicella unclassified","Klebsiella oxytoca",
                                             "Mucilaginibacter unclassified","Novosphingobium resinovorum","Novosphingobium rosa",
                                             "Novosphingobium unclassified","Occallatibacter unclassified","Pantoea rwandensis",
                                             "Pseudomonas mohnii","Pseudomonas unclassified","Rahnella1 unclassified",
                                             "Raoultella planticola","Raoultella terrigena","Rhodanobacter unclassified",
                                             "Roseiarcus unclassified","Serratia plymuthica","Serratia unclassified",
                                             "Streptococcus gallolyticus", "Other species <0.5%")))) + 
    geom_bar(aes(), stat="identity", position="fill", width = 1)  + 
    guides(fill=guide_legend(title="Species", nrow = 5)) + taxaplot_theme + 
    theme(axis.title.y = element_blank(),axis.text.y = element_blank()) + 
    labs(x="Nest litter samples") +
    facet_grid(.~Age, scales = "free_x", space='free') +
    scale_fill_manual(values = nest.taxa.col)
taxa_plot_nest


taxa_plot_nest_age <- ggplot(data=df_nest.T, 
                         aes(x=Age, y=Abundance,  
                             fill = factor(Taxonomy, 
                                           c("Acidipila unclassified","Acidisoma unclassified","Acidocella unclassified",
                                             "Acinetobacter pragensis","Arachidicoccus unclassified",
                                             "Burkholderia-Caballeronia-Paraburkholderia unclassified",
                                             "Dyella unclassified","Escherichia-Shigella coli","Escherichia-Shigella unclassified",
                                             "Flavobacterium unclassified","Granulicella unclassified","Klebsiella oxytoca",
                                             "Mucilaginibacter unclassified","Novosphingobium resinovorum","Novosphingobium rosa",
                                             "Novosphingobium unclassified","Occallatibacter unclassified","Pantoea rwandensis",
                                             "Pseudomonas mohnii","Pseudomonas unclassified","Rahnella1 unclassified",
                                             "Raoultella planticola","Raoultella terrigena","Rhodanobacter unclassified",
                                             "Roseiarcus unclassified","Serratia plymuthica","Serratia unclassified",
                                             "Streptococcus gallolyticus", "Other species <0.5%")))) + 
    geom_bar(aes(), stat="identity", position="fill", width = 1.5)  + 
    guides(fill=guide_legend(title="Species", nrow = 5)) + taxaplot_theme + 
    ggtitle("Litter samples by days since first chick") +
    theme(strip.text.x = element_blank()) +
    #scale_x_discrete(position = "top") +
    labs(y="Relative sequence abundance      ") +
    facet_wrap(~Age, scales = "free_x", nrow=1) +
    scale_fill_manual(values = nest.taxa.col)
taxa_plot_nest_age
#ggsave("litter_taxa_plot.png", taxa_plot_nest, height = 20, width = 22, dpi = 400)
```


```{r fig.height = 30, fig.width = 44, dpi=300}
taxa.f = ggarrange(faecal_taxa_plotbar_age, faecal_taxa_plotbar,  
          ncol=2, nrow=1, common.legend = T, legend = "bottom", widths = c(0.25,1))
taxa.f

taxa.n = ggarrange(taxa_plot_nest_age, taxa_plot_nest, 
          ncol=2, nrow=1, common.legend = T, legend = "bottom", widths = c(0.27,1))
taxa.n

taxa.combined = ggarrange(taxa.f, NULL, taxa.n, nrow = 3, labels = c("A","B"), font.label = list(size = 30), heights = c(1, 0.02, 1))
taxa.combined
ggsave("taxa_plots/barplot_taxa_age_combined_May2022revised.png", taxa.combined, height = 30, width = 46, dpi=400, bg = "white")

faecal.l.combined <- ggarrange(taxa.f, NULL, faecal_taxa_plotbar.L, nrow = 3, labels = c("A","B"), font.label = list(size = 30), heights = c(1, 0.02, 1))
faecal.l.combined
ggsave("taxa_plots/faecal_barplot_taxa_age_location_combined_May2022revised.png", faecal.l.combined, height = 30, width = 44, dpi=400, bg = "white")
```


#Alpha Diversity

Use phyloseq's estimate_richness function to get desired diversity estimates.

###Faecal

```{r}
rich_psF <- estimate_richness(psF_SRS, measures = c("InvSimpson","Shannon","Observed"))
richF <- list(rich_psF, sample_data(psF_SRS)$Movement, sample_data(psF_SRS)$Location, sample_data(psF_SRS)$Days, sample_data(psF_SRS)$Aspergillosis,  sample_data(psF_SRS)$Nest_type, sample_data(psF_SRS)$Nest, sample_data(psF_SRS)$Name, sample_data(psF_SRS)$Sample_Name, sample_data(psF_SRS)$Hand_rearing, sample_data(psF_SRS)$Faecal_experiment, sample_data(psF_SRS)$Age, sample_data(psF_SRS)$Date, sample_data(psF_SRS)$SAMPLE.ID)
names(richF) <- c("alpha_diversity", "Movement", "Location", "Days", "Aspergillosis", "Nest_type", "Nest", "Name", "Sample_Name", "Hand_rearing","Faecal_experiment", "Age", "Date","SAMPLE.ID")
richF$New_name <- paste(richF$Hand_rearing, "_", richF$Sample_Name)

rich_dfF <- as.data.frame(richF)
names(rich_dfF)[names(rich_dfF) == "alpha_diversity.Observed"] <- "Observed"
names(rich_dfF)[names(rich_dfF) == "alpha_diversity.InvSimpson"] <- "InvSimpson"


shapiro.test(richF$alpha_diversity$InvSimpson) 
shapiro.test(richF$alpha_diversity$Shannon)
shapiro.test(richF$alpha_diversity$Observed)

#Faecal experiment
rich_psF_UKsubset = estimate_richness(psF_UKsubset, measures = c("InvSimpson","Shannon","Observed"))
richF_UK = list(rich_psF_UKsubset, sample_data(psF_UKsubset)$Faecal_experiment)
names(richF_UK) <- c("alpha_diversity", "Faecal_experiment")

shapiro.test(richF_UK$alpha_diversity$InvSimpson) 
shapiro.test(richF_UK$alpha_diversity$Shannon)
shapiro.test(richF_UK$alpha_diversity$Observed) 

kruskal.test(richF_UK$alpha_diversity$InvSimpson, richF_UK$Faecal_experiment) 
kruskal.test(richF_UK$alpha_diversity$Shannon, richF_UK$Faecal_experiment) 
kruskal.test(richF_UK$alpha_diversity$Observed, richF_UK$Faecal_experiment) 

psF_UK_HRsubset <- subset_samples(psF_UKsubset, Faecal_experiment != "Hand rearing")
rich_psF_UK_HRsubset <- estimate_richness(psF_UK_HRsubset, measures = c("Observed","InvSimpson"))
rich_psF_UK_HR <- list(rich_psF_UK_HRsubset, sample_data(psF_UK_HRsubset)$Faecal_experiment)
names(rich_psF_UK_HR) <- c("alpha_diversity", "Faecal_experiment")

kruskal.test(rich_psF_UK_HR$alpha_diversity$Observed, rich_psF_UK_HR$Faecal_experiment)
kruskal.test(rich_psF_UK_HR$alpha_diversity$InvSimpson, rich_psF_UK_HR$Faecal_experiment)

                                          
#Movement
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Movement) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Movement)
kruskal.test(richF$alpha_diversity$Observed, richF$Movement) 

#Location
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Location) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Location)
kruskal.test(richF$alpha_diversity$Observed, richF$Location)

rich_psF_Loc = estimate_richness(psF_sub.L, measures = c("InvSimpson","Shannon","Observed"))
richF_Location = list(rich_psF_Loc, sample_data(psF_sub.L)$Location, sample_data(psF_sub.L)$Age, sample_data(psF_sub.L)$Days)
names(richF_Location) <- c("alpha_diversity", "Island", "Age", "Days")

kruskal.test(richF_Location$alpha_diversity$InvSimpson, richF_Location$Island) 
kruskal.test(richF_Location$alpha_diversity$Shannon, richF_Location$Island)
kruskal.test(richF_Location$alpha_diversity$Observed, richF_Location$Island) 

#Rearing
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Hand_rearing) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Hand_rearing)
kruskal.test(richF$alpha_diversity$Observed, richF$Hand_rearing)

#Days
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Days) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Days)
kruskal.test(richF$alpha_diversity$Observed, richF$Days)

kruskal.test(richF_Location$alpha_diversity$InvSimpson, richF_Location$Days) 
kruskal.test(richF_Location$alpha_diversity$Shannon, richF_Location$Days)
kruskal.test(richF_Location$alpha_diversity$Observed, richF_Location$Days)

#Age
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Age) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Age)
kruskal.test(richF$alpha_diversity$Observed, richF$Age)

kruskal.test(richF_Location$alpha_diversity$InvSimpson, richF_Location$Age) 
kruskal.test(richF_Location$alpha_diversity$Shannon, richF_Location$Age)
kruskal.test(richF_Location$alpha_diversity$Observed, richF_Location$Age)

#Aspergillosis
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Aspergillosis) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Aspergillosis)
kruskal.test(richF$alpha_diversity$Observed, richF$Aspergillosis)

#Nest type
##No HR or sub-adult
rich_psF_Nest <- estimate_richness(psF_sub_NT, measures = c("InvSimpson","Shannon","Observed"))
richF_Nest <- list(rich_psF_Nest, sample_data(psF_sub_NT)$Nest_type, sample_data(psF_sub_NT)$Nest)
names(richF_Nest) = c("alpha_diversity","Nest_type","Nest")

kruskal.test(richF_Nest$alpha_diversity$InvSimpson, richF_Nest$Nest_type) 
kruskal.test(richF_Nest$alpha_diversity$Shannon, richF_Nest$Nest_type)
kruskal.test(richF_Nest$alpha_diversity$Observed, richF_Nest$Nest_type)

##With HR
rich_psF_Nest_HR <- estimate_richness(psF_sub_NT_HR, measures = c("InvSimpson","Shannon","Observed"))
richF_Nest_HR <- list(rich_psF_Nest_HR, sample_data(psF_sub_NT_HR)$Nest_type, sample_data(psF_sub_NT_HR)$Nest)
names(richF_Nest_HR) = c("alpha_diversity","Nest_type","Nest")

kruskal.test(richF_Nest_HR$alpha_diversity$InvSimpson, richF_Nest_HR$Nest_type) 
kruskal.test(richF_Nest_HR$alpha_diversity$Shannon, richF_Nest_HR$Nest_type)
kruskal.test(richF_Nest_HR$alpha_diversity$Observed, richF_Nest_HR$Nest_type)

#Nest
kruskal.test(richF_Nest_HR$alpha_diversity$InvSimpson, richF_Nest_HR$Nest) 
kruskal.test(richF_Nest_HR$alpha_diversity$Shannon, richF_Nest_HR$Nest)
kruskal.test(richF_Nest_HR$alpha_diversity$Observed, richF_Nest_HR$Nest)

#Chick
kruskal.test(richF$alpha_diversity$InvSimpson, richF$Name) 
kruskal.test(richF$alpha_diversity$Shannon, richF$Name)
kruskal.test(richF$alpha_diversity$Observed, richF$Name)
```

```{r}
dunn.test(richF$alpha_diversity$InvSimpson, richF$Faecal_experiment, method = "bh")
dunn.test(richF$alpha_diversity$Observed, richF$Faecal_experiment, method = "bh") 

dunn.test(richF$alpha_diversity$Observed, richF$Location, method = "bh") 
dunn.test(richF$alpha_diversity$InvSimpson, richF$Location, method = "bh")

dunn.test(richF$alpha_diversity$InvSimpson, richF$Age, method = "bh")
dunn.test(richF$alpha_diversity$Observed, richF$Age, method = "bh") 

dunn.test(richF_Nest_HR$alpha_diversity$InvSimpson, richF_Nest_HR$Nest_type, method = "bh")
dunn.test(richF_Nest_HR$alpha_diversity$Observed, richF_Nest_HR$Nest_type, method = "bh")
dunn.test(richF$alpha_diversity$Observed, richF$Nest_type, method = "bh")

InvSimpson_nest_dunn <- data.frame(dunn.test(richF$alpha_diversity$InvSimpson, richF$Nest, method = "bh")) 
write.table(InvSimpson_nest_dunn, "tables/invsimp_faecal_nest_dunn_comparison.csv")
```

```{r}
p.obs.hr <- c("0.0017","0.46","0.0009","0.0048","0.00000009","0.22","0.0006","0.00005","0.15")
p.obs <- c("0.25","0.075","0.007","0.0000007","0.68","0.0008")

p.invsimp.hr <- c("0.16","0.66","0.018","0.06","0.04","0.28","0.13","0.0000006","0.022")
p.invsimp <- c("0.13","0.011","0.10","0.21","0.14","0.000007")

p.adjust(p.obs.hr, method = "BH")
p.adjust(p.obs, method = "BH")
p.adjust(p.invsimp.hr, method = "BH")
p.adjust(p.invsimp, method = "BH")
```

####LMMs
```{r}
library(lme4); packageVersion("lme4")

richF.glmm <- rich_dfF

richF.glmm.norear <- richF.glmm[-which(richF.glmm$Location == "Hand rearing"),]
richF.glmm.FE <- richF.glmm[-which(richF.glmm$Faecal_experiment == "Unknown" | richF.glmm$Faecal_experiment == "Hand rearing"),]
richF.glmm.mv <- richF.glmm[-which(richF.glmm$Nest_type == "Hand rearing"| richF.glmm$Nest_type == "Sub-adult samples"),]

#Observed richness

###Faecal experiment
obs_model_fe_null <- glmer(Observed ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.FE, family = poisson(link=log))
obs_model_fe <- glmer(Observed ~ Faecal_experiment + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.FE, family = poisson(link=log)) 
summary(obs_model_fe) 
anova(obs_model_fe, obs_model_fe_null)
confint(obs_model_fe)

###Location
obs_model_lc_null <- glmer(Observed ~ (1|Name) + (1|Nest) + (1|Days), data = richF.glmm.norear, family = poisson(link=log))
obs_model_lc <- glmer(Observed ~ Location + (1|Name) + (1|Nest) + (1|Days), data = richF.glmm.norear, family = poisson(link=log)) 
summary(obs_model_lc) 
anova(obs_model_lc,obs_model_lc_null)
confint(obs_model_lc)

###Movement
obs_model_mv_null <- glmer(Observed ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv, family = poisson(link=log))
obs_model_mv <- glmer(Observed ~ Movement + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv, family = poisson(link=log)) 
summary(obs_model_mv) 
anova(obs_model_mv, obs_model_mv_null)
confint(obs_model_mv)

###Aspergillosis
obs_model_asp_null <- glmer(Observed ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm, family = poisson(link=log))
obs_model_asp <- glmer(Observed ~ Aspergillosis + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm, family = poisson(link=log)) 
summary(obs_model_asp)
anova(obs_model_asp, obs_model_asp_null)
confint(obs_model_asp)

###Days
obs_model_days_null <- lmer(Observed ~ (1|Location:Nest) + (1|Name), data = richF.glmm) 
obs_model_days <- lmer(Observed ~ Days + (1|Location:Nest) + (1|Name), data = richF.glmm) 
summary(obs_model_days) 
anova(obs_model_days, obs_model_days_null)
confint(obs_model_days)

###Age
obs_model_age_null <- lmer(Observed ~ (1|Location:Nest) + (1|Name), data = richF.glmm) 
obs_model_age <- lmer(Observed ~ Age + (1|Location:Nest) + (1|Name), data = richF.glmm) 
summary(obs_model_age) 
anova(obs_model_age, obs_model_age_null)
confint(obs_model_age)

###Hand rearing
obs_model_hr_null <- glmer(Observed ~ (1|Name) + (1|Days), data = richF.glmm, family = poisson(link=log)) 
obs_model_hr <- glmer(Observed ~ Hand_rearing + (1|Name) + (1|Days), data = richF.glmm, family = poisson(link=log)) 
summary(obs_model_hr) 
anova(obs_model_hr, obs_model_hr_null)
confint(obs_model_hr)

###Nest type
obs_model_nt <- glmer(Observed ~ Nest_type + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv, family = poisson(link=log)) 
obs_model_nt_null <- glmer(Observed ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv, family = poisson(link=log))
summary(obs_model_nt) 
anova(obs_model_nt, obs_model_nt_null)
confint(obs_model_nt)

###Hand rearing + Age
obs_model_hr_days_null <- glmer(Observed ~ (1|Name), data = richF.glmm, family = poisson(link=log)) 
obs_model_hr_days <- glmer(Observed ~ Hand_rearing*Days + (1|Name), data = richF.glmm, family = poisson(link=log)) 
summary(obs_model_hr_days) 
anova(obs_model_hr_days, obs_model_hr_days_null)
confint(obs_model_hr_days)




#Inverse Simpson
richF.glmm[,3] <- scale(richF.glmm[,3])
richF.glmm.norear[,3] <- scale(richF.glmm.norear[,3])
richF.glmm.FE[,3] <- scale(richF.glmm.FE[,3])
richF.glmm.mv[,3] <- scale(richF.glmm.mv[,3])

###Faecal experiment
invsimp_model_fe_null <- lmer(InvSimpson ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.FE)
invsimp_model_fe <- lmer(InvSimpson ~ Faecal_experiment + (1|Name) +  (1|Location:Nest) + (1|Days), data = richF.glmm.FE) 
summary(invsimp_model_fe) 
anova(invsimp_model_fe, invsimp_model_fe_null)
confint(invsimp_model_fe)

###Location
invsimp_model_lc_null <- lmer(InvSimpson ~ (1|Name) + (1|Nest) + (1|Days), data = richF.glmm.norear) 
invsimp_model_lc <- lmer(InvSimpson ~ Location + (1|Name) + (1|Nest) + (1|Days), data = richF.glmm.norear) 
summary(invsimp_model_lc) 
anova(invsimp_model_lc, invsimp_model_lc_null)
confint(invsimp_model_lc)

###Movement
invsimp_model_mv_null <- lmer(InvSimpson ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv) 
invsimp_model_mv <- lmer(InvSimpson ~ Movement + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv) 
summary(invsimp_model_mv) 
anova(invsimp_model_mv,invsimp_model_mv_null)
confint(invsimp_model_mv)

###Aspergillosis
invsimp_model_asp_null <- lmer(InvSimpson ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm) 
invsimp_model_asp <- lmer(InvSimpson ~ Aspergillosis + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm) 
summary(invsimp_model_asp) 
anova(invsimp_model_asp, invsimp_model_asp_null)
confint(invsimp_model_asp)

###Days
invsimp_model_days_null <- lmer(InvSimpson ~ (1|Location:Nest) + (1|Name), data = richF.glmm) 
invsimp_model_days <- lmer(InvSimpson ~ Days + (1|Location:Nest) + (1|Name), data = richF.glmm) 
summary(invsimp_model_days) 
anova(invsimp_model_days, invsimp_model_days_null)
confint(invsimp_model_days)

###Age
invsimp_model_age_null <- lmer(InvSimpson ~ (1|Location:Nest) + (1|Name), data = richF.glmm) 
invsimp_model_age <- lmer(InvSimpson ~ Age + (1|Location:Nest) + (1|Name), data = richF.glmm) 
summary(invsimp_model_age) 
anova(invsimp_model_age, invsimp_model_age_null)
confint(invsimp_model_age)

###Hand rearing
invsimp_model_hr_null <- lmer(InvSimpson ~ (1|Name) + (1|Days), data = richF.glmm) 
invsimp_model_hr <- lmer(InvSimpson ~ Hand_rearing + (1|Name) + (1|Days), data = richF.glmm) 
summary(invsimp_model_hr)
anova(invsimp_model_hr, invsimp_model_hr_null)
confint(invsimp_model_hr)

###Nest type
invsimp_model_nt_null <- lmer(InvSimpson ~ (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv) 
invsimp_model_nt <- lmer(InvSimpson ~ Nest_type + (1|Name) + (1|Location:Nest) + (1|Days), data = richF.glmm.mv) 
summary(invsimp_model_nt) 
anova(invsimp_model_nt, invsimp_model_nt_null)
confint(invsimp_model_nt)

###Hand rearing + Age
invsimp_model_hr_days_null <- lmer(InvSimpson ~ (1|Name), data = richF.glmm) 
invsimp_model_hr_days <- lmer(InvSimpson ~ Hand_rearing*Days + (1|Name), data = richF.glmm) 
summary(invsimp_model_hr_days) 
anova(invsimp_model_hr_days, invsimp_model_hr_days_null)
confint(invsimp_model_hr_days)
```


Create an alpha diversity plot.

```{r fig.height = 15, fig.width = 20, dpi=300}
simpson.F.location <- data.frame(start=c("Hand rearing","Hand rearing","Pukenui"),
                              end=c("Pukenui","Whenua Hou","Whenua Hou"),
                              y=c(1.5,2,1.7),
                              label=c("0.42","0.05","0.01*"))

observed.F.pooR <- data.frame(start=c("Faeces in","Faeces removed","Hand rearing"), 
                            end=c("Hand rearing","Hand rearing","Mixed"),
                              y=c(240,220,200),
                              label=c("0.01**","0.0004***","0.08"))

observed.F.location <- data.frame(start=c("Hand rearing","Hand rearing","Pukenui"),
                              end=c("Pukenui","Whenua Hou","Whenua Hou"),
                              y=c(240,270,220),
                              label=c("0.0003***","0.007**","0.04*"))

observed.F.nest_type <- data.frame(start=c("A-frame","Hand rearing","Hand rearing"), #"A-frame","Hole","Sub-adult samples"),
                              end=c("Hand rearing","Hole","Tree"),#"Sub-adult samples","Sub-adult samples","Tree"),
                              y=c(220,200,240),#350,310,190),
                              label=c("0.0008***","0.0004***","0.001**"))#"0.00001****","0.00001****","0.00001****"))


observed.age.bar.F <- data.frame(start=c("<14 days","<14 days","<14 days","15 - 28 days","15 - 28 days","15 - 28 days","29 - 42 days",
                                         "29 - 42 days","29 - 42 days","43 - 56 days","57 - 70 days","57 - 70 days"),
                              end=c("29 - 42 days","71 - 120 days","200+ days","43 - 56 days","71 - 120 days","200+ days",
                                    "43 - 56 days","71 - 120 days","200+ days","200+ days", "71 - 120 days","200+ days"),
                              y=c(260,220,320,240,200,300,160,180,280,260,160,240),
                              label=c("*","**","**","*","***","***","**","***","***","*","*","**"))



richF_UK.df <- as.data.frame(richF_UK)
names(richF_UK.df)[names(richF_UK.df) == "alpha_diversity.Observed"] <- "Observed"
names(richF_UK.df)[names(richF_UK.df) == "alpha_diversity.InvSimpson"] <- "InvSimpson"
richF_UK.df$Faecal_experiment <- factor(richF_UK.df$Faecal_experiment, levels = c("Faeces in","Faeces removed","Hand rearing","Mixed"))

richF_Nest_HR.df <- as.data.frame(richF_Nest_HR)
names(richF_Nest_HR.df)[names(richF_Nest_HR.df) == "alpha_diversity.Observed"] <- "Observed"
names(richF_Nest_HR.df)[names(richF_Nest_HR.df) == "alpha_diversity.InvSimpson"] <- "InvSimpson"

myadptheme <- theme_ipsum() + theme(plot.title = element_text(size = 26),
  
          plot.subtitle = element_text(size = 24),
          
          axis.text.x = element_blank(),

          axis.title.x = element_text(size=35),

          axis.ticks.x = element_blank(),

          axis.text.y=element_text(size=25),

          axis.title.y=element_text(size=35),

          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_line(color="black",size=1.0,linetype=1),

          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),

          legend.box.background = element_rect(),

          legend.box.margin = margin(5, 5, 5, 5),

          legend.position="bottom",

          legend.title = element_text(face = "bold", size = 35),
          
          legend.text = element_text(size = 30))

```


```{r fig.height=10, fig.width=44}
kakapo_age_colours <- c("#4b5e1e", "#7D9D33", "#DCC949", "#BCA888","#706451", "#CD8862", "#775B24")

obs_bar <- ggplot(data=rich_dfF, aes(x=New_name,y=Observed, fill = Age)) + 
  
  geom_bar(aes(), stat="identity", position="stack", width = 1)  +
  
  theme_ipsum() + theme(axis.text.x = element_blank(),

          axis.ticks.x = element_blank(),

          axis.text.y=element_blank(),

          axis.title.y=element_blank(),
          
          axis.title.x = element_text(size = 35),
          
          strip.text.x = element_blank(),
          
          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),
          
          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_blank(),
          
          legend.position = "none") +
  
  labs(x="\nK\u101k\u101p\u14d faecal samples") + 
  
  scale_y_continuous(limits = c(0,340), expand = c(0, 0)) +
  
  facet_grid(~Age, scales = "free_x", space = "free")  + 
  
  scale_fill_manual(values = kakapo_age_colours)

obs_bar
```

```{r fig.height=15, fig.width=15}
obs.Age <- ggplot(rich_dfF, aes(x=Age, y=Observed))
obs.Age.plot <- obs.Age + geom_boxplot(size=1.0, aes(fill=Age)) + 
    myadptheme + theme(plot.title = element_text(size = 35)) +
    scale_fill_manual(values = kakapo_age_colours) + 
    labs(y = "Observed species", x = "\nAge groups") +
    ggtitle("Kruskal-Wallis and glmm p < 0.001***") +
    geom_signif(data=observed.age.bar.F,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 8,colour = "blue") 

obs.Age.plot
```

```{r fig.height=10, fig.width=44}
library(cowplot); packageVersion("cowplot")
obs.faecal = ggarrange(obs.Age.plot, obs_bar, labels = c("B"), font.label = list(size = 30),
          ncol=2, nrow=1, legend = "none", widths = c(0.25,1))
obs.faecal
```

```{r fig.height=10, fig.width=32}
rich_dfF$InvSimpsonlog <- log10(rich_dfF$InvSimpson)

invsimpson_bar <- ggplot(data=rich_dfF, aes(x=New_name,y=InvSimpsonlog, fill = Age)) + 
  
  geom_bar(aes(), stat="identity", position="stack", width = 1)  + 
  
  theme_ipsum() + theme(axis.text.x = element_blank(),

          axis.ticks.x = element_blank(),

          axis.text.y=element_blank(),

          axis.title.y=element_blank(),
          
          axis.title.x = element_text(size = 35),
          
          strip.text.x = element_blank(),
          
          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),
          
          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_blank(),
          
          legend.position = "bottom", 
          
          legend.title = element_text(face = "bold", size = 38),
          
          legend.text = element_text(size = 35),
          
          legend.box.background = element_rect(),

          legend.box.margin = margin(5, 5, 5, 5)) +
  
  labs(x = "\nK\u101k\u101p\u14d faecal samples") +
  
  guides(fill = guide_legend(nrow = 1, override.aes=list(shape=15, size = 15))) +
  
  scale_y_continuous(expand = c(0, 0), limits = c(0, 2.3)) +
  
  facet_grid(~Age, scales = "free_x", space = "free") + 
  
  scale_fill_manual(values = kakapo_age_colours)

invsimpson_bar

invsimpson_bar.NL <- invsimpson_bar + theme(legend.position = "none")

faecal.adp.legend <- get_legend(invsimpson_bar)
```

```{r fig.height=10, fig.width=10}
invsimp.Age <- ggplot(rich_dfF, aes(x=Age, y=InvSimpsonlog))
invsimp.Age.plot <- invsimp.Age + geom_boxplot(size=1.0, aes(fill=Age)) + 
    myadptheme + theme(plot.title = element_text(size = 35)) +
    scale_fill_manual(values = kakapo_age_colours) + 
    labs(y = "Inverse Simpson diversity [log10]", x = "\nAge groups") +
    ggtitle("Kruskal-Wallis and lmm p = 0.09") 

invsimp.Age.plot
```

```{r fig.height=10, fig.width=42}
invsimp.faecal = ggarrange(invsimp.Age.plot, invsimpson_bar.NL, labels = c("C"), font.label = list(size = 30),
          ncol=2, nrow=1, legend = "none", widths = c(0.25,1))
invsimp.faecal
```

```{r fig.height = 40, fig.width = 42, dpi=300}
faecal.taxa.adp.combined = ggarrange(taxa.f, NULL, obs.faecal,invsimp.faecal,faecal.adp.legend, nrow = 5, labels = c("A"), font.label = list(size = 30), heights = c(1, 0.02, 0.7, 0.7, 0.2))
faecal.taxa.adp.combined
ggsave("taxa_plots/faecal_age_taxaplot_adp_revisedAUG2022.png", faecal.taxa.adp.combined, height = 30, width = 44, dpi = 400, bg = "white")
```

```{r fig.height = 10, fig.width = 15, dpi=300}
nest.f.col <- c("#882E72","#B178A6","#D6C1DE","#54809D","#1965B0","#7BAFDE","#4EB265","#CAE0AB","#77b6b1","#33605d","#F7EE55","#F6C141","#e98537","#FF99AB","#ECD3D8","#FF0F39","#ac2847","#E2DDDE","#767676")

##By nest

obs.nest <- ggplot(richF_Nest_HR.df, aes(x=Nest, y=Observed))  
obs.nest.plot <- obs.nest + geom_boxplot(size=1.0, aes(fill=Nest)) + #,outlier.shape = NA) 
    myadptheme + theme(axis.title.x = element_text(size = 24), 
                                                 axis.title.y = element_text(size = 24), 
                                                 legend.text = element_text(size = 22), 
                                                 legend.title = element_text(size = 24)) +
    labs(y = "Observed species",  x = "Nest") +
    ggtitle("Observed", subtitle = "Kruskal-Wallis p < 0.001") +
    scale_fill_manual(values = col.42) #+
obs.nest.plot


invsimp.nest <- ggplot(richF_Nest_HR.df, aes(x=Nest, y=InvSimpson))  
invsimp.nest.plot <- invsimp.nest + geom_boxplot(size=1.0, aes(fill=Nest), outlier.shape = NA) + myadptheme + 
    scale_y_continuous(limits = c(1,45)) + theme(axis.title.x = element_text(size = 24), 
                                                 axis.title.y = element_text(size = 24), 
                                                 legend.text = element_text(size = 22), 
                                                 legend.title = element_text(size = 24)) +
    labs(y = "Inverse Simpson diversity", x = "\nNest") + 
    ggtitle("Inverse Simpson",subtitle = "Kruskal-Wallis p < 0.001") +
    scale_fill_manual(values = col.42)
invsimp.nest.plot
```

```{r fig.height = 21, fig.width = 15, dpi=300}
nest.f = ggarrange(obs.nest.plot,invsimp.nest.plot, labels = c("A","B"), font.label = list(size = 30), 
          ncol=1, nrow=2, common.legend = TRUE, legend="bottom")
nest.f.title = annotate_figure(nest.f, top = text_grob("Faecal samples by nest of residence", face = "bold", family = "sans", size = 30))
nest.f.title
ggsave("alpha_div/faecal_nest_adp.png",nest.f.title, height = 21, width = 15, dpi = 400, bg = "white")
```

```{r}
myadptheme.edit <- theme_ipsum() + theme(plot.title = element_text(size = 28),
                                         
          plot.subtitle = element_text(size = 25),
  
          axis.text.x = element_blank(),

          axis.title.x = element_text(size=20),

          axis.ticks.x = element_blank(),

          axis.text.y=element_text(size=16),

          axis.title.y=element_text(size=20),

          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_line(color="black",size=1.0,linetype=1),

          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),

          legend.box.background = element_rect(),

          legend.box.margin = margin(5,5,5,5),

          legend.position="bottom",

          legend.title = element_text(face = "bold", size = 24),
          
          legend.text = element_text(size = 20))
```

```{r fig.height = 10, fig.width = 13, dpi=300}
obs.pooR <- ggplot(richF_UK.df, aes(x=Faecal_experiment, y=Observed))
obs.pooR.plot <- obs.pooR + geom_boxplot(size=1.0, aes(fill=Faecal_experiment)) + myadptheme.edit + 
    labs(y = "Observed species", x = "Faecal experiment groups") +
    scale_fill_manual(values= get_pal("Kakapo"), name = "Observed species") + 
    ggtitle("Faecal samples", subtitle = "Kruskal-Wallis p = 0.003") +
    geom_signif(data=observed.F.pooR,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 6) 
obs.pooR.plot
```


```{r fig.height = 10, fig.width = 13, dpi=300}
##Location
obs.location <- ggplot(rich_dfF, aes(x=Location, y=Observed))
obs.location.plot <- obs.location + geom_boxplot(size=1.0, aes(fill=Location)) + myadptheme.edit + 
    theme(plot.margin = unit(c(2,0.5,0.5,0.5), "cm"), axis.title.y = element_text(size = 35), 
          axis.title.x = element_blank(), axis.text.x = element_text(size = 35), legend.position = "none") +
    labs(y = "Observed species", x = "Location") +
    scale_fill_manual(values= c("#DCC949","#4B5F6C", "#A8B9CB")) + 
    ggtitle("Observed", subtitle = "Kruskal-Wallis p = 0.002** and glmm p <0.001***") +
    geom_signif(data=observed.F.location,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 6) 
obs.location.plot

# , legend.title = element_text(face = "bold", size = 35), 
#           legend.text = element_text(size = 30), plot.title = element_text(size = 38), 
#           plot.subtitle = element_text(size = 35)

invsimp.location <- ggplot(rich_dfF, aes(x=Location, y=InvSimpsonlog))
invsimp.location.plot <- invsimp.location + geom_boxplot(size=1.0, aes(fill=Location)) + myadptheme.edit +
    theme(plot.margin = unit(c(2,0.5,0.5,0.5), "cm"), axis.title.y = element_text(size = 35), 
          axis.title.x = element_blank(), axis.text.x = element_text(size = 35), legend.position = "none") +
    labs(y = "Inverse Simpson diversity [log10]", x = "Location") +
    scale_fill_manual(values= c("#DCC949","#4B5F6C", "#A8B9CB")) + 
    ggtitle("Inverse Simpson", subtitle = "Kruskal-Wallis p = 0.07 and lmm p = 0.39") +
    geom_signif(data=simpson.F.location,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 6) 
invsimp.location.plot
```

```{r fig.height = 15, fig.width = 44, dpi=300}
location.f = ggarrange(obs.location.plot, NULL, invsimp.location.plot, labels = c("A","","B"), font.label = list(size = 30),
          ncol=3, nrow=1, common.legend = F, widths = c(1,0.25,1))
#legend="bottom", 
location.f.title = annotate_figure(location.f, top = text_grob("Faecal samples by location\n", face = "bold", family = "sans", size = 38))
location.f.title
```


```{r fig.height = 10, fig.width = 13, dpi=300}
nt.col <- c("#c9cca1", "#caa05a", "#ae6a47", "#8b4049", "#515262", "#63787d", "#8ea091")
##Nest type
obs.nest_type <- ggplot(richF_Nest_HR.df, aes(x=Nest_type, y=Observed))
obs.nest_type.plot <- obs.nest_type + geom_boxplot(size=1.0, aes(fill=Nest_type)) + myadptheme.edit + 
    theme(plot.margin = unit(c(2,0.5,0.5,0.5), "cm")) +
    labs(y = "Observed species", x = "Nest type") +
    scale_fill_manual(values= nt.col, name = "Nest type") + 
    ggtitle("Observed", subtitle = "Kruskal-Wallis p = 0.002") +
    geom_signif(data=observed.F.nest_type,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 6) 
obs.nest_type.plot

richF_Nest_HR.df$InvSimpsonlog = log10(richF_Nest_HR.df$InvSimpson)

invsimp.nest_type <- ggplot(richF_Nest_HR.df, aes(x=Nest_type, y=InvSimpsonlog))
invsimp.nest_type.plot <- invsimp.nest_type + geom_boxplot(size=1.0, aes(fill=Nest_type)) + myadptheme.edit +
    theme(plot.margin = unit(c(2,0.5,0.5,0.5), "cm")) +
    #scale_y_log10() +
    labs(y = "Inverse Simpson diversity [log10]", x = "Nest type") +
    scale_fill_manual(values= nt.col, name = "Nest type") + 
    ggtitle("Inverse Simpson", subtitle = "Kruskal-Wallis p = 0.20")
invsimp.nest_type.plot
```

```{r fig.height = 10, fig.width = 15, dpi=300}
nest.type.f = ggarrange(obs.nest_type.plot, invsimp.nest_type.plot, labels = c("A","B"), font.label = list(size = 30),
                        ncol=2, nrow=1, common.legend = TRUE, legend="bottom")
nest.type.f.title = annotate_figure(nest.type.f, top = text_grob("Faecal samples by nest type\n", face = "bold", family = "sans", size = 30))
nest.type.f.title
```

```{r fig.height = 25, fig.width = 26, dpi=300}
location.taxaplot.adp.combined <- ggarrange(location.f.title,NULL, faecal_taxa_plotbar.L, labels = c("","","C"), font.label = list(size = 30), 
                                     nrow = 3, heights = c(0.9,0.09,1)) + theme(plot.margin = margin(1,0.5,0.5,0.5, "cm"))
location.taxaplot.adp.combined
ggsave("location_taxaplot_adp_combined_nolegend.png",location.taxaplot.adp.combined, width = 26, height = 25, dpi = 400)
```


###Litter

```{r}
rich_psN <- estimate_richness(psN_SRS, measures = c("InvSimpson","Shannon","Observed"))
richN <- list(rich_psN, sample_data(psN_SRS)$Faecal_experiment, sample_data(psN_SRS)$Movement, sample_data(psN_SRS)$Location, sample_data(psN_SRS)$Age,  sample_data(psN_SRS)$Days, sample_data(psN_SRS)$Aspergillosis, sample_data(psN_SRS)$Nest_type, sample_data(psN_SRS)$Nest, sample_data(psN_SRS)$Sample_Name, sample_data(psN_SRS)$Name)
names(richN) <- c("alpha_diversity", "Faecal_experiment", "Movement", "Location", "Age", "Days", "Aspergillosis", "Nest_type", "Nest", "Sample_Name", "Name")

rich_dfN <- as.data.frame(richN)
names(rich_dfN)[names(rich_dfN) == "alpha_diversity.InvSimpson"] <- "InvSimpson"
names(rich_dfN)[names(rich_dfN) == "alpha_diversity.Observed"] <- "Observed"

shapiro.test(richN$alpha_diversity$InvSimpson) 
shapiro.test(richN$alpha_diversity$Shannon) 
shapiro.test(richN$alpha_diversity$Observed) 

#Faecal experiment
rich_psN_UKsubset <- estimate_richness(psN_UKsubset, measures = c("Observed","InvSimpson"))
richN_UK <- list(rich_psN_UKsubset, sample_data(psN_UKsubset)$Faecal_experiment)
names(richN_UK) <- c("alpha_diversity", "Faecal_experiment")

wilcox.test(richN_UK$alpha_diversity$Observed ~ richN_UK$Faecal_experiment)
wilcox.test(richN_UK$alpha_diversity$InvSimpson ~ richN_UK$Faecal_experiment) 

#Movement
kruskal.test(richN$alpha_diversity$InvSimpson, richN$Movement) 
kruskal.test(richN$alpha_diversity$Observed, richN$Movement)

#Location
kruskal.test(richN$alpha_diversity$InvSimpson, richN$Location) 
kruskal.test(richN$alpha_diversity$Observed, richN$Location)

wilcox.test(richN$alpha_diversity$Observed ~ richN$Location) 
wilcox.test(richN$alpha_diversity$InvSimpson ~ richN$Location) 

#Days since first chick
kruskal.test(richN$alpha_diversity$InvSimpson, richN$Days) 
kruskal.test(richN$alpha_diversity$Observed, richN$Days)

kruskal.test(richN$alpha_diversity$InvSimpson, richN$Age) 
kruskal.test(richN$alpha_diversity$Observed, richN$Age)

#Aspergillosis
kruskal.test(richN$alpha_diversity$InvSimpson, richN$Aspergillosis)
kruskal.test(richN$alpha_diversity$Observed, richN$Aspergillosis)

#Nest_type
kruskal.test(richN$alpha_diversity$InvSimpson, richN$Nest_type) 
kruskal.test(richN$alpha_diversity$Observed, richN$Nest_type)

#Nest
kruskal.test(richN$alpha_diversity$InvSimpson, richN$Nest) 
kruskal.test(richN$alpha_diversity$Observed, richN$Nest)

```

```{r}
dunn.test(richN$alpha_diversity$Observed, richN$Age, method = "bh") 
```

```{r}
l.p.obs <- c("0.11","0.17","0.79","0.22","0.0005","0.39","0.54","0.33")
l.p.invsimp <- c("0.9","0.03","0.36","0.54","0.03","0.05","0.74","0.39")

p.adjust(l.p.obs, method = "BH")
p.adjust(l.p.invsimp, method = "BH")
```

####LMMs

```{r}
richN.glmm <- rich_dfN
richN.glmm.FE <- richN.glmm[-which(richN.glmm$Faecal_experiment == "Unknown"),]

# hist(richN.glmm$Observed)
# hist(richN.glmm$InvSimpson)


#Observed richness

###Faecal experiment
N_obs_model_fe_null <- glmer(Observed ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm.FE, family = poisson(link=log))
N_obs_model_fe <- glmer(Observed ~ Faecal_experiment + (1|Name) + (1|Location) + (1|Days), data = richN.glmm.FE, family = poisson(link=log)) 
summary(N_obs_model_fe) 
anova(N_obs_model_fe, N_obs_model_fe_null)
N.mod.fe <- profile(N_obs_model_fe, devtol = 1e-7)
confint(N.mod.fe)

###Location
N_obs_model_lc_null <- glmer(Observed ~ (1|Name) + (1|Days), data = richN.glmm, family = poisson(link=log))
N_obs_model_lc <- glmer(Observed ~ Location + (1|Name) + (1|Days), data = richN.glmm, family = poisson(link=log)) 
summary(N_obs_model_lc) 
anova(N_obs_model_lc,N_obs_model_lc_null)
confint(N_obs_model_lc)

###Movement
N_obs_model_mv_null <- glmer(Observed ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm, family = poisson(link=log))
N_obs_model_mv <- glmer(Observed ~ Movement + (1|Name) + (1|Location) + (1|Days), data = richN.glmm, family = poisson(link=log)) 
summary(N_obs_model_mv) 
anova(N_obs_model_mv, N_obs_model_mv_null)
N.mod.mv <- profile(N_obs_model_mv, devtol = 1e-6)
confint(N.mod.mv)

###Aspergillosis
N_obs_model_asp_null <- glmer(Observed ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm, family = poisson(link=log))
N_obs_model_asp <- glmer(Observed ~ Aspergillosis + (1|Name) + (1|Location) + (1|Days), data = richN.glmm, family = poisson(link=log)) 
summary(N_obs_model_asp)
anova(N_obs_model_asp, N_obs_model_asp_null)
confint(N_obs_model_asp)

###Days
N_obs_model_days_null <- lmer(Observed ~ (1|Location) + (1|Name), data = richN.glmm) 
N_obs_model_days <- lmer(Observed ~ Days + (1|Location) + (1|Name), data = richN.glmm) 
summary(N_obs_model_days) 
anova(N_obs_model_days, N_obs_model_days_null)
confint(N_obs_model_days)

###Age
N_obs_model_age_null <- lmer(Observed ~ (1|Location) + (1|Name), data = richN.glmm) 
N_obs_model_age <- lmer(Observed ~ Age + (1|Location) + (1|Name), data = richN.glmm) 
summary(N_obs_model_age) 
anova(N_obs_model_age, N_obs_model_age_null)
confint(N_obs_model_age)

###Nest type
N_obs_model_nt <- glmer(Observed ~ Nest_type + (1|Name) + (1|Location) + (1|Days), data = richN.glmm, family = poisson(link=log)) 
N_obs_model_nt_null <- glmer(Observed ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm, family = poisson(link=log))
summary(N_obs_model_nt) 
anova(N_obs_model_nt, N_obs_model_nt_null)
N.mod.nt <- profile(N_obs_model_nt, devtol = 1e-6)
confint(N.mod.nt)


#Inverse Simpson
richN.glmm[,3] <- scale(richN.glmm[,3])
richN.glmm.FE[,3] <- scale(richN.glmm.FE[,3])

###Faecal experiment
N_invsimp_model_fe_null <- lmer(InvSimpson ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm)
N_invsimp_model_fe <- lmer(InvSimpson ~ Faecal_experiment + (1|Name) +  (1|Location) + (1|Days), data = richN.glmm) 
summary(N_invsimp_model_fe) 
anova(N_invsimp_model_fe, N_invsimp_model_fe_null)
confint(N_invsimp_model_fe)

###Location
N_invsimp_model_lc_null <- lmer(InvSimpson ~ (1|Name) + (1|Days), data = richN.glmm) 
N_invsimp_model_lc <- lmer(InvSimpson ~ Location + (1|Name) + (1|Days), data = richN.glmm) 
summary(N_invsimp_model_lc) 
anova(N_invsimp_model_lc, N_invsimp_model_lc_null)
confint(N_invsimp_model_lc)

###Movement
N_invsimp_model_mv_null <- lmer(InvSimpson ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm) 
N_invsimp_model_mv <- lmer(InvSimpson ~ Movement + (1|Name) + (1|Location) + (1|Days), data = richN.glmm) 
summary(N_invsimp_model_mv) 
anova(N_invsimp_model_mv,N_invsimp_model_mv_null)
confint(N_invsimp_model_mv)

###Aspergillosis
N_invsimp_model_asp_null <- lmer(InvSimpson ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm) 
N_invsimp_model_asp <- lmer(InvSimpson ~ Aspergillosis + (1|Name) + (1|Location) + (1|Days), data = richN.glmm) 
summary(N_invsimp_model_asp) 
anova(N_invsimp_model_asp, N_invsimp_model_asp_null)
confint(N_invsimp_model_asp)

###Days
N_invsimp_model_days_null <- lmer(InvSimpson ~ (1|Location) + (1|Name), data = richN.glmm) 
N_invsimp_model_days <- lmer(InvSimpson ~ Days + (1|Location) + (1|Name), data = richN.glmm) 
summary(N_invsimp_model_days) 
anova(N_invsimp_model_days, N_invsimp_model_days_null)
confint(N_invsimp_model_days)

###Age
N_invsimp_model_age_null <- lmer(InvSimpson ~ (1|Location) + (1|Name), data = richN.glmm) 
N_invsimp_model_age <- lmer(InvSimpson ~ Age + (1|Location) + (1|Name), data = richN.glmm) 
summary(N_invsimp_model_age) 
anova(N_invsimp_model_age, N_invsimp_model_age_null)
confint(N_invsimp_model_age)

###Nest type
N_invsimp_model_nt_null <- lmer(InvSimpson ~ (1|Name) + (1|Location) + (1|Days), data = richN.glmm) 
N_invsimp_model_nt <- lmer(InvSimpson ~ Nest_type + (1|Name) + (1|Location) + (1|Days), data = richN.glmm) 
summary(N_invsimp_model_nt) 
anova(N_invsimp_model_nt, N_invsimp_model_nt_null)
confint(N_invsimp_model_nt)
```

```{r}
dunn.test(richN$alpha_diversity$InvSimpson, richN$Age, method = "bh") 
```

Create an alpha diversity plot.

```{r fig.height = 15, fig.width = 20, dpi=300}
obs.N.Age.bar <- data.frame(start=c("<14 days","<14 days","<14 days"),
                              end=c("15 - 28 days","29 - 42 days","43 - 56 days"),
                              y=c(540,580,620),
                              label=c("*","**","**"))

simpson.N.Age.bar <- data.frame(start=c("<14 days","<14 days"),
                              end=c("15 - 28 days","29 - 42 days"),
                              y=c(160,180),
                              label=c("*","*"))


richN_UK.df <- as.data.frame(richN_UK)
names(richN_UK.df)[names(richN_UK.df) == "alpha_diversity.InvSimpson"] <- "InvSimpson"
names(richN_UK.df)[names(richN_UK.df) == "alpha_diversity.Observed"] <- "Observed"

```


```{r fig.height=10, fig.width=32}
kakapo_age_colours <- c("#4b5e1e", "#7D9D33", "#DCC949", "#BCA888","#706451", "#CD8862", "#775B24")


obs_bar.n <- ggplot(data=rich_dfN, aes(x=Sample_Name,y=Observed, fill = Age)) + 
  
  geom_bar(aes(), stat="identity", position="stack", width = 1)  + 
  
  theme_ipsum() + theme(axis.text.x = element_blank(),

          axis.ticks.x = element_blank(),

          axis.text.y=element_blank(),

          axis.title.y=element_blank(),
          
          axis.title.x = element_text(size = 35),
          
          strip.text.x = element_blank(),
          
          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),
          
          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_blank(),
          
          legend.position = "none") +
  
  labs(x="\nNest litter samples") + 
  
  scale_y_continuous(limits = c(0,740), expand = c(0, 0)) +
  
  facet_grid(~Age, scales = "free_x", space = "free")  + 
  
  scale_fill_manual(values = kakapo_age_colours)

obs_bar.n
```

```{r fig.height=10, fig.width=10}
obs.Age.n <- ggplot(rich_dfN, aes(x=Age, y=Observed))
obs.Age.plot.n <- obs.Age.n + geom_boxplot(size=1.0, aes(fill=Age)) + myadptheme + 
    scale_fill_manual(values= kakapo_age_colours) + theme(plot.title = element_text(size = 35)) +
    labs(y = "Observed species", x = "\nTemporal groups") +
    ggtitle("Kruskal-Wallis p = 0.004** and glmm p < 0.001***") +
    geom_signif(data=obs.N.Age.bar,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 8, colour = "blue") 
obs.Age.plot.n
```

```{r fig.height=10, fig.width=42}
obs.litter = ggarrange(obs.Age.plot.n, obs_bar.n, labels = c("B"), font.label = list(size = 30), 
          ncol=2, nrow=1, legend = "none", widths = c(0.27,1))
obs.litter
```


```{r fig.height=10, fig.width=32}
simpson_bar.n <- ggplot(data=rich_dfN, aes(x=Sample_Name,y=InvSimpson, fill=Age)) + 
  
  geom_bar(aes(), stat="identity", position="stack", width = 1)  + 
  
  theme_ipsum() + theme(axis.text.x = element_blank(),

          axis.ticks.x = element_blank(),

          axis.text.y=element_blank(),

          axis.title.y=element_blank(),
          
          axis.title.x = element_text(size = 35),
          
          strip.text.x = element_blank(),
          
          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),
          
          axis.line.x=element_line(color="black",size=1.0,linetype=1),

          axis.line.y=element_blank(),
          
          legend.position = "bottom", 
          
          legend.title = element_text(face = "bold", size = 35),
          
          legend.text = element_text(size = 30),
          
          legend.box.background = element_rect(),

          legend.box.margin = margin(5, 5, 5, 5)) +
  
  guides(fill = guide_legend(nrow = 1, override.aes=list(shape=15, size = 15))) +
  
  labs(x = "\nNest litter samples") +
    
  scale_y_continuous(limits = c(0,225), expand = c(0, 0)) +
  
  facet_grid(~Age, scales = "free_x", space = "free") + 
  
  scale_fill_manual(values = kakapo_age_colours, name = "Days") 

simpson_bar.n

simpson_bar.n.NL = simpson_bar.n + theme(legend.position = "none")

litter.adp.legend = get_legend(simpson_bar.n)
```

```{r fig.height=10, fig.width=10}
simpson.Age.n <- ggplot(rich_dfN, aes(x=Age, y=InvSimpson))
simpson.Age.plot.n <- simpson.Age.n + geom_boxplot(size=1.0, aes(fill=Age)) + 
    myadptheme +  theme(plot.title = element_text(size = 35)) +
    scale_fill_manual(values = kakapo_age_colours) + 
    labs(y = "Inverse Simpson diversity", x = "\nTemporal groups") +
    ggtitle("Kruskal-Wallis p = 0.12 and lmm p = 0.002**") +
    geom_signif(data=simpson.N.Age.bar,aes(xmin=start, xmax=end, annotations=label, y_position=y),
              manual=TRUE, tip_length = 0, textsize = 8, colour = "blue") 
simpson.Age.plot.n
```

```{r fig.height=10, fig.width=42}
simpson.litter = ggarrange(simpson.Age.plot.n, simpson_bar.n.NL, labels = c("C"), font.label = list(size = 30), 
          ncol=2, nrow=1, widths = c(0.27,1), legend = "none")
simpson.litter
```

```{r fig.height = 32, fig.width = 42, dpi=300}
litter.taxa.adp.combined = ggarrange(taxa.n, NULL, obs.litter,simpson.litter, litter.adp.legend, labels = c("A"), font.label = list(size = 30), nrow = 5, heights = c(1, 0.02, 0.7, 0.7, 0.2))
litter.taxa.adp.combined
ggsave("taxa_plots/litter_age_taxaplot_adp_revisedMay2022.png", litter.taxa.adp.combined, height = 32, width = 48, dpi = 400)
```

```{r fig.height = 10, fig.width = 15, dpi=300}
##By nest

obs.nest.n <- ggplot(rich_dfN, aes(x=Nest, y=Observed))  
obs.nest.n.plot <- obs.nest.n + geom_boxplot(size=1.0, aes(fill=Nest)) + #,outlier.shape = NA) 
    myadptheme + 
        ggtitle("Observed species", subtitle = "Kruskal-Wallis p = 0.33") +
    scale_fill_manual(values = col.42) 
obs.nest.n.plot

shannon.nest.n <- ggplot(rich_dfN, aes(x=Nest, y=Shannon))  
shannon.nest.n.plot <- shannon.nest.n + geom_boxplot(size=1.0, aes(fill=Nest)) + myadptheme + 
    labs(y = "Shannon index") + 
    ggtitle("Shannon diversity",subtitle = "Kruskal-Wallis p = 0.39") +
    scale_fill_manual(values = col.42)
shannon.nest.n.plot
```

```{r fig.height = 21, fig.width = 15, dpi=300}
nest.n = ggarrange(obs.nest.n.plot, shannon.nest.n.plot, labels = c("A","B"),  
          ncol=1, nrow=2, common.legend = TRUE, legend="bottom")
nest.n.title = annotate_figure(nest.n, top = text_grob("Litter by nest", face = "bold", family = "sans", size = 30))
nest.n.title
ggsave("alpha_div/litter_nest_adp.png",nest.n.title, height = 21, width = 15, dpi = 400)
```


```{r fig.height = 10, fig.width = 13, dpi=300}
##Faecal experiment
n.obs.pooR <- ggplot(richN_UK.df, aes(x=Faecal_experiment, y=Observed))
n.obs.pooR.plot <- n.obs.pooR + geom_boxplot(size=1.0, aes(fill=Faecal_experiment)) + myadptheme.edit + 
    labs(y="Observed species", x = "Faecal experiment groups") + 
    scale_fill_manual(values= get_pal("Kakapo"), name = "Observed") + 
    ggtitle("Litter samples", subtitle = "Wilcoxon p = 0.44") 
n.obs.pooR.plot
```


```{r  fig.height = 19, fig.width = 15, dpi=300}
obs.pooR.together <- ggarrange(obs.pooR.plot, n.obs.pooR.plot, ncol=2, nrow=1, common.legend = TRUE, legend="bottom")

pooR.adp.bcbox.combined <- ggarrange(obs.pooR.together, NULL, bc.boxplots.combined, labels = c("A","","B"), font.label = list(size = 30), 
                                     nrow = 3, heights = c(1,0.15,1)) + theme(plot.margin = margin(1,0.5,0.5,0.5, "cm"))
pooR.adp.bcbox.combined
ggsave("pooR_adp_bcbox_combined.png",pooR.adp.bcbox.combined, height = 17, width = 15, dpi = 400, bg = "white")
```


#Heat maps

```{r}
heatmap.theme <- theme_ipsum() + theme(plot.title = element_text(size = 24),
  
          axis.ticks.x = element_blank(),

          axis.text.y=element_text(size=14),
          
          axis.text.x=element_text(size=17),

          axis.title.y=element_text(size=20),
          
          axis.title.x = element_text(size=20),
          
          panel.grid.major = element_blank(),

          panel.grid.minor = element_blank(),

          panel.background = element_blank(),
          
          legend.position = "right",
          
          legend.title = element_text(size = 17),
          
          legend.text = element_text(size = 12))
```

```{r fig.height = 22, fig.width = 16, dpi=300}
psF_sub.NT <- subset_samples(psF_SRS, Nest_type != "Sub-adult samples")
merged.ps.F.NT = merge_samples(psF_sub.NT, "Nest_type")
top20.F.NT <- prune_taxa(names(sort(taxa_sums(merged.ps.F.NT),TRUE)[1:20]), merged.ps.F.NT)

hm.f.NT = plot_heatmap(top20.F.NT, "PCoA","bray", low="#ffd1d5", high="#6b2643", na.value="#f6e8e0", taxa.order="Family", sample.order = c("A-frame","Hand rearing","Hole","Open","Rock","Tree")) + 
      theme_ipsum() + 
      labs(x = "Nest type", y = "ASV") + 
      heatmap.theme + 
      ggtitle("Heatmap of 20 most abundant ASVs")
hm.f.NT

heatmap.adp.combined.NT <- ggarrange(nest.type.f.title, NULL, hm.f.NT, nrow = 3, labels = c("","","C"), font.label = list(size = 30),
                                     heights = c(1, 0.15, 1)) + theme(plot.margin = margin(1,0.5,0.5,0.5, "cm"))
heatmap.adp.combined.NT
ggsave("heatmap_adp_combined_nest_type.png", heatmap.adp.combined.NT, width = 18, height = 22, dpi = 400, bg = "white")
```

```{r fig.height = 22, fig.width = 16, dpi=300}
merged.ps.F.location <- merge_samples(psF_SRS, "Location")
top20.F.location <- prune_taxa(names(sort(taxa_sums(merged.ps.F.location),TRUE)[1:20]), merged.ps.F.location)

hm.f.is = plot_heatmap(top20.F.location, "PCoA","bray", low="#ffd1d5", high="#6b2643", na.value="#f6e8e0",
                        taxa.order="Family", sample.order = c("Pukenui","Hand rearing","Whenua Hou")) + 
      theme_ipsum() + 
      labs(x = "Location", y = "ASV") + 
      heatmap.theme + 
      ggtitle("Faecal samples")
hm.f.is

heatmap.adp.combined.location <- ggarrange(location.f.title, NULL, hm.f.is, nrow = 3, labels = c("A","","B"), font.label = list(size = 30),
                                     heights = c(1, 0.15, 1)) + theme(plot.margin = margin(3,0.5,0.5,0.5, "cm"))
heatmap.adp.combined.location
ggsave("heatmap_adp_combined_location.png", heatmap.adp.combined.location, width = 16, height = 22, dpi = 400, bg = "white")
```


#Beta Diversity

```{r fig.height = 10, fig.width = 15, dpi=300}
map.f.2 <- sample_data(psF_SRS)
identical(rownames(map.f.2), rownames(SRS_outputF.df.sort))
map.f.2$E_abundance = SRS_outputF.df.sort$`ASV_1_Escherichia-Shigella coli`
psF_SRS_beta <- phyloseq(otu_table(SRS_outputF.df.sort, taxa_are_rows = F), 
                sample_data(map.f.2),
                tax_table(NtaxaF.df))

psF_RA <- transform_sample_counts(psF_SRS_beta, function(x) {x/sum(x)})

map.n.2 <- sample_data(psN_SRS)
identical(rownames(map.n.2), rownames(SRS_outputN.df.sort))
map.n.2$E_abundance = SRS_outputN.df.sort$`ASV_1_Escherichia-Shigella coli`
psN_SRS_beta <- phyloseq(otu_table(SRS_outputN.df.sort, taxa_are_rows = F), 
                sample_data(map.n.2),
                tax_table(NtaxaN.df))

psN_RA <- transform_sample_counts(psN_SRS_beta, function(x) {x/sum(x)})
```


```{r}
library(ggtext)

ord_theme = theme_ipsum() + 
  theme(plot.title = element_markdown(size = 32, margin=margin(0,0,30,0)),
    
    axis.title.x = element_text(size=25),
    
    axis.title.y =element_text(size=25),
    
    axis.text.x = element_text(size = 17),
    
    axis.text.y = element_text(size = 17),

    axis.line.x=element_line(color="black",size=0.5,linetype=1),

    axis.line.y=element_line(color="black",size=0.5,linetype=1),

    panel.grid.major = element_blank(),

    panel.grid.minor = element_blank(),

    panel.background = element_blank(),

    legend.text = element_markdown(size=25),
    
    legend.title = element_markdown(face="bold", size = 28),
    
    legend.position = "top") 
```


####Faecal
```{r results='hide'}
F_otu_RA <- data.frame(otu_table(psF_RA))
F.dist <- vegdist(F_otu_RA, method="bray",
                    binary=FALSE, diag=FALSE, upper=FALSE,
                    na.rm=FALSE)

pcoa_bactF<-cmdscale(F.dist, k=2, eig=T)
pcoa.var.perF<-round(pcoa_bactF$eig/sum(pcoa_bactF$eig)*100, 1)

pcoa.valuesF <- pcoa_bactF$points

pcoa.dataF <- data.frame(Sample=rownames(pcoa.valuesF),
                        X=pcoa.valuesF[,1],
                        Y=pcoa.valuesF[,2])

pcoa.mapF <- data.frame(sample_data(psF_RA))

pcoa.dataF$Name <- pcoa.mapF$Name
pcoa.dataF$Nest <- pcoa.mapF$Nest
pcoa.dataF$Age <- pcoa.mapF$Age
pcoa.dataF$Days <- pcoa.mapF$Days
pcoa.dataF$Aspergillosis <- pcoa.mapF$Aspergillosis
pcoa.dataF$Faecal_experiment <- pcoa.mapF$Faecal_experiment
pcoa.dataF$Nest_Type <- pcoa.mapF$Nest_Type
pcoa.dataF$Location <- pcoa.mapF$Location
pcoa.dataF$E_abundance <- pcoa.mapF$E_abundance
pcoa.dataF$HR <- as.character(pcoa.dataF$Location)
pcoa.dataF$HR[which(pcoa.dataF$HR == "Hand rearing")] = "In captive facility"
pcoa.dataF$HR[which(pcoa.dataF$HR != "In captive facility")] = "In nest"
pcoa.dataF$Location = factor(pcoa.dataF$Location, levels = c("Pukenui","Whenua Hou","Hand rearing"))

vec.spF<-envfit(pcoa_bactF$points , F_otu_RA, perm=1000)

vec.sp.df_F<-
  as.data.frame(scores(vec.spF, "vectors"))

vec.sp.df_F$species<-rownames(vec.sp.df_F)


vec.sp.df_F.sig <- vec.sp.df_F[c(1,12,24,2,3,97,100,138,21,51,6), ]

kakapo_colours <- c("#4b5e1e", "#7D9D33", "#DCC949", "#BCA888", "#CD8862", "#775B24")
```

```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.f.HR <- ggplot(data=pcoa.dataF, aes(x = X, y = Y, colour = Location)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perF[2], "%","]" ,sep=" ")) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_color_manual(values = c("#818e61","#a5b08b","#8e6181"), name = "Location") + 
  scale_shape_manual(values=c(16,15,5,21,22,18)) +
  ord_theme + theme(legend.box = "vertical") + 
  ggtitle("Faecal samples by location")

taxa.f.HR
```

```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.f.coli <- ggplot(data=pcoa.dataF, aes(x = X, y = Y, colour = E_abundance)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_shape_manual(values=c(16,15,5,21,22,18)) +
  ord_theme + theme(legend.box = "vertical") + 
  guides(shape = guide_legend(order = 1)) +
  scale_color_gradient(low = "blue", high = "red", name="*ES. coli* abundance",
                       labels=c("Low","High"),breaks=c(200,1000), guide = "colourbar") +
  ggtitle("Faecal samples by ASV1 *ES. coli* abundance")

taxa.f.coli
```


```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.f.age <- ggplot(data=pcoa.dataF, aes(x = X, y = Y, colour = Days)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  # scale_color_manual(values = c("#788374","#ebd27d","#aa644d","#372a39","#597692","#5a5145")) + 
  # scale_shape_manual(values=c(21,22,18,17)) +
  # ord_theme + theme(legend.box = "vertical") + 
  # guides(color = guide_legend(nrow = 2)) +
  # guides(shape = guide_legend(order = 1)) +
  scale_shape_manual(values=c(16,15,5,21,22,18)) +
  ord_theme + theme(legend.box = "vertical") + 
  guides(shape = guide_legend(order = 1)) +
  scale_color_viridis(option = "D", name="Chick age",
                       labels=c("<14","300+"),breaks=c(20,350), guide = "colourbar") +
  ggtitle("Faecal samples by k\u101k\u101p\u14d chick age")

taxa.f.age
```

```{r fig.height = 10, fig.width = 18, dpi=300}
library(ggrepel); packageVersion("ggrepel")
taxa.f.vec <- ggplot(data=pcoa.dataF, aes(x = X, y = Y)) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_segment(data=vec.sp.df_F.sig,
               aes(x=0,xend=Dim1,y=0,yend=Dim2),
               arrow = arrow(length = unit(0.3, "cm")),
               colour="red", size = 1,
               inherit.aes=FALSE) +
  geom_text_repel(data=vec.sp.df_F.sig,
            aes(x=Dim1,y=Dim2,label=species),size=7.5,
            inherit.aes=FALSE, max.overlaps = Inf) +
  ord_theme + 
  xlim(-1.22, 0.7) +
  ylim(-1, 0.6) +
  ggtitle("Influential ASV vectors for ordinated faecal samples")

taxa.f.vec
```

```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.f.nest <- ggplot(data=pcoa.dataF, aes(x = X, y = Y, colour = Nest)) +
  geom_point(size=5, aes(shape=Aspergillosis)) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_segment(data=vec.sp.df_F.sig, 
               aes(x=0,xend=Dim1,y=0,yend=Dim2),
               arrow = arrow(length = unit(0.3, "cm")),
               colour="red", size = 1,
               inherit.aes=FALSE) + 
  geom_text(data=vec.sp.df_F.sig,
            aes(x=Dim1,y=Dim2,label=species),size=4,
            inherit.aes=FALSE) + 
  scale_color_manual(values = col.42) + 
  scale_shape_manual(values=c(15:17)) +
  ordplot_theme + theme(legend.box = "vertical") + 
  guides(color = guide_legend(order = 1)) +
  xlim(-1.1, 0.6) +
  ylim(-0.45, 0.9) +
  ggtitle("Faecal samples by resident nest")

taxa.f.nest
ggsave("ordinations/taxa_vec_faecal_nest.png", taxa.f.nest, height = 10, width = 18, dpi = 300)
```

####Nest
```{r results='hide'}
N_otu_RA <- data.frame(otu_table(psN_RA))
N.dist <- vegdist(N_otu_RA, method="bray",
                    binary=FALSE, diag=FALSE, upper=FALSE,
                    na.rm=FALSE)

pcoa_bactN<-cmdscale(N.dist, k=2, eig=T)
pcoa.var.perN<-round(pcoa_bactN$eig/sum(pcoa_bactN$eig)*100, 1)

pcoa.valuesN <- pcoa_bactN$points

pcoa.dataN <- data.frame(Sample=rownames(pcoa.valuesN),
                        X=pcoa.valuesN[,1],
                        Y=pcoa.valuesN[,2])

pcoa.mapN <- data.frame(sample_data(psN_RA))

pcoa.dataN$Faecal_experiment <- pcoa.mapN$Faecal_experiment
pcoa.dataN$Nest <- pcoa.mapN$Nest
pcoa.dataN$Aspergillosis <- pcoa.mapN$Aspergillosis
pcoa.dataN$Nest_Type <- pcoa.mapN$Nest_Type
pcoa.dataN$Days <- pcoa.mapN$Days
pcoa.dataN$Location <- pcoa.mapN$Location
pcoa.dataN$E_abundance <- pcoa.mapN$E_abundance

vec.spN<-envfit(pcoa_bactN$points , N_otu_RA, perm=1000)

vec.sp.df_N<-
  as.data.frame(scores(vec.spN, "vectors"))

vec.sp.df_N$species<-rownames(vec.sp.df_N)


vec.sp.df_N.sig <- vec.sp.df_N[c(1,15,237,10,104,356,88,7,2,3,160,46,69), ]
```

```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.n.age <- ggplot(data=pcoa.dataN, aes(x = X, y = Y, colour = Days)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  #scale_color_manual(values = c("#788374","#ebd27d","#aa644d","#372a39")) + 
  scale_color_viridis(option = "D", name="Days",
                       labels=c("<14","75+"),breaks=c(14,75), guide = "colourbar") +
  scale_shape_manual(values=c(16,15,18,17,21:25)) +
  ord_theme + theme(legend.box = "vertical") + guides(shape = guide_legend(order = 1)) +
  ggtitle("Litter samples by days since first chick")


taxa.n.age
```


```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.n.coli <- ggplot(data=pcoa.dataN, aes(x = X, y = Y, colour = E_abundance)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_shape_manual(values=c(16,15,21:25)) +
  ord_theme + theme(legend.box = "vertical") + 
  guides(shape = guide_legend(order = 1)) +
  scale_color_gradient(low = "blue", high = "red", name="*ES. coli* abundance",
                       labels=c("Low","High"),breaks=c(250,1550), guide = "colourbar") +
  ggtitle("Litter samples by *ES. coli* abundance")

taxa.n.coli
```

```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.n.is <- ggplot(data=pcoa.dataN, aes(x = X, y = Y, colour = Location)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_color_manual(values = c("#818e61","#a5b08b")) + 
  scale_shape_manual(values=c(16,15)) +
  ord_theme + theme(legend.box = "vertical") + 
  ggtitle("Litter samples by island")

taxa.n.is
```

```{r fig.height = 10, fig.width = 18, dpi=300}
taxa.n.vec <- ggplot(data=pcoa.dataN, aes(x = X, y = Y)) +
  xlab(paste("PCoA 1","[" ,pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_segment(data=vec.sp.df_N.sig,
               aes(x=0,xend=Dim1,y=0,yend=Dim2),
               arrow = arrow(length = unit(0.3, "cm")),
               colour="red", size = 1,
               inherit.aes=FALSE) +
  geom_text_repel(data=vec.sp.df_N.sig,
            aes(x=Dim1,y=Dim2,label=species),size=7.5,
            inherit.aes=FALSE, max.overlaps = Inf) +
  ord_theme + #theme(legend.box = "vertical") + 
  ylim(-0.8, 0.8) +
  xlim(-0.95, 0.7) +
  ggtitle("Influential ASV vectors for ordinated litter samples")

taxa.n.vec
```

```{r fig.height = 21, fig.width = 38, dpi=300}
pcoa_faecal_ords <-  ggarrange(taxa.f.HR, taxa.f.coli, taxa.f.age, taxa.f.vec, labels = c("A","B","C","D"), ncol = 2, nrow=2, font.label = list(size = 30))
pcoa_faecal_ords
ggsave("ordinations/taxa_vectors_faecal_Mayrevised.png", pcoa_faecal_ords, width = 36, height = 20, dpi = 300, bg = "white")

pcoa_litter_ords <-  ggarrange(taxa.n.is, taxa.n.coli, taxa.n.age, taxa.n.vec, labels = c("A","B","C","D"), ncol = 2, nrow=2, font.label = list(size = 30))
pcoa_litter_ords
ggsave("ordinations/taxa_vectors_litter_Mayrevised.png", pcoa_litter_ords, width = 36, height = 20, dpi = 400, bg = "white")
```


##gUniFrac PCoA

```{r results=F, message=F, warning=F}
library(GUniFrac); packageVersion("GUniFrac")
library(phangorn); packageVersion("phangorn")
```

```{r, results='hide'}
asvF.unif <- data.frame(otu_table(psF_SRS_GUF))
asvF.unif = asvF.unif[,order(colSums(asvF.unif),decreasing = T)]
gunifrac.tree <- midpoint(phy_tree(psF_SRS_GUF))
gunifracs <- GUniFrac(asvF.unif, gunifrac.tree,  alpha=c(0,0.5,1))$unifracs

d5 <- gunifracs[, , "d_0.5"]
d5.dist <- as.dist(d5)

pcoa_guniF<-cmdscale(d5, k=2, eig=T)
unif.pcoa.var.perF <-round(pcoa_guniF$eig/sum(pcoa_guniF$eig)*100, 1)
unif.pcoa.valuesF <- pcoa_guniF$points
unif.pcoa.dataF <- data.frame(Sample=rownames(unif.pcoa.valuesF),
                        X=unif.pcoa.valuesF[,1],
                        Y=unif.pcoa.valuesF[,2])

unif.pcoa.dataF$Name <- map.f.2$Name
unif.pcoa.dataF$Nest <- map.f.2$Nest
unif.pcoa.dataF$Age <- map.f.2$Age
unif.pcoa.dataF$Days <- map.f.2$Days
unif.pcoa.dataF$Aspergillosis <- map.f.2$Aspergillosis
unif.pcoa.dataF$Faecal_experiment <- map.f.2$Faecal_experiment
unif.pcoa.dataF$Nest_Type <- map.f.2$Nest_Type
unif.pcoa.dataF$Location <- map.f.2$Location
unif.pcoa.dataF$E_abundance <- map.f.2$E_abundance
unif.pcoa.dataF$HR <- as.character(unif.pcoa.dataF$Location)
unif.pcoa.dataF$HR[which(unif.pcoa.dataF$HR == "Hand rearing")] = "In captive facility"
unif.pcoa.dataF$HR[which(unif.pcoa.dataF$HR != "In captive facility")] = "In nest"
unif.pcoa.dataF$Location = factor(unif.pcoa.dataF$Location, levels = c("Pukenui","Whenua Hou","Hand rearing"))
```

Rename ASV sequences and create taxonomic vectors
```{r}
Ntaxa.df.unif <- as.data.frame(NtaxaF)
to.remove = setdiff(rownames(Ntaxa.df.unif), colnames(asvF.unif))
Ntaxa.df.unif = Ntaxa.df.unif[!row.names(Ntaxa.df.unif) %in% to.remove,]
setdiff(rownames(Ntaxa.df.unif), colnames(asvF.unif))

identical(rownames(Ntaxa.df.unif), colnames(asvF.unif))
Ntaxa.df.unif = Ntaxa.df.unif[colnames(asvF.unif),]
identical(rownames(Ntaxa.df.unif), colnames(asvF.unif))

Ntaxa.df.unif$ASV_ID <- paste("ASV", 1:nrow(Ntaxa.df.unif), sep="")
Ntaxa.df.unif$concat = paste(Ntaxa.df.unif$ASV_ID, Ntaxa.df.unif$Taxonomy, sep = "_")
rownames(Ntaxa.df.unif) = Ntaxa.df.unif$concat
names(asvF.unif) = rownames(Ntaxa.df.unif)
```

```{r}
unif.vec.spF<-envfit(pcoa_guniF$points , asvF.unif, perm=1000)

unif.vec.sp.df_F<-
  as.data.frame(scores(unif.vec.spF, "vectors"))

unif.vec.sp.df_F$species<-rownames(unif.vec.sp.df_F)


unif.vec.sp.df_F.sig <- unif.vec.sp.df_F[c(1,12,13,24,4,5,38,2,59,46,21,3,100,97,6,138,9,51,30,49,72,14), ]

kakapo_colours <- c("#4b5e1e", "#7D9D33", "#DCC949", "#BCA888", "#CD8862", "#775B24")
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.f.HR <- ggplot(data=unif.pcoa.dataF, aes(x = X, y = Y, colour = Location)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perF[2], "%","]" ,sep=" ")) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
 scale_color_manual(values = c("#818e61","#a5b08b","#8e6181"), name = "Location") + 
  scale_shape_manual(values=c(16,15,5,21,22,18)) +
  ord_theme + theme(legend.box = "vertical") + 
  ggtitle("Faecal samples by location")

unif.taxa.f.HR
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.f.coli <- ggplot(data=unif.pcoa.dataF, aes(x = X, y = Y, colour = E_abundance)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_shape_manual(values=c(16,15,5,21,22,18)) +
  ord_theme + theme(legend.box = "vertical") + 
  guides(shape = guide_legend(order = 1)) +
  scale_color_gradient(low = "blue", high = "red", name="*ES. coli* abundance",
                       labels=c("Low","High"),breaks=c(200,1000), guide = "colourbar") +
  ggtitle("Faecal samples by ASV1 *ES. coli* abundance")

unif.taxa.f.coli
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.f.age <- ggplot(data=unif.pcoa.dataF, aes(x = X, y = Y, colour = Days)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_shape_manual(values=c(16,15,5,21,22,18)) +
  ord_theme + theme(legend.box = "vertical") + 
  guides(shape = guide_legend(order = 1)) +
 # scale_color_gradient(low = "purple", high = "yellow", name="Chick age",
  #                     labels=c("Low","High"),breaks=c(70,295), guide = "colourbar") +
  scale_color_viridis(option = "D", name="Chick age in days",
                       labels=c("<14","350+"),breaks=c(14,350), guide = "colourbar") +
  ggtitle("Faecal samples by k\u101k\u101p\u14d chick age")

unif.taxa.f.age
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.f.vec <- ggplot(data=unif.pcoa.dataF, aes(x = X, y = Y)) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perF[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perF[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_segment(data=unif.vec.sp.df_F.sig,
               aes(x=0,xend=Dim1,y=0,yend=Dim2),
               arrow = arrow(length = unit(0.3, "cm")),
               colour="red", size = 1,
               inherit.aes=FALSE) +
  geom_text_repel(data=unif.vec.sp.df_F.sig,
            aes(x=Dim1,y=Dim2,label=species),size=7.5,
            inherit.aes=FALSE, max.overlaps = Inf) +
  ord_theme + 
  xlim(-0.9, 0.7) +
  ylim(-0.6, 0.7) +
  ggtitle("Influential ASV vectors for ordinated faecal samples")

unif.taxa.f.vec
```

###Litter
```{r, results='hide'}
asvN.unif <- data.frame(otu_table(psN_SRS_GUF))
asvN.unif = asvN.unif[,order(colSums(asvN.unif),decreasing = T)]
gunifrac.tree.N <- midpoint(phy_tree(psN_SRS_GUF))
gunifracs.N <- GUniFrac(asvN.unif, gunifrac.tree.N,  alpha=c(0,0.5,1))$unifracs

d5N <- gunifracs.N[, , "d_0.5"]
d5.dist.N <- as.dist(d5N)

pcoa_guniN<-cmdscale(d5N, k=2, eig=T)
unif.pcoa.var.perN <-round(pcoa_guniN$eig/sum(pcoa_guniN$eig)*100, 1)
unif.pcoa.valuesN <- pcoa_guniN$points
unif.pcoa.dataN <- data.frame(Sample=rownames(unif.pcoa.valuesN),
                        X=unif.pcoa.valuesN[,1],
                        Y=unif.pcoa.valuesN[,2])

unif.pcoa.dataN$Name <- map.n.2$Name
unif.pcoa.dataN$Days <- map.n.2$Days
unif.pcoa.dataN$Location <- map.n.2$Location
unif.pcoa.dataN$E_abundance <- map.n.2$E_abundance
```

Rename ASV sequences and create taxonomic vectors
```{r}
NtaxaN.df.unif <- as.data.frame(NtaxaN)
to.remove = setdiff(rownames(NtaxaN.df.unif), colnames(asvN.unif))
NtaxaN.df.unif = NtaxaN.df.unif[!row.names(NtaxaN.df.unif) %in% to.remove,]
setdiff(rownames(NtaxaN.df.unif), colnames(asvN.unif))

identical(rownames(NtaxaN.df.unif), colnames(asvN.unif))
NtaxaN.df.unif = NtaxaN.df.unif[colnames(asvN.unif),]
identical(rownames(NtaxaN.df.unif), colnames(asvN.unif))

NtaxaN.df.unif$ASV_ID <- paste("ASV", 1:nrow(NtaxaN.df.unif), sep="")
NtaxaN.df.unif$concat = paste(NtaxaN.df.unif$ASV_ID, NtaxaN.df.unif$Taxonomy, sep = "_")
rownames(NtaxaN.df.unif) = NtaxaN.df.unif$concat
names(asvN.unif) = rownames(NtaxaN.df.unif)
```

```{r}
unif.vec.spN<-envfit(pcoa_guniN$points , asvN.unif, perm=1000)

unif.vec.sp.df_N<-
  as.data.frame(scores(unif.vec.spN, "vectors"))

unif.vec.sp.df_N$species<-rownames(unif.vec.sp.df_N)


unif.vec.sp.df_N.sig <- unif.vec.sp.df_N[c(1,2,3,4,5,8,10,12,15,46,47,60,80,88,104,178,208), ]

kakapo_colours <- c("#4b5e1e", "#7D9D33", "#DCC949", "#BCA888", "#CD8862", "#775B24")
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.n.is <- ggplot(data=unif.pcoa.dataN, aes(x = X, y = Y, colour = Location)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_color_manual(values = c("#8e6181","#818e61")) + 
  scale_shape_manual(values=c(16,15)) +
  ord_theme + theme(legend.box = "vertical") + 
  ggtitle("Litter samples by island")

unif.taxa.n.is
```


```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.n.days <- ggplot(data=unif.pcoa.dataN, aes(x = X, y = Y, colour = Days)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  #scale_color_manual(values = c("#788374","#ebd27d","#aa644d","#372a39")) + 
  scale_color_viridis(option = "D", name="Days",
                       labels=c("<14","75+"),breaks=c(14,75), guide = "colourbar") +
  scale_shape_manual(values=c(16,15)) +
  ord_theme + theme(legend.box = "vertical") + guides(shape = guide_legend(order = 1)) +
  ggtitle("Litter samples by days since first chick")


unif.taxa.n.days
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.n.coli <- ggplot(data=unif.pcoa.dataN, aes(x = X, y = Y, colour = E_abundance)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_shape_manual(values=c(16,15)) +
  ord_theme + theme(legend.box = "vertical") + 
  guides(shape = guide_legend(order = 1)) +
  scale_color_gradient(low = "blue", high = "red", name="*ES. coli* abundance",
                       labels=c("Low","High"),breaks=c(250,1550), guide = "colourbar") +
  ggtitle("Litter samples by *ES. coli* abundance")

unif.taxa.n.coli
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.n.is <- ggplot(data=unif.pcoa.dataN, aes(x = X, y = Y, colour = Location)) +
  geom_point(size=7, aes(shape=Location), stroke = 2) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") + 
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_color_manual(values = c("#818e61","#a5b08b")) + 
  scale_shape_manual(values=c(16,15)) +
  ord_theme + theme(legend.box = "vertical") + 
  ggtitle("Litter samples by island")

unif.taxa.n.is
```

```{r fig.height = 10, fig.width = 18, dpi=300}
unif.taxa.n.vec <- ggplot(data=unif.pcoa.dataN, aes(x = X, y = Y)) +
  xlab(paste("PCoA 1","[" ,unif.pcoa.var.perN[1], "%","]" ,sep=" ")) +
  ylab(paste("PCoA 2","[" ,unif.pcoa.var.perN[2], "%","]" ,sep=" ")) + 
  geom_vline(xintercept = 0, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_segment(data=unif.vec.sp.df_N.sig,
               aes(x=0,xend=Dim1,y=0,yend=Dim2),
               arrow = arrow(length = unit(0.3, "cm")),
               colour="red", size = 1,
               inherit.aes=FALSE) +
  geom_text_repel(data=unif.vec.sp.df_N.sig,
            aes(x=Dim1,y=Dim2,label=species),size=7.5,
            inherit.aes=FALSE, max.overlaps = Inf) +
  ord_theme + #theme(legend.box = "vertical") + 
  ylim(-0.8, 0.8) +
  xlim(-0.95, 0.7) +
  ggtitle("Influential ASV vectors for ordinated litter samples")

unif.taxa.n.vec
```


```{r fig.height = 21, fig.width = 38, dpi=300}
unif.pcoa_faecal_ords <-  ggarrange(unif.taxa.f.HR, unif.taxa.f.coli, unif.taxa.f.age, unif.taxa.f.vec, labels = c("A","B","C","D"), ncol = 2, nrow=2, font.label = list(size = 30))
unif.pcoa_faecal_ords
ggsave("ordinations/gunif_pcoa_faecal.png", unif.pcoa_faecal_ords, width = 36, height = 20, dpi = 300, bg = "white")

unif.pcoa_litter_ords <-  ggarrange(unif.taxa.n.is, unif.taxa.n.coli, unif.taxa.n.days, unif.taxa.n.vec, labels = c("A","B","C","D"), ncol = 2, nrow=2, font.label = list(size = 30))
unif.pcoa_litter_ords
ggsave("ordinations/gunif_taxa_vectors_litter.png", pcoa_litter_ords, width = 36, height = 20, dpi = 400, bg = "white")
```


#Mixed models

```{r}
library(microbiome); packageVersion("microbiome")

glom_f_genus <- tax_glom(psF_RA, taxrank = 'Genus')
clr_f_genus <- microbiome::transform(glom_f_genus, "clr") #transform to log-ratios

tax.table.g <- data.frame(otu_table(clr_f_genus))
tax.glom.g <- data.frame(tax_table(clr_f_genus))
tax.map.g <- data.frame(sample_data(clr_f_genus))

names(tax.table.g) <- tax.glom.g$Genus

taxa.model.map.g <- cbind(tax.map.g,tax.table.g)
names(taxa.model.map.g)[names(taxa.model.map.g) == "Escherichia-Shigella"] <- "Escherichia.Shigella"
names(taxa.model.map.g)[names(taxa.model.map.g) == "Clostridium sensu stricto 1"] <- "Clostridium.sensu.stricto.1"

hist(taxa.model.map.g$Escherichia.Shigella)

#Escherichia-Shigella
hist(taxa.model.map.g$Escherichia.Shigella)
escherichia.model <- lme4::lmer(Escherichia.Shigella ~ Age + (1|Name) + (1|Nest), data=taxa.model.map.g)
summary(escherichia.model)
null.es.model <- lme4::lmer(Escherichia.Shigella ~ (1|Name) + (1|Nest), data=taxa.model.map.g)
anova(escherichia.model,null.es.model)

escherichia.model.L <- lme4::lmer(Escherichia.Shigella ~ Location + (1|Name) + (1|Days), data=taxa.model.map.g)
null.es.model.L <- lme4::lmer(Escherichia.Shigella ~ (1|Name) + (1|Age), data=taxa.model.map.g)
summary(escherichia.model.L)
anova(escherichia.model.L,null.es.model.L)

#Streptococcus
strep.model <- lme4::lmer(Streptococcus ~ Age + (1|Name)  + (1|Nest), data=taxa.model.map.g)
summary(strep.model)
null.strep.model <- lme4::lmer(Streptococcus ~ (1|Name)  + (1|Nest), data=taxa.model.map.g)
anova(strep.model,null.strep.model)

strep.model.L <- lme4::lmer(Streptococcus ~ Location + (1|Name)  + (1|Age), data=taxa.model.map.g)
summary(strep.model.L)
null.strep.model.L <- lme4::lmer(Streptococcus ~ (1|Name)  + (1|Age), data=taxa.model.map.g)
anova(strep.model.L,null.strep.model.L)

#Lactobacillus
lactob.model <- lme4::lmer(Lactobacillus ~ Age + (1|Name)  + (1|Nest), data=taxa.model.map.g)
summary(lactob.model)
null.lactob.model <- lme4::lmer(Lactobacillus ~ (1|Name)  + (1|Nest), data=taxa.model.map.g)
anova(null.lactob.model,lactob.model)

lactob.model.L <- lme4::lmer(Lactobacillus ~ Location + (1|Name)  + (1|Age), data=taxa.model.map.g)
summary(lactob.model.L)
null.lactob.model.L <- lme4::lmer(Lactobacillus ~ (1|Name)  + (1|Age), data=taxa.model.map.g)
anova(lactob.model.L,null.lactob.model.L)

#Tyzzerella
tyzz.model <- lme4::lmer(Tyzzerella ~ Age + (1|Name)  + (1|Nest), data=taxa.model.map.g)
summary(tyzz.model)
null.tyzz.model <- lme4::lmer(Tyzzerella ~ (1|Name)  + (1|Nest), data=taxa.model.map.g)
anova(null.tyzz.model,tyzz.model)

tyzz.model.L <- lme4::lmer(Tyzzerella ~ Location + (1|Name)  + (1|Age), data=taxa.model.map.g)
summary(tyzz.model.L)
null.tyzz.model.L <- lme4::lmer(Tyzzerella ~ (1|Name)  + (1|Age), data=taxa.model.map.g)
anova(tyzz.model.L,null.tyzz.model.L)

#Clostridium.sensu.stricto.1 
clostridium.model <- lme4::lmer(Clostridium.sensu.stricto.1 ~ Age + (1|Name)  + (1|Nest), data=taxa.model.map.g)
summary(clostridium.model)
null.clostridium.model <- lme4::lmer(Clostridium.sensu.stricto.1 ~ (1|Name)  + (1|Nest), data=taxa.model.map.g)
anova(null.clostridium.model,clostridium.model)

clostridium.model.L <- lme4::lmer(Clostridium.sensu.stricto.1 ~ Location + (1|Name)  + (1|Age), data=taxa.model.map.g)
summary(clostridium.model.L)
null.clostridium.model.L <- lme4::lmer(Clostridium.sensu.stricto.1 ~ (1|Name)  + (1|Age), data=taxa.model.map.g)
anova(clostridium.model.L,null.clostridium.model.L)


lme4.p.values <- c("0.00004","0.00000000003","0.19","0.0004","0.00000002","0.0000000000000002","0.03","0.0000000005","0.001","0.0000000000000002")
p.adjust(lme4.p.values, method = "BH")
```

#Chick weight
```{r}
weight.df <- read.csv("weights_2019_2020.csv")
levels(factor(weight.df$birdName))

chick.names.df <- read.table("all_chick_names.txt")

weight.df.edit <- weight.df[trimws(weight.df$birdName) %in% trimws(chick.names.df$V1),]
write.csv(weight.df.edit, "weight.df.edit.csv")


chick.id.name <- read.csv("Chick_id_names.csv")
map.weights <- map.ps2.F.sort[trimws(map.ps2.F.sort$Name) %in% trimws(chick.id.name$SampleID),]
map.w.edit <- merge(map.weights, chick.id.name, by="Name")
map.w.edit$Name.date <- paste(map.w.edit$Chick_Name,"_",map.w.edit$Date)


weight.df.slim <- read.csv("weight.df.slim.csv")
weight.df.slim$Name.date <- paste(weight.df.slim$birdName,"_",weight.df.slim$date)
weight.df.slim.subset <- weight.df.slim[trimws(weight.df.slim$Name.date) %in% trimws(map.w.edit$Name.date),]


richF.subset.df <- as.data.frame(richF)
richF.subset.df <- richF.subset.df[trimws(richF.subset.df$Name) %in% trimws(map.weights$Name),]#remove pooled samples
richF.subset.df.names <- merge(richF.subset.df, chick.id.name, by="Name")
names(richF.subset.df.names)[names(richF.subset.df.names) == "alpha_diversity.Observed"] <- "Observed"
names(richF.subset.df.names)[names(richF.subset.df.names) == "alpha_diversity.InvSimpson"] <- "InvSimpson"

richF.subset.df.names$Name.date <- paste(richF.subset.df.names$Chick_Name,"_",richF.subset.df.names$Date)
richF.subset.df.names.date <- richF.subset.df.names[trimws(richF.subset.df.names$Name.date) %in% trimws(map.w.edit$Name.date),]

alphadiv.weights.df <- merge(richF.subset.df.names.date, weight.df.slim.subset, by="Name.date")
alphadiv.weights.df.sub <- alphadiv.weights.df[!duplicated(alphadiv.weights.df$SAMPLE.ID),]

alphadiv.weights.df.sub %>% 
  dplyr::count(Rear_method)

w.obs.mod <- lm(Observed ~ t_weight, alphadiv.weights.df.sub)
summary(w.obs.mod)
w.invsimp.mod <- lm(InvSimpson ~ t_weight, alphadiv.weights.df.sub)
summary(w.invsimp.mod)

SRS_outputF.df.sort.subset <- SRS_outputF.df.sort[trimws(rownames(SRS_outputF.df.sort)) %in% trimws(alphadiv.weights.df.sub$SAMPLE.ID),]


permanova.dis.F.weights <- vegdist(SRS_outputF.df.sort.subset, method="bray",
                    binary=FALSE, diag=FALSE, upper=FALSE,
                    na.rm=FALSE)


vegan::adonis2(permanova.dis.F.weights ~ t_weight, alphadiv.weights.df.sub, permutations = 9999)

```

```{r}
##max chicks per nest

max.chicks <- read.csv("nest_chicks_max.csv")
max.chicks.edit <- max.chicks[trimws(max.chicks$mother) %in% trimws(map$Nest), ]

max.chicks.edit %>% dplyr::count(maxChick)
```


#DESeq2
```{r}
library(DESeq2); packageVersion("DESeq2")
library(RColorBrewer)

my_theme <- theme_ipsum() + 
  theme(axis.text.y = element_text(face="italic", size = 20),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_rect(color="black",size=0.7,linetype=1, fill = "NA"), 
        panel.background = element_blank(),
        axis.title.y = element_text(size = 35),
        axis.title.x = element_text(size=23),
        legend.box.background = element_rect(),
        legend.box.margin = margin(5, 5, 5, 5),
        legend.title = element_text(face = "bold", size = 28),
        legend.text = element_text(size = 28), 
        legend.position = "top") 
# Create a folder to save results
dir.create("deseq_results")
```

```{r}
psF2.ASV.df = as.data.frame(otu_table(psF2))
psF2.ASV.df = psF2.ASV.df[,order(colSums(psF2.ASV.df),decreasing = T)]
psF2.taxa.df = as.data.frame(tax_table(psF2))

identical(rownames(psF2.taxa.df), colnames(psF2.ASV.df))
setdiff(rownames(psF2.taxa.df), colnames(psF2.ASV.df))
psF2.taxa.df = psF2.taxa.df[colnames(psF2.ASV.df),]

psF2.taxa.df$ASV_ID <- paste("ASV_", 1:nrow(psF2.taxa.df), sep="")
psF2.taxa.df$concat = paste(psF2.taxa.df$ASV_ID, psF2.taxa.df$Taxonomy, sep = "_")
rownames(psF2.taxa.df) = psF2.taxa.df$concat
names(psF2.ASV.df) = rownames(psF2.taxa.df)

psF2.taxa.df$ASV_ID = NULL
psF2.taxa.df$concat = NULL
psF2.taxa.df = as.matrix(psF2.taxa.df)

psF2_edit <- phyloseq(otu_table(psF2.ASV.df, taxa_are_rows = F),
                     tax_table(psF2.taxa.df),
                     sample_data(psF2))
psF2_edit

ps.sta <- psF2_edit

sample_data(ps.sta)$Age <- revalue(sample_data(ps.sta)$Age, c("<14 days" = "<14","15-28 days" = "15.28",
                                                              "29-42 days" = "29.42", "43-56 days" = "43.56",
                                                              "57-70 days" = "57.70", "71-120 days" = "71.120",
                                                              "200+ days" = "200"))
```

```{r}
ps.age = subset_samples(ps.sta, Age != "15.28" & Age != "29.42" & Age != "43.56" & Age != "57.70" & 
                                  Age != "71.120" & Age != "200")
ps.age.0.1 = filter_taxa(ps.age, function(x) sum(x > 3) > (0.05*length(x)), TRUE)
ps.age.1 <- ps.age.0.1
```

```{r}
meta.st <- meta(ps.age.1)
meta.st$Hand_rearing <- as.factor(meta.st$Hand_rearing)
diagdds_sta = phyloseq_to_deseq2(ps.age.1, ~ Hand_rearing)
 gm_mean = function(x, na.rm=TRUE){
     exp(sum(log(x[x > 0]), na.rm=na.rm) / length(x))
 }
 geoMeans = apply(counts(diagdds_sta), 1, gm_mean)
 diagdds_sta = estimateSizeFactors(diagdds_sta, geoMeans = geoMeans)
 dds_st = DESeq(diagdds_sta, test="Wald", fitType="local")
```

```{r}
otu.ab1 <- abundances(ps.age.1)
 res1 = results(dds_st, cooksCutoff = FALSE)
 res_tax1 = cbind(as.data.frame(res1), as.matrix(rownames(otu.ab1)), OTU = rownames(res1))
 res_tax1 = cbind(as(res_tax1, "data.frame"), as(tax_table(ps.age.1)[rownames(res_tax1), ], "matrix"))
 res_tax_sig1 = subset(res_tax1, padj < 0.01 & 0 < abs(log2FoldChange))
 res_tax1$Significant <- ifelse(rownames(res_tax1) %in% rownames(res_tax_sig1) , "Yes", "No")
 res_tax1$Significant[is.na(res_tax1$Significant)] <- "No"
 sig_res1 <- res_tax1[rownames(res_tax_sig1),"OTU"]
 res_table1 <- data.frame(res_tax_sig1$baseMean , res_tax_sig1$log2FoldChange,res_tax_sig1$padj)
 row.names(res_table1) <- rownames(res_tax_sig1)
 
data_to_write1 <-res_tax_sig1[,c("baseMean","log2FoldChange","pvalue","padj","Phylum", "Class", "Order", "Family", "Genus","Species","Taxonomy","OTU")]
data_to_write1$DifferentiallyAbundant <-levels(meta.st[,"Hand_rearing"])[as.numeric(data_to_write1$log2FoldChange>0)+1]

# Total numer of OTUs DA
nrow(data_to_write1) 
length(unique(data_to_write1$Genus)) 
length(unique(data_to_write1$Taxonomy))
write.csv(data_to_write1,"deseq_results/rearing_deseq_comparison_14.csv")
df1 <- mutate(data_to_write1, Taxonomy, Taxonomy= paste(data_to_write1$Taxonomy ))
```

```{r fig.width=10, fig.height=10}
age.71.120<- ggplot(df1, aes(log2FoldChange, Taxonomy)) + 
  geom_point(aes(color = DifferentiallyAbundant), shape = 21, size = 3, stroke = 2) + 
  scale_color_manual(values= c("#4b5e1e", "#7D9D33"), labels = c("Wild", "Captive"), name = "71 - 120 days") + my_theme +
  labs(y = "Species") +  geom_vline(xintercept = 0) 

age.71.120
ggsave("deseq_results/Deseq_71.120.png", width = 12, height = 13, dpi=400, bg = "white")
```

```{r fig.height= 13, fig.width= 42}
deseq.plots.1 <- ggarrange(age.14, age.15.28, age.29.42, ncol = 3)
deseq.plots.1

deseq.plots.2 <- ggarrange(age.43.56, age.57.70, age.71.120, ncol = 3)
deseq.plots.2

ggsave("deseq_results/deseq.plot.1.png", deseq.plots.1, width = 42, height = 13, dpi = 200, bg = "white")
ggsave("deseq_results/deseq.plot.2.png", deseq.plots.2, width = 42, height = 13, dpi = 200, bg = "white")
```
