###################################################
### R scripts for the analysis of ssRNA phages. ###
### Stephen R. Stockdale & Julie Callanan       ###
###################################################

setwd('/Users/BioInfo/Desktop/Supplementary_data_2/')

######### Install and load necessary packages ##### 

#install.packages('ggplot2')
library('ggplot2')

#install.packages('ellipse')
library('ellipse')

#install.packages('RColorBrewer')
library('RColorBrewer')

#install.packages('dplyr')
library('dplyr')

#install.packages('readr')
library('readr')

#install.packages('tidyr')
library('tidyr')

#install.packages('cowplot')
library('cowplot')

#install.packages('Hmisc')
library('Hmisc')

#install.packages('lavaan')
library('lavaan')

#install.packages('plyr')
library('plyr')

#install.packages('reshape2')
library('reshape2')

#install.packages('ggpubr')
library('ggpubr')

#install.packages('iNEXT')
library('iNEXT')

#install.packages('plotly')
library('plotly')

#install.packages('networkD3')
library('networkD3')

#install.packages('corrplot')
library('corrplot')

#install.packages("PerformanceAnalytics")
library("PerformanceAnalytics")

#install.packages('summarytools')
library('summarytools')

#install.packages('treeio')
library('treeio')

#install.packages('ggtree')
library("ggtree")

#install.packages('phangorn')
library('phangorn')

#install.packages('gridExtra')
library('gridExtra')

#install.packages('grid')
library('grid')

#install.packages('phytools')
library('phytools')

#install.packages('stringr')
library("stringr")

#install.packages('cluster')
library("cluster")

#install.packages('seqinr')
library('seqinr')

#install.packages("wesanderson")
library('wesanderson')

#install.packages('yarrr')
library('yarrr')

#devtools::install_github('mikabr/ggpirate', force = T)
library('ggpirate')

#install.packages('tidyverse')
library('tidyverse')

#install.packages("dabestr")
library("dabestr")

#install.packages("vegan")
library("vegan")

#install.packages("phyloseq")
library('phyloseq')

######### Package citations and R version ######### 

citation() 
#To find package citations.

R.version
#R version 3.5.3 (2019-03-11)

###################################################
######### Unique contigs from protein hits ########

#Read in and sort tables from each HMM model (m1 to m5_plus) against 82 metaT samples.
#The rnaSPAdes and megahit assembled contigs are read in separately.

#Model 1 rnaSPAdes

read.csv('supp_figs/m1_rna_table.csv', header = F, stringsAsFactors = F) -> m1_all82_rna_table
m1_all82_rna_table[ ,c(2, 4, 7:19)] <- NULL
colnames(m1_all82_rna_table)[1:4] <- c('Cluster', 'Protein_ID' ,'evalue', 'score')
m1_all82_rna_table <- m1_all82_rna_table[which(m1_all82_rna_table$score >= 30), ]

U_Protein_ID_M1R <- as.data.frame(m1_all82_rna_table$Protein_ID)
colnames(U_Protein_ID_M1R)[1] <- 'Protein_ID'

split_names_M1R <- U_Protein_ID_M1R %>% separate(Protein_ID, into = c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'gNumber', 'iNumber', 'Protein_number'), sep = '_')

m1_all82_rna_table$Contig_ID <- paste(split_names_M1R$SRA, split_names_M1R$NodeNo, split_names_M1R$Length, split_names_M1R$LengthNo, split_names_M1R$Coverage, split_names_M1R$CoverageNo, split_names_M1R$gNumber, split_names_M1R$iNumber, sep = '_')

dataframe_1 <- U_Protein_ID_M1R <- as.data.frame(m1_all82_rna_table$Contig_ID)
colnames(dataframe_1)[1] <- 'Contig_ID'
dataframe_1 <- unique(dataframe_1)

split_contigs_M1R <- dataframe_1 %>% separate(Contig_ID, c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'CoverageNo2', 'gNumber', 'iNumber'))
dataframe_1$length <- paste(split_contigs_M1R$LengthNo)

write.csv(dataframe_1, 'supp_figs/model_contigs/dataframe_1.csv', row.names = F)

#Model 2 rnaSPAdes 

read.csv('supp_figs/m2_rna_table.csv', header = F, stringsAsFactors = F) -> m2_all82_rna_table
m2_all82_rna_table[ ,c(2, 4, 7:19)] <- NULL
colnames(m2_all82_rna_table)[1:4] <- c('Cluster', 'Protein_ID' ,'evalue', 'score')
m2_all82_rna_table <- m2_all82_rna_table[which(m2_all82_rna_table$score >= 30), ]

U_Protein_ID_M2R <- as.data.frame(m2_all82_rna_table$Protein_ID)
colnames(U_Protein_ID_M2R)[1] <- 'Protein_ID'

split_names_M2R <- U_Protein_ID_M2R %>% separate(Protein_ID, into = c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'gNumber', 'iNumber', 'Protein_number'), sep = '_')

m2_all82_rna_table$Contig_ID <- paste(split_names_M2R$SRA, split_names_M2R$NodeNo, split_names_M2R$Length, split_names_M2R$LengthNo, split_names_M2R$Coverage, split_names_M2R$CoverageNo, split_names_M2R$gNumber, split_names_M2R$iNumber, sep = '_')

dataframe_2 <- U_Protein_ID_M2R <- as.data.frame(m2_all82_rna_table$Contig_ID)
colnames(dataframe_2)[1] <- 'Contig_ID'
dataframe_2 <- unique(dataframe_2)

split_contigs_M2R <- dataframe_2 %>% separate(Contig_ID, c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'CoverageNo2', 'gNumber', 'iNumber'))
dataframe_2$length <- paste(split_contigs_M2R$LengthNo)

write.csv(dataframe_2, 'supp_figs/model_contigs/dataframe_2.csv', row.names = F)

#Model 3 rnaSPAdes 

read.csv('supp_figs/m3_rna_table.csv', header = F, stringsAsFactors = F) -> m3_rna_table
m3_rna_table[ ,c(2, 4, 7:19)] <- NULL
colnames(m3_rna_table)[1:4] <- c('Cluster', 'Protein_ID' ,'evalue', 'score')
m3_rna_table <- m3_rna_table[which(m3_rna_table$score >= 30), ]

U_Protein_ID_M3R <- as.data.frame(m3_rna_table$Protein_ID)
colnames(U_Protein_ID_M3R)[1] <- 'Protein_ID'

split_names_M3R <- U_Protein_ID_M3R %>% separate(Protein_ID, into = c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'gNumber', 'iNumber', 'Protein_number'), sep = '_')

m3_rna_table$Contig_ID <- paste(split_names_M3R$SRA, split_names_M3R$NodeNo, split_names_M3R$Length, split_names_M3R$LengthNo, split_names_M3R$Coverage, split_names_M3R$CoverageNo, split_names_M3R$gNumber, split_names_M3R$iNumber, sep = '_')

dataframe_3 <- U_Protein_ID_M3R <- as.data.frame(m3_rna_table$Contig_ID)
colnames(dataframe_3)[1] <- 'Contig_ID'
dataframe_3 <- unique(dataframe_3)

split_contigs_M3R <- dataframe_3 %>% separate(Contig_ID, c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'CoverageNo3', 'gNumber', 'iNumber'))
dataframe_3$length <- paste(split_contigs_M3R$LengthNo)

write.csv(dataframe_3, 'supp_figs/model_contigs/dataframe_3.csv', row.names = F)

#Model 4 rnaSPAdes

read.csv('supp_figs/m4_rna_table.csv', header = F, stringsAsFactors = F) -> m4_rna_table
m4_rna_table[ ,c(2, 4, 7:19)] <- NULL
colnames(m4_rna_table)[1:4] <- c('Cluster', 'Protein_ID' ,'evalue', 'score')
m4_rna_table <- m4_rna_table[which(m4_rna_table$score >= 30), ]

U_Protein_ID_M4R <- as.data.frame(m4_rna_table$Protein_ID)
colnames(U_Protein_ID_M4R)[1] <- 'Protein_ID'

split_names_M4R <- U_Protein_ID_M4R %>% separate(Protein_ID, into = c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'gNumber', 'iNumber', 'Protein_number'), sep = '_')

m4_rna_table$Contig_ID <- paste(split_names_M4R$SRA, split_names_M4R$NodeNo, split_names_M4R$Length, split_names_M4R$LengthNo, split_names_M4R$Coverage, split_names_M4R$CoverageNo, split_names_M4R$gNumber, split_names_M4R$iNumber, sep = '_')

dataframe_4 <- U_Protein_ID_M4R <- as.data.frame(m4_rna_table$Contig_ID)
colnames(dataframe_4)[1] <- 'Contig_ID'
dataframe_4 <- unique(dataframe_4)

split_contigs_M4R <- dataframe_4 %>% separate(Contig_ID, c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'CoverageNo4', 'gNumber', 'iNumber'))
dataframe_4$length <- paste(split_contigs_M4R$LengthNo)

write.csv(dataframe_4, 'supp_figs/model_contigs/dataframe_4.csv', row.names = F)

#Model 5 rnaSPAdes

read.csv('supp_figs/m5_rna_table.csv', header = F, stringsAsFactors = F) -> m5_rna_table
m5_rna_table[ ,c(2, 4, 7:19)] <- NULL
colnames(m5_rna_table)[1:4] <- c('Cluster', 'Protein_ID' ,'evalue', 'score')
m5_rna_table <- m5_rna_table[which(m5_rna_table$score >= 30), ]

U_Protein_ID_M5R <- as.data.frame(m5_rna_table$Protein_ID)
colnames(U_Protein_ID_M5R)[1] <- 'Protein_ID'

split_names_M5R <- U_Protein_ID_M5R %>% separate(Protein_ID, into = c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'gNumber', 'iNumber', 'Protein_number'), sep = '_')

m5_rna_table$Contig_ID <- paste(split_names_M5R$SRA, split_names_M5R$NodeNo, split_names_M5R$Length, split_names_M5R$LengthNo, split_names_M5R$Coverage, split_names_M5R$CoverageNo, split_names_M5R$gNumber, split_names_M5R$iNumber, sep = '_')

dataframe_5 <- U_Protein_ID_M5R <- as.data.frame(m5_rna_table$Contig_ID)
colnames(dataframe_5)[1] <- 'Contig_ID'
dataframe_5 <- unique(dataframe_5)

split_contigs_M5R <- dataframe_5 %>% separate(Contig_ID, c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'CoverageNo5', 'gNumber', 'iNumber'))
dataframe_5$length <- paste(split_contigs_M5R$LengthNo)

write.csv(dataframe_5, 'supp_figs/model_contigs/dataframe_5.csv', row.names = F)

#Model 5 plus rnaSPAdes 

read.csv('supp_figs/m5_plus_rna_table.csv', header = F, stringsAsFactors = F) -> m5_plus_rna_table
m5_plus_rna_table[ ,c(2, 4, 7:19)] <- NULL
colnames(m5_plus_rna_table)[1:4] <- c('Cluster', 'Protein_ID' ,'evalue', 'score')
m5_plus_rna_table <- m5_plus_rna_table[which(m5_plus_rna_table$score >= 30), ]

U_Protein_ID_M5R_plus <- as.data.frame(m5_plus_rna_table$Protein_ID)
colnames(U_Protein_ID_M5R_plus)[1] <- 'Protein_ID'

split_names_M5R_plus <- U_Protein_ID_M5R_plus %>% separate(Protein_ID, into = c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'gNumber', 'iNumber', 'Protein_number'), sep = '_')

m5_plus_rna_table$Contig_ID <- paste(split_names_M5R_plus$SRA, split_names_M5R_plus$NodeNo, split_names_M5R_plus$Length, split_names_M5R_plus$LengthNo, split_names_M5R_plus$Coverage, split_names_M5R_plus$CoverageNo, split_names_M5R_plus$gNumber, split_names_M5R_plus$iNumber, sep = '_')

dataframe_5_plus <- U_Protein_ID_M5R_plus <- as.data.frame(m5_plus_rna_table$Contig_ID)
colnames(dataframe_5_plus)[1] <- 'Contig_ID'
dataframe_5_plus <- unique(dataframe_5_plus)

split_contigs_M5R_plus <- dataframe_5_plus %>% separate(Contig_ID, c('SRA', 'NodeNo', 'Length', 'LengthNo', 'Coverage', 'CoverageNo', 'CoverageNo5', 'gNumber', 'iNumber'))
dataframe_5_plus$length <- paste(split_contigs_M5R_plus$LengthNo)

write.csv(dataframe_5_plus, 'supp_figs/model_contigs/dataframe_5_plus.csv', row.names = F)

#Model 1 megahit

read.csv('supp_figs/m1_mh_table.csv', header = F, stringsAsFactors = F) -> m1_mh_table
m1_mh_table[ ,c(2,4,7:19)] <- NULL
colnames(m1_mh_table)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'score')

U_Protein_ID_m1_mh <- as.data.frame(m1_mh_table$Protein_ID)
colnames(U_Protein_ID_m1_mh)[1] <- 'Protein_ID'

split_names_m1_mh <- U_Protein_ID_m1_mh %>% separate(Protein_ID, c('SRA', 'Contig', 'Protein_Number'))

m1_mh_table$U_Contig_ID <- paste(split_names_m1_mh$SRA, split_names_m1_mh$Contig, sep = '_')

m1_mh_table <- m1_mh_table[which(m1_mh_table$score >= 30), ]

m1_mh_contigs_list <- as.data.frame(m1_mh_table$U_Contig_ID)

m1_mh_contigs_list <- unique(m1_mh_contigs_list)

write.csv(m1_mh_contigs_list, 'supp_figs/model_contigs/m1_mh_contigs_list.csv', row.names = F)

#Model 2 megahit

read.csv('supp_figs/m2_mh_table.csv', header = F, stringsAsFactors = F) -> m2_mh_table
m2_mh_table[ ,c(2,4,7:19)] <- NULL
colnames(m2_mh_table)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'score')

U_Protein_ID_m2_mh <- as.data.frame(m2_mh_table$Protein_ID)
colnames(U_Protein_ID_m2_mh)[1] <- 'Protein_ID'

split_names_m2_mh <- U_Protein_ID_m2_mh %>% separate(Protein_ID, c('SRA', 'Contig', 'Protein_Number'))

m2_mh_table$U_Contig_ID <- paste(split_names_m2_mh$SRA, split_names_m2_mh$Contig, sep = '_')

m2_mh_table <- m2_mh_table[which(m2_mh_table$score >= 30), ]

m2_mh_contigs_list <- as.data.frame(m2_mh_table$U_Contig_ID)

m2_mh_contigs_list <- unique(m2_mh_contigs_list)

write.csv(m2_mh_contigs_list, 'supp_figs/model_contigs/m2_mh_contigs_list.csv', row.names = F)

#Model 3 megahit

read.csv('supp_figs/m3_mh_table.csv', header = F, stringsAsFactors = F) -> m3_mh_table
m3_mh_table[ ,c(2,4,7:19)] <- NULL
colnames(m3_mh_table)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'score')

U_Protein_ID_m3_mh <- as.data.frame(m3_mh_table$Protein_ID)
colnames(U_Protein_ID_m3_mh)[1] <- 'Protein_ID'

split_names_m3_mh <- U_Protein_ID_m3_mh %>% separate(Protein_ID, c('SRA', 'Contig', 'Protein_Number'))

m3_mh_table$U_Contig_ID <- paste(split_names_m3_mh$SRA, split_names_m3_mh$Contig, sep = '_')

m3_mh_table <- m3_mh_table[which(m3_mh_table$score >= 30), ]

m3_mh_contigs_list <- as.data.frame(m3_mh_table$U_Contig_ID)

m3_mh_contigs_list <- unique(m3_mh_contigs_list)

write.csv(m3_mh_contigs_list, 'supp_figs/model_contigs/m3_mh_contigs_list.csv', row.names = F)

#Model 4 megahit

read.csv('supp_figs/m4_mh_table.csv', header = F, stringsAsFactors = F) -> m4_mh_table
m4_mh_table[ ,c(2,4,7:19)] <- NULL
colnames(m4_mh_table)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'score')

U_Protein_ID_m4_mh <- as.data.frame(m4_mh_table$Protein_ID)
colnames(U_Protein_ID_m4_mh)[1] <- 'Protein_ID'

split_names_m4_mh <- U_Protein_ID_m4_mh %>% separate(Protein_ID, c('SRA', 'Contig', 'Protein_Number'))

m4_mh_table$U_Contig_ID <- paste(split_names_m4_mh$SRA, split_names_m4_mh$Contig, sep = '_')

m4_mh_table <- m4_mh_table[which(m4_mh_table$score >= 30), ]

m4_mh_contigs_list <- as.data.frame(m4_mh_table$U_Contig_ID)

m4_mh_contigs_list <- unique(m4_mh_contigs_list)

write.csv(m4_mh_contigs_list, 'supp_figs/model_contigs/m4_mh_contigs_list.csv', row.names = F)

#Model 5 megahit

read.csv('supp_figs/m5_mh_table.csv', header = F, stringsAsFactors = F) -> m5_mh_table
m5_mh_table[ ,c(2,4,7:19)] <- NULL
colnames(m5_mh_table)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'score')

U_Protein_ID_m5_mh <- as.data.frame(m5_mh_table$Protein_ID)
colnames(U_Protein_ID_m5_mh)[1] <- 'Protein_ID'

split_names_m5_mh <- U_Protein_ID_m5_mh %>% separate(Protein_ID, c('SRA', 'Contig', 'Protein_Number'))

m5_mh_table$U_Contig_ID <- paste(split_names_m5_mh$SRA, split_names_m5_mh$Contig, sep = '_')

m5_mh_table <- m5_mh_table[which(m5_mh_table$score >= 30), ]

m5_mh_contigs_list <- as.data.frame(m5_mh_table$U_Contig_ID)

m5_mh_contigs_list <- unique(m5_mh_contigs_list)

write.csv(m5_mh_contigs_list, 'supp_figs/model_contigs/m5_mh_contigs_list.csv', row.names = F)

#Model 5 plus megahit

read.csv('supp_figs/m5_plus_mh_table.csv', header = F, stringsAsFactors = F) -> m5_plus_mh_table
m5_plus_mh_table[ ,c(2,4,7:19)] <- NULL
colnames(m5_plus_mh_table)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'score')

U_Protein_ID_m5_mh_plus <- as.data.frame(m5_plus_mh_table$Protein_ID)
colnames(U_Protein_ID_m5_mh_plus)[1] <- 'Protein_ID'

split_names_m5_mh_plus <- U_Protein_ID_m5_mh_plus %>% separate(Protein_ID, c('SRA', 'Contig', 'Protein_Number'))

m5_plus_mh_table$U_Contig_ID <- paste(split_names_m5_mh_plus$SRA, split_names_m5_mh_plus$Contig, sep = '_')

m5_plus_mh_table <- m5_plus_mh_table[which(m5_plus_mh_table$score >= 30), ]

m5_plus_mh_contigs_list <- as.data.frame(m5_plus_mh_table$U_Contig_ID)

m5_plus_mh_contigs_list <- unique(m5_plus_mh_contigs_list)

write.csv(m5_plus_mh_contigs_list, 'supp_figs/model_contigs/m5_plus_mh_contigs_list.csv', row.names = F)

#Using contig names, lengths are determined with 'seqstat' on server and
#saved to a file 'length_15611_contigs.csv' which is fed in below.

###################################################

#clean environment
rm(list = ls())

###################################################
######### Figure 1 ################################

#Linegraph of unique contigs per model ############

#Read in table of unique contigs per models and plot

read.csv('fig_1/unique_contigHits_perModel_linegraph.csv', header = T, stringsAsFactors = F) -> linegraph_contigs

#Graph of unique contigs per model as linegraph 

contigs_linegraph <- ggplot(linegraph_contigs, aes(x = linegraph_contigs$Model_No, y = linegraph_contigs$No_contigs, group = 1)) +
  geom_line(stat = 'identity') +
  geom_point(colour = c('HMM Model 1' = "#A6CEE3",
                        'HMM Model 2' = "#1F78B4",
                        'HMM Model 3' = "#B2DF8A",
                        'HMM Model 4' = "#33A02C",
                        'HMM Model 5' = "#FB9A99",
                        'HMM Model plus'='#905CC4'),
             size = 5) +
  theme_classic() +
  theme(legend.position = 'none') +
  labs(x = '', y = 'Number of contigs') +
  scale_x_discrete(labels = c('HMM Model 1'='1',
                              'HMM Model 2'='2',
                              'HMM Model 3'='3',
                              'HMM Model 4'='4',
                              'HMM Model 5'='5',
                              'HMM Model plus'='5-MC')) +
  theme(axis.text.x = element_text(size = rel(0.8)), axis.title.y = element_text(size = rel(0.8), angle = 90)) +
  ggtitle('A') +
  ylim(12500,19000) +
  NULL
contigs_linegraph

###################################################
#Raincloud: Contig Lengths of HMM 5-plus ##########

read.csv('fig_1/length_15611_contigs.csv', header = T, stringsAsFactors = F) -> length_15611_contigs_tbl

length_15611_contigs_tbl$length <- 'length'
length_15611_contigs_tbl_melt <- melt(length_15611_contigs_tbl, id.vars = c('length'))
length_15611_contigs_tbl_melt$value <- as.numeric(as.character(length_15611_contigs_tbl_melt$value))
length_15611_contigs_tbl_melt <- length_15611_contigs_tbl_melt[which(length_15611_contigs_tbl_melt$value > 0), ]

source("https://gist.githubusercontent.com/benmarwick/2a1bb0133ff568cbe28d/raw/fb53bd97121f7f9ce947837ef1a4c65a73bffb3f/geom_flat_violin.R")

raincloud_plot_m5plus <- ggplot(length_15611_contigs_tbl_melt, aes(x = length_15611_contigs_tbl_melt$variable, y = length_15611_contigs_tbl_melt$value, color = length_15611_contigs_tbl_melt$variable)) +
  geom_flat_violin(aes(fill = length_15611_contigs_tbl_melt$variable), position = position_nudge(x = .2, y = 0), alpha = .8) +
  geom_point(aes(y = length_15611_contigs_tbl_melt$value, color = length_15611_contigs_tbl_melt$variable), position = position_jitter(width = .15), size = .5, alpha = 0.8) +
  geom_boxplot(width = .1, guides = FALSE, outlier.shape = NA,  alpha = 0.5, colour = '#6b7b88') +
  labs(x = '', y = 'Contig length (bp)') +
  guides(fill = FALSE) +
  guides(color = FALSE) +
  scale_color_manual(values = '#905CC4') +
  scale_fill_manual(values = '#905CC4') +
  theme_classic() +
  theme(axis.text.x = element_text()) +
  scale_x_discrete(labels = c('M_len' = '5-MC\n (18,120)')) +
  ggtitle('B') +
  NULL
raincloud_plot_m5plus

###################################################
#Length vs coverage of contigs from Model 5 #######

minlen <- read.csv('fig_1/len_v_cov.csv', header = T, stringsAsFactors = F)

minlen$Factor <- as.factor(minlen$Factor)

minlen <- minlen[order(minlen$Length, decreasing = T), ]

colrs <- brewer.pal(4, 'Spectral')

cov_len <- ggplot(minlen, aes(minlen$Length, minlen$Coverage)) + 
  geom_point(aes(color = minlen$Factor, alpha = 0.75)) +
  geom_smooth(method = 'lm', se = T, color = 'black') +
  scale_y_log10() +
  theme_classic() +
  scale_color_manual(values = colrs,
                     breaks = c('1', '2', '3', '4'),
                     labels = c('Three core proteins\n(all complete)', 'Three core proteins', 'Two core proteins', 'One core protein')) +
  xlab('Contig length (bp)') +
  ylab('Coverage') +
  theme(legend.position="right") +
  guides(colour = guide_legend('', ncol = 1, byrow = F)) +
  scale_alpha(guide = 'none') +
  ggtitle('E') +
  NULL
cov_len

###################################################
#Pirate plot: Contigs per Study Location image ####
#Contigs encoding a protein of interest (nr at 100%) and a min length of 750bp

read.csv('fig_1/study_location_table_5387.csv', header = T, stringsAsFactors = T) -> contigs_per_sra_5387_table

shapiro.test(contigs_per_sra_5387_table$Freq)
kruskal.test(Freq ~ Location, data = contigs_per_sra_5387_table)
#p-value: 1.847e-06

#geom_pirate script:

pirate2 <- ggplot(contigs_per_sra_5387_table, aes(x = contigs_per_sra_5387_table$Location, y = contigs_per_sra_5387_table$Freq, fill = contigs_per_sra_5387_table$Location)) +
  geom_pirate(aes(colour = Location, fill = Location), show.legend = F,
              cis_params = list(fill = "white", size = 0.5, alpha = 0.5, width = 0.7),
              violins_params = list(fill = 'grey80', size = 0.8, alpha = 0.5, width = 1),
              jitter_width = 0.4,
              points_params = list(shape = 16, size = 1, alpha  = 0.5),
              bars_params = list(alpha = 0.2, width = 0.9),
              lines_params = list(size = 0.5, width = 0.9)) +
  xlab('') +
  ylab('Contigs detected per assembly') +
  theme_classic() +
  ggtitle('C') +
  scale_x_discrete(labels = c('Activated sludge' = 'Activated sludge\n(n = 70)',
                              'Aquatic' = 'Aquatic\n(n = 12)'))
pirate2

###################################################
#PCOA plot ########################################

rd_cnt <- read.csv('fig_1/m5plus_read_count_matrix.csv', header = T, stringsAsFactors = F, row.names = 1)

metadata <- read.csv('fig_1/sra_sample_list.csv', header = T, stringsAsFactors = F)

otu_reads <- otu_table(t(rd_cnt), taxa_are_rows = F)

sample_names(otu_reads)

rownames(metadata) <- metadata$SRA_accession
sample_metadata <- sample_data(metadata)

sample_names(sample_metadata)

phyloseq_with_metadata <- phyloseq(otu_reads, sample_metadata)

dist_methods <- c("canberra", "bray", "jaccard")

plist <- vector("list", length(dist_methods))
names(plist) = dist_methods
for( i in dist_methods ){
  # Calculate distance matrix
  iDist <- vegan::vegdist(otu_reads, method=i)
  # Calculate ordination
  iPCoA  <- ordinate(phyloseq_with_metadata, "PCoA", distance = iDist)
  ## Make plot
  # Don't carry over previous plot (if error, p will be blank)
  p <- NULL
  # Create plot, store as temp variable, p
  p <- plot_ordination(phyloseq_with_metadata, iPCoA, color="Location") 
  # Add title to each plot
  p <- p + ggtitle(paste("PCoA using distance method ", i, sep=""))
  # Save the graphic to file.
  plist[[i]] = p
}

df = ldply(plist, function(x) x$data)
names(df)[1] <- "distance"
p = ggplot(df, aes(x = Axis.1, y = Axis.2, color=Location))
p = p + geom_point(size=3, alpha=0.5) + stat_ellipse(aes(group = Location)) + theme_minimal(base_size = 10)
p = p + facet_wrap(~distance, scales="free")
p = p + ggtitle("PCoA using various distance metrics for Location within dataset")
p

bray_plot_data <- df[df$distance == 'bray', ]

bray_dist_adonis <- vegan::vegdist(otu_reads, method = 'bray')

set.seed(1)
adonis(bray_dist_adonis ~ Location, bray_plot_data)

### For phage analysis: R^2 = 36.858% (0.36858) of data explained by Location, p-value = 0.001

princomp(bray_plot_data$Axis.1)
princomp(bray_plot_data$Axis.2)

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

n = 6
cols = gg_color_hue(n)

pcoa_plot <- ggplot(bray_plot_data, aes(x = Axis.1, y = Axis.2)) +
  geom_point(aes(color = Location, shape = Sample)) + 
  stat_ellipse(geom = 'polygon', alpha = 0.25, aes(fill = Location)) + 
  theme_classic() + 
  scale_fill_manual(values=c("Austria" = "#B79F00",
                             "Illinois" = "#F564E3",
                             "Japan" = "#00BA38",
                             "Singapore" = "#00BFC4",
                             "Lake_Mississippi" = "#8A2BE2",
                             "Lake_Mendota" = "#F8766D")) +
  scale_color_manual(values=c("Austria" = "#B79F00",
                             "Illinois" = "#F564E3",
                             "Japan" = "#00BA38",
                             "Singapore" = "#00BFC4",
                             "Lake_Mississippi" = "#8A2BE2",
                             "Lake_Mendota" = "#F8766D")) +
  labs(x = 'PC1 (28.31%)', y = 'PC2 (19.51%)') + 
  labs(title = 'D', subtitle = 'PERMANOVA: R^2 = 0.36858, p-value = 0.001') +
  guides(shape = F) +
  NULL
pcoa_plot

#Grid.arrange figure 1 ############################

#pdf('Figure_1.pdf', paper = 'A4', width = 20, height = 29.7)
grid.arrange(contigs_linegraph, raincloud_plot_m5plus, pirate2, pcoa_plot, cov_len,
                           layout_matrix = rbind(c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5),
                                                 c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5)))

#dev.off()

###################################################

#Clean environment
rm(list = ls())

###################################################
######### Figure 2 #########

#Functional hit in Model 5 #####

read.csv('fig_2/HMM_M5_plus_vs_all82.csv', header = F, stringsAsFactors = F) -> m5_plus_function_table

m5_plus_function_table[ ,c(2, 4, 7:19)] <- NULL

colnames(m5_plus_function_table)[1:4] <- c('Specific_Fun','Protein_ID', 'evalue', 'score')

m5_plus_function_table_30 <- m5_plus_function_table[which(m5_plus_function_table$score >= 30), ]

m5_plus_function_table_30_remDups <- m5_plus_function_table_30[!duplicated(m5_plus_function_table_30$Protein_ID), ]

#write.csv(m5_plus_function_table_30_remDups, 'm5_plus_function_table_30_remProteinDups.csv', row.names = F)

read.csv('fig_2/nr_function_contigs_hits.csv', header = T, stringsAsFactors = F) -> nr_function_hits_table

nr_function_hits_table <- nr_function_hits_table[order(nr_function_hits_table$Percent_hit, decreasing = F) , ]

nr_function_hits_table$Protein <- factor(nr_function_hits_table$Protein, levels = nr_function_hits_table$Protein[order(nr_function_hits_table$Percent_hit, decreasing = F)])

#cols8 <- brewer.pal(n = 8, 'Accent')
#cols5 <- brewer.pal(n = 12, 'Paired')

nr_function_graph <- ggplot(nr_function_hits_table, aes(x = nr_function_hits_table$No_protein, y = nr_function_hits_table$Percent_hit, fill = nr_function_hits_table$Protein)) +
  geom_bar(stat = 'identity', position = 'stack', colour = 'black') +
  theme(plot.title = element_text(face = 'bold')) +
  theme_classic() +
  labs(x = '', y = 'Distribution of protein clusters (%)') +
  scale_fill_manual(values = c( 'MP B' = '#7570B3', 
                                'MP A' = '#33A02C',
                                'MP C' = '#E41A1C',
                                'CP E' = '#386CB0',
                                'CP G' = '#BF5B17',
                                'CP D' = '#FFFF99',
                                'CP F' = '#F0027F',
                                'CP A' = '#7FC97F',
                                'CP B' = '#BEAED4',
                                'CP H' = '#666666',
                                'CP C' = '#FDC086',
                                'RdRp A' = '#A6CEE3',
                                'RdRp B' = '#FF7F00'),
                    breaks = c('MP A'  ,
                               'MP B' ,
                               'MP C' ,
                               'CP A' ,
                               'CP B' ,
                               'CP C' ,
                               'CP D' ,
                               'CP E' ,
                               'CP F' ,
                               'CP G' ,
                               'CP H' ,
                               'RdRp A',
                               'RdRp B')) + 
  scale_x_discrete(labels = c('A_MP' = 'MP\n(8,057)', 'CP' = 'CP\n(5,313)', 'RdRp' = 'RdRp\n(11,049)')) +
  theme(legend.position="bottom") +
  guides(fill = guide_legend('Protein cluster:', ncol = 8, byrow = F)) +
  ggtitle('A') +
  NULL 
nr_function_graph

###################################################
#Network image ####

hmm_m5_output <- read.csv('fig_2/hmmScan_m5_score30_withGenomeIDs.csv', header = T, stringsAsFactors = F)

hmm_m5_output <- hmm_m5_output[order(hmm_m5_output$HMM_score, decreasing = T), ]

hmm_m5_output <- hmm_m5_output[!duplicated(hmm_m5_output$Protein_ID), ]

nr <- as.data.frame(stringr::str_split_fixed(hmm_m5_output$HMM_cluster, '_', 2))

hmm_m5_output$nr <- paste(hmm_m5_output$Genome_ID, nr$V1, sep = '_')

hmm_m5_output <- hmm_m5_output[!duplicated(hmm_m5_output$nr), ]

#remove contigs less than 750bp

minlen_contigs <- read.csv('fig_2/minlen_contigIDs.csv', header = F, stringsAsFactors = F)

minlen_list <- minlen_contigs$V1

hmm_m5_output_minlen <- hmm_m5_output[which(hmm_m5_output$Genome_ID %in% minlen_list), ]

#with 2 or more proteins

hmm_m5_output <- hmm_m5_output_minlen[hmm_m5_output_minlen$Genome_ID %in% unique(hmm_m5_output_minlen$Genome_ID[duplicated(hmm_m5_output_minlen$Genome_ID)]),]

hmm_m5 <- hmm_m5_output[,c(1,2)]

col_df <- hmm_m5[which(hmm_m5$HMM_cluster != 'MP_A'), ]
col_df <- col_df[which(col_df$HMM_cluster != 'MP_B'), ]
col_df <- col_df[which(col_df$HMM_cluster != 'MP_C'), ]
col_df <- col_df[which(col_df$HMM_cluster != 'RdRp_A'), ]
col_df <- col_df[which(col_df$HMM_cluster != 'RdRp_B'), ]

col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_A", replacement = "#7FC97F")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_B", replacement = "#BEAED4")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_C", replacement = "#FDC086")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_D", replacement = "#FFFF99")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_E", replacement = "#386CB0")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_F", replacement = "#F0027F")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_G", replacement = "#BF5B17")
col_df$HMM_cluster <- gsub(x = col_df$HMM_cluster, pattern = "CP_H", replacement = "#666666")

colnames(col_df)[2] <- 'Colours'

contigs_df <- hmm_m5

contigs_df <- merge(contigs_df, col_df, by = 'Genome_ID', all = T)

contigs_df$Colours[is.na(contigs_df$Colours)] <- NA

contigs_df <- contigs_df[,c(1,2,3)]

contigs_df$HMM_cluster <- as.factor(contigs_df$HMM_cluster)

library(igraph)

vert <- contigs_df[order(contigs_df$HMM_cluster), ]

vert2 <- vert

vert2 <- vert[,c(2,1, 3)]

colnames(vert2)[1:2] <- c('Genome_ID', 'HMM_cluster')

vert2$HMM_cluster <- NA
vert2$Colours <- "#6ed3cf"

vert <- rbind(vert, vert2)

vert <- vert[!duplicated(vert$Genome_ID), ]
g <- graph.data.frame(contigs_df, vertices = vert, directed = F)

bipartite.mapping(g)

V(g)$type <- bipartite_mapping(g)$type

deg <- degree(g, mode = 'in')

head(deg, n = 13)

V(g)$frame.color <- NA
V(g)$shape <- ifelse(V(g)$type, "square", "circle")
E(g)$color <- "grey90"

l <- layout.fruchterman.reingold(g, niter = 50000)

#pdf('all_contigs_two_prot.pdf')
set.seed(1)
plot(g, vertex.label = ifelse(degree(g) > 9, V(g)$name, NA), vertex.label.color = 'black', vertex.label.font = 2, vertex.size = ifelse(degree(g) > 9, 2*log10(deg*0.1), deg*1.1), edge.color = E(g)$Colours, vertex.color = V(g)$Colours, layout = l)
#dev.off()

###################################################
#Sankey diagram of genomes with 3 core proteins #####

genomes_core <- read.csv('fig_2/Genome_HmmHits_with2orMoreProteins.csv', header = T, stringsAsFactors = F)

complete_genomes <- read.csv('fig_2/list_noEdgeProteins_1015seqs.csv', header = F, stringsAsFactors = F)
colnames(complete_genomes)[1] <- 'Genome_ID'

complete_genomes_prot <- merge(complete_genomes, genomes_core, all.x = T)

#write.csv(complete_genomes_prot, 'complete_genomes_proteins_1015.csv', row.names = F)

#Feed in nodes (not labelled as this will be added manually at later stage)
nodes = data.frame('name' = c('','','','','','','','','','','','','','','','','','',''))

#nodes = data.frame('name' = c('MP_A','MP_B','MP_C', 'CP_A','CP_B','CP_C','CP_D','CP_E','CP_F','CP_G','CP_H','RdRp_A','RdRp_B')) #labels are turned off for aesthetics purpose

#Feed in links between nodes (no. of connections between each connection profile)

links = as.data.frame(matrix(c(0,3,352,
                               0,4,173,
                               0,5,108,
                               0,9,73,
                               0,10,31,
                               1,6,122,
                               1,8,125,
                               2,7,31,
                               3,11,352,
                               4,11,173,
                               5,11,108,
                               9,11,73,
                               10,11,31,
                               6,12,122,
                               8,12,125,
                               7,12,31), byrow = T, ncol = 3))

names(links) = c('source', 'target', 'value')

new_df <- list(nodes = nodes, links = links)

sankeyNetwork(Links = new_df$links, Nodes = new_df$nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name', fontSize = 10, nodeWidth = 50)

###################################################

#Clean environment
rm(list = ls())

###################################################
######### Figure 3 ################################
#Phylogenetic tree of concatonated genomes ########

treeBS <- read.tree('fig_3/bootstrap_concat_aln_tree_BS100_1044seqs.tre')
metadata <- read.csv('fig_3/taxonomic_table_orthoMCL_and_SDT.csv', header = T, stringsAsFactors = T)

tree <- rotate(treeBS, 1990) %>% rotate(2021)

p1 <- ggtree(tree, layout = 'fan')

p2 <- flip(p1, 2021, 1990)

p3 <- flip(p2, 1048, 1083)

p4 <- flip(p3, 1084, 1201)

p5 <- flip(p4, 1561, 1286)

p6 <- flip(p5, 1526, 1529)

p7 <- flip(p6, 1677, 1285)

p8 <- flip(p7, 1421, 1391)

p9 <- flip(p8, 1425, 1422)

col <- brewer.pal(8, 'Accent')

tree_plot <- p9 %<+% metadata + 
  geom_tippoint(aes(color = Subfamily, shape = Family), alpha = 0.8, size = 3) +
  theme(legend.position = 'right') +
  scale_color_manual(breaks = c('CP_A',
                                'CP_B',
                                'CP_C',
                                'CP_D',
                                'CP_E',
                                'CP_F',
                                'CP_G',
                                'CP_H'),
                     values = col) +
  NULL
tree_plot

known_levi <- read.csv('fig_3/prevKnown_RNAphage_info.csv', header = T, stringsAsFactors = T)

metadata_heatmap <- merge(metadata, known_levi, by = 'Genome_ID', all.x = T)

rownames(metadata_heatmap) <- metadata_heatmap$Genome_ID
metadata_heatmap$Genome_ID <- ''
metadata_heatmap <- as.data.frame(metadata_heatmap[,-c(2:5,7)])

#pdf('heatmap_1044.pdf', paper = 'A4r', width = 29.7, height = 20)
gheatmap(tree_plot, metadata_heatmap, width = 0.1, colnames = F) + 
  theme(legend.position = 'right') + 
  scale_fill_manual(breaks = c('Allolevivirus', 'Levivirus', 'Unclassified'),
                    values = c('Allolevivirus' = '#ff0000',
                               'Levivirus' = '#2ad4ff',
                               'Unclassified' = '#9921ff'),
                    name = 'Prior taxonomy') +
  NULL
#dev.off()

###################################################

#Clean environment
rm(list = ls())

###################################################
######### Supplementary figures #########
#Raincloud: Contig Length Analysis per model #####

read.csv('supp_figs/model_contigs/dataframe_1.csv', header = T, stringsAsFactors = F) -> df_model1_table
colnames(df_model1_table)[1:2] <- c('M_name', 'M_len')

read.csv('supp_figs/model_contigs/dataframe_2.csv', header = T, stringsAsFactors = F) -> df_model2_table
colnames(df_model2_table)[1:2] <- c('M_name', 'M_len')

read.csv('supp_figs/model_contigs/dataframe_3.csv', header = T, stringsAsFactors = F) -> df_model3_table
colnames(df_model3_table)[1:2] <- c('M_name', 'M_len')

read.csv('supp_figs/model_contigs/dataframe_4.csv', header = T, stringsAsFactors = F) -> df_model4_table
colnames(df_model4_table)[1:2] <- c('M_name', 'M_len')

read.csv('supp_figs/model_contigs/dataframe_5.csv', header = T, stringsAsFactors = F) -> df_model5_table
colnames(df_model5_table)[1:2] <- c('M_name', 'M_len')

read.csv('supp_figs/model_contigs/dataframe_5_plus.csv', header = T, stringsAsFactors = F) -> df_model5_plus_table
colnames(df_model5_plus_table)[1:2] <- c('M_name', 'M_len')

#Identify unique contigs per iteration
#m1 vs m2

m_list <- df_model1_table$M_name
m2_overlap_m1 <- df_model2_table[ ! df_model2_table$M_name %in% m_list, ]

#m1, m2 vs m3

m1_and_2_df <- rbind(df_model1_table, df_model2_table)
m1_and_2_df <- unique(m1_and_2_df)
m_list_2 <- m1_and_2_df$M_name
m3_overlap_m1m2 <- df_model3_table[ ! df_model3_table$M_name %in% m_list_2, ]

#m1, m2, m3 vs m4

m1_2_and_3_df <- rbind(df_model1_table, df_model2_table, df_model3_table)
m1_2_and_3_df <- unique(m1_2_and_3_df)
m_list_3 <- m1_2_and_3_df$M_name
m4_overlap_m1m2m3 <- df_model4_table[ ! df_model4_table$M_name %in% m_list_3, ]

#m1, m2, m3, m4 vs m5

m1_2_3_and_4_df <- rbind(df_model1_table, df_model2_table, df_model3_table, df_model4_table)
m1_2_3_and_4_df <- unique(m1_2_3_and_4_df)
m_list_4 <- m1_2_3_and_4_df$M_name
m5_overlap_m1m2m3m4 <- df_model5_table[ ! df_model5_table$M_name %in% m_list_4, ]

write.csv(m2_overlap_m1, 'supp_figs/model_contigs/unique_contigs_between_models/m2_not_in_m1.csv', row.names = F)
write.csv(m3_overlap_m1m2, 'supp_figs/model_contigs/unique_contigs_between_models/m3_not_in_m1m2.csv', row.names = F)
write.csv(m4_overlap_m1m2m3, 'supp_figs/model_contigs/unique_contigs_between_models/m4_not_in_m1m2m3.csv', row.names = F)
write.csv(m5_overlap_m1m2m3m4, 'supp_figs/model_contigs/unique_contigs_between_models/m5_not_in_m1m2m3m4.csv', row.names = F)

#paste the tables together and read back in.

read.csv('supp_figs/model_contigs/unique_contigs_between_models/unique_contigs_per_model.csv', header = T, stringsAsFactors = F) -> unique_contigs_per_model_table

unique_contigs_per_model_table[is.na(unique_contigs_per_model_table)] <- '0'
unique_contigs_per_model_table$length <- 'length'
unique_contigs_melt <- melt(unique_contigs_per_model_table, id.vars = c('length'))
unique_contigs_melt$value <- as.numeric(as.character(unique_contigs_melt$value))
unique_contigs_melt <- unique_contigs_melt[which(unique_contigs_melt$value > 0), ]

source("https://gist.githubusercontent.com/benmarwick/2a1bb0133ff568cbe28d/raw/fb53bd97121f7f9ce947837ef1a4c65a73bffb3f/geom_flat_violin.R")

raincloud_plot <- ggplot(unique_contigs_melt, aes(x = unique_contigs_melt$variable, y = unique_contigs_melt$value, color = unique_contigs_melt$variable)) +
  geom_flat_violin(aes(fill = unique_contigs_melt$variable), position = position_nudge(x = .2, y = 0), alpha = .8) +
  geom_point(aes(y = unique_contigs_melt$value, color = unique_contigs_melt$variable), position = position_jitter(width = .15), size = .5, alpha = 0.8) +
  geom_boxplot(width = .1, guides = FALSE, outlier.shape = NA,  alpha = 0.5, colour = '#6b7b88') +
  labs(x = 'Cumulative (additional) contigs per HMM iteration', y = 'Contig length (bp)') +
  expand_limits(x = 4) +
  guides(fill = FALSE) +
  guides(color = FALSE) +
  scale_color_manual(values = c('M1' = "#A6CEE3",
                       'M2' = "#1F78B4",
                       'M3' = "#B2DF8A",
                       'M4' = "#33A02C",
                       'M5' = "#FB9A99",
                       'M5_plus'='#905CC4')) +
  scale_fill_manual(values = c('M1' = "#A6CEE3",
                      'M2' = "#1F78B4",
                      'M3' = "#B2DF8A",
                      'M4' = "#33A02C",
                      'M5' = "#FB9A99",
                      'M5_plus'='#905CC4')) +
  theme_classic() +
  theme(axis.text.x = element_text()) +
  scale_x_discrete(labels = c('M1' = '1\n (13,557)',  'M2' = '2\n(+3,339)', 'M3' = '3\n (+1,914)', 'M4' = '4\n (+294)', 'M5' = '5\n (+128)', 'M5_plus' = '5-MC\n (18,120)')) +
  NULL
raincloud_plot

#pdf('all_hmm_models_raincloud_plot.pdf', paper = 'A4', width = 20, height = 29.7)
raincloud_plot
#dev.off()

###################################################
#Richness plot ####################################

m1 <- read.csv('supp_figs/species_richness/m1_read_count_matrix.csv', header = T, stringsAsFactors = F)

m5plus <- read.csv('supp_figs/species_richness/m5plus_read_count_matrix.csv', header = T, stringsAsFactors = F)

sra_list <- read.csv('supp_figs/species_richness/sra_list.csv', header = T, stringsAsFactors = F)

austria        <-   sra_list$SRA_accession[which(sra_list$Location == 'Austria')]
illinois       <-   sra_list$SRA_accession[which(sra_list$Location == 'Illinois')]
japan          <-   sra_list$SRA_accession[which(sra_list$Location == 'Japan')]
singapore      <-   sra_list$SRA_accession[which(sra_list$Location == 'Singapore')]
mississippi    <-   sra_list$SRA_accession[which(sra_list$Location == 'Lake_Mississippi')]
mendota        <-   sra_list$SRA_accession[which(sra_list$Location == 'Lake_Mendota')]

### m1

m1_aus <- m1[, which(names(m1) %in% austria)]
m1_ill <- m1[, which(names(m1) %in% illinois)]
m1_jap <- m1[, which(names(m1) %in% japan)]
m1_sin <- m1[, which(names(m1) %in% singapore)]
m1_mis <- m1[, which(names(m1) %in% mississippi)]
m1_men <- m1[, which(names(m1) %in% mendota)]

### m5plus

m5plus_aus <- m5plus[, which(names(m5plus) %in% austria)]
m5plus_ill <- m5plus[, which(names(m5plus) %in% illinois)]
m5plus_jap <- m5plus[, which(names(m5plus) %in% japan)]
m5plus_sin <- m5plus[, which(names(m5plus) %in% singapore)]
m5plus_mis <- m5plus[, which(names(m5plus) %in% mississippi)]
m5plus_men <- m5plus[, which(names(m5plus) %in% mendota)]

### Species on x axis

m1_aus <- as.data.frame(t(m1_aus))
m1_ill <- as.data.frame(t(m1_ill))
m1_jap <- as.data.frame(t(m1_jap))
m1_sin <- as.data.frame(t(m1_sin))
m1_mis <- as.data.frame(t(m1_mis))
m1_men <- as.data.frame(t(m1_men))
m5plus_aus <- as.data.frame(t(m5plus_aus))
m5plus_ill <- as.data.frame(t(m5plus_ill))
m5plus_jap <- as.data.frame(t(m5plus_jap))
m5plus_sin <- as.data.frame(t(m5plus_sin))
m5plus_mis <- as.data.frame(t(m5plus_mis))
m5plus_men <- as.data.frame(t(m5plus_men))

### Margalef's index

m1_aus_n      <- apply(m1_aus[,] > 0, 1, sum)
m1_ill_n      <- apply(m1_ill[,] > 0, 1, sum)
m1_jap_n      <- apply(m1_jap[,] > 0, 1, sum)
m1_sin_n      <- apply(m1_sin[,] > 0, 1, sum)
m1_mis_n      <- apply(m1_mis[,] > 0, 1, sum)
m1_men_n      <- apply(m1_men[,] > 0, 1, sum)
m5plus_aus_n  <- apply(m5plus_aus[,] > 0, 1, sum)    
m5plus_ill_n  <- apply(m5plus_ill[,] > 0, 1, sum)    
m5plus_jap_n  <- apply(m5plus_jap[,] > 0, 1, sum)    
m5plus_sin_n  <- apply(m5plus_sin[,] > 0, 1, sum)    
m5plus_mis_n  <- apply(m5plus_mis[,] > 0, 1, sum)    
m5plus_men_n  <- apply(m5plus_men[,] > 0, 1, sum)

m1_aus_N      <- apply(m1_aus[,], 1, sum)
m1_ill_N      <- apply(m1_ill[,], 1, sum)
m1_jap_N      <- apply(m1_jap[,], 1, sum)
m1_sin_N      <- apply(m1_sin[,], 1, sum)
m1_mis_N      <- apply(m1_mis[,], 1, sum)
m1_men_N      <- apply(m1_men[,], 1, sum)
m5plus_aus_N  <- apply(m5plus_aus[,], 1, sum)
m5plus_ill_N  <- apply(m5plus_ill[,], 1, sum)
m5plus_jap_N  <- apply(m5plus_jap[,], 1, sum)
m5plus_sin_N  <- apply(m5plus_sin[,], 1, sum)
m5plus_mis_N  <- apply(m5plus_mis[,], 1, sum)
m5plus_men_N  <- apply(m5plus_men[,], 1, sum)

m1_aus_Margalefs      <-   (m1_aus_n     - 1) / log(m1_aus_N    )
m1_ill_Margalefs      <-   (m1_ill_n     - 1) / log(m1_ill_N    )
m1_jap_Margalefs      <-   (m1_jap_n     - 1) / log(m1_jap_N    )
m1_sin_Margalefs      <-   (m1_sin_n     - 1) / log(m1_sin_N    )
m1_mis_Margalefs      <-   (m1_mis_n     - 1) / log(m1_mis_N    )
m1_men_Margalefs      <-   (m1_men_n     - 1) / log(m1_men_N    )
m5plus_aus_Margalefs  <-   (m5plus_aus_n - 1) / log(m5plus_aus_N)
m5plus_ill_Margalefs  <-   (m5plus_ill_n - 1) / log(m5plus_ill_N)
m5plus_jap_Margalefs  <-   (m5plus_jap_n - 1) / log(m5plus_jap_N)
m5plus_sin_Margalefs  <-   (m5plus_sin_n - 1) / log(m5plus_sin_N)
m5plus_mis_Margalefs  <-   (m5plus_mis_n - 1) / log(m5plus_mis_N)
m5plus_men_Margalefs  <-   (m5plus_men_n - 1) / log(m5plus_men_N)

### Prepare richness for plotting

df_m1_aus_Margalefs      <- as.data.frame(m1_aus_Margalefs    )
df_m1_ill_Margalefs      <- as.data.frame(m1_ill_Margalefs    )
df_m1_jap_Margalefs      <- as.data.frame(m1_jap_Margalefs    )
df_m1_sin_Margalefs      <- as.data.frame(m1_sin_Margalefs    )
df_m1_mis_Margalefs      <- as.data.frame(m1_mis_Margalefs    )
df_m1_men_Margalefs      <- as.data.frame(m1_men_Margalefs    )
df_m5plus_aus_Margalefs  <- as.data.frame(m5plus_aus_Margalefs)
df_m5plus_ill_Margalefs  <- as.data.frame(m5plus_ill_Margalefs)
df_m5plus_jap_Margalefs  <- as.data.frame(m5plus_jap_Margalefs)
df_m5plus_sin_Margalefs  <- as.data.frame(m5plus_sin_Margalefs)
df_m5plus_mis_Margalefs  <- as.data.frame(m5plus_mis_Margalefs)
df_m5plus_men_Margalefs  <- as.data.frame(m5plus_men_Margalefs)

df_m1_aus_Margalefs    $SRR  <-  rownames(df_m1_aus_Margalefs    ) 
df_m1_ill_Margalefs    $SRR  <-  rownames(df_m1_ill_Margalefs    )
df_m1_jap_Margalefs    $SRR  <-  rownames(df_m1_jap_Margalefs    )
df_m1_sin_Margalefs    $SRR  <-  rownames(df_m1_sin_Margalefs    )
df_m1_mis_Margalefs    $SRR  <-  rownames(df_m1_mis_Margalefs    )
df_m1_men_Margalefs    $SRR  <-  rownames(df_m1_men_Margalefs    )
df_m5plus_aus_Margalefs$SRR  <-  rownames(df_m5plus_aus_Margalefs)
df_m5plus_ill_Margalefs$SRR  <-  rownames(df_m5plus_ill_Margalefs)
df_m5plus_jap_Margalefs$SRR  <-  rownames(df_m5plus_jap_Margalefs)
df_m5plus_sin_Margalefs$SRR  <-  rownames(df_m5plus_sin_Margalefs)
df_m5plus_mis_Margalefs$SRR  <-  rownames(df_m5plus_mis_Margalefs)
df_m5plus_men_Margalefs$SRR  <-  rownames(df_m5plus_men_Margalefs)

rownames(df_m1_aus_Margalefs    ) <-  NULL
rownames(df_m1_ill_Margalefs    ) <-  NULL
rownames(df_m1_jap_Margalefs    ) <-  NULL
rownames(df_m1_sin_Margalefs    ) <-  NULL
rownames(df_m1_mis_Margalefs    ) <-  NULL
rownames(df_m1_men_Margalefs    ) <-  NULL
rownames(df_m5plus_aus_Margalefs) <-  NULL
rownames(df_m5plus_ill_Margalefs) <-  NULL
rownames(df_m5plus_jap_Margalefs) <-  NULL
rownames(df_m5plus_sin_Margalefs) <-  NULL
rownames(df_m5plus_mis_Margalefs) <-  NULL
rownames(df_m5plus_men_Margalefs) <-  NULL

Margalefs_m1 <- merge(df_m1_aus_Margalefs, df_m1_ill_Margalefs, by = 'SRR', all = T)
Margalefs_m1 <- merge(Margalefs_m1, df_m1_jap_Margalefs, by = 'SRR', all = T)
Margalefs_m1 <- merge(Margalefs_m1, df_m1_sin_Margalefs, by = 'SRR', all = T)
Margalefs_m1 <- merge(Margalefs_m1, df_m1_mis_Margalefs, by = 'SRR', all = T)
Margalefs_m1 <- merge(Margalefs_m1, df_m1_men_Margalefs, by = 'SRR', all = T)

Margalefs_m5plus <- merge(df_m5plus_aus_Margalefs, df_m5plus_ill_Margalefs, by = 'SRR', all = T)
Margalefs_m5plus <- merge(Margalefs_m5plus, df_m5plus_jap_Margalefs, by = 'SRR', all = T)
Margalefs_m5plus <- merge(Margalefs_m5plus, df_m5plus_sin_Margalefs, by = 'SRR', all = T)
Margalefs_m5plus <- merge(Margalefs_m5plus, df_m5plus_mis_Margalefs, by = 'SRR', all = T)
Margalefs_m5plus <- merge(Margalefs_m5plus, df_m5plus_men_Margalefs, by = 'SRR', all = T)

Margalefs_m1_combine <- Margalefs_m1 %>% mutate(Richness = dplyr::coalesce(m1_aus_Margalefs,
                                                                           m1_ill_Margalefs,
                                                                           m1_jap_Margalefs,
                                                                           m1_sin_Margalefs,
                                                                           m1_mis_Margalefs,
                                                                           m1_men_Margalefs)) %>% select(SRR, Richness)
Margalefs_m1_combine$Model <- 'HMM1'

Margalefs_m5plus_combine <- Margalefs_m5plus %>% mutate(Richness = dplyr::coalesce(m5plus_aus_Margalefs,
                                                                                   m5plus_ill_Margalefs,
                                                                                   m5plus_jap_Margalefs,
                                                                                   m5plus_sin_Margalefs,
                                                                                   m5plus_mis_Margalefs,
                                                                                   m5plus_men_Margalefs)) %>% select(SRR, Richness)
Margalefs_m5plus_combine$Model <- 'HMM5-plus'

Margalef_final <- rbind(Margalefs_m1_combine, Margalefs_m5plus_combine)

### Plot richness

paired_mean_diff <- dabest(Margalef_final, Model, Richness,
                           idx = c('HMM1', 'HMM5-plus'), 
                           id.column = SRR, paired = T)

location <- sra_list

colnames(location)[1:2] <- c('SRR', 'Location')

paired_mean_diff <- merge(paired_mean_diff$data, location, by = 'SRR', all = T)

cols <- brewer.pal(n = 8, 'Set2')

kruskal.test(paired_mean_diff$Richness, paired_mean_diff$Model, data = paired_mean_diff)

unique(paired_mean_diff$Location)

richness <- ggplot(paired_mean_diff, aes(Model, Richness, group = SRR, fill = Location, color = Location)) +
  geom_line(size=1, alpha =0.7) +
  theme_classic() +
  geom_point(size=3, shape=21, colour="grey50", alpha = 0.8) +
  scale_fill_manual(values=c("Austria" = "#B79F00",
                             "Illinois" = "#F564E3",
                             "Japan" = "#00BA38",
                             "Singapore" = "#00BFC4",
                             "Lake_Mississippi" = "#8A2BE2",
                             "Lake_Mendota" = "#F8766D")) +
  scale_color_manual(values=c("Austria" = "#B79F00",
                              "Illinois" = "#F564E3",
                              "Japan" = "#00BA38",
                              "Singapore" = "#00BFC4",
                              "Lake_Mississippi" = "#8A2BE2",
                              "Lake_Mendota" = "#F8766D")) +
  xlab('') +
  ylab("Rarefied species richness\n(Margalef's index)") +
  labs(title = 'C', subtitle = 'Kruskal-Wallis, p-value = 0.07629') +
  theme(legend.position = 'none')
NULL
richness

###################################################
#Other phage representative proteins #########

#Analyze total protein hits with HMM scan score >= 30

#Caudovirales order 

read.csv('supp_figs/other_phages_in_samples/HMM_Caudovirales_vs_all82.csv', header = F, stringsAsFactors = F) -> caudo_tbl    #PF04466_seed
caudo_tbl[ , c(2,4,7:19)] <- NULL
colnames(caudo_tbl)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'bitscore')
caudo_tbl <- caudo_tbl[which(caudo_tbl$bitscore >= 30), ]

#Microviridae family 

read.csv('supp_figs/other_phages_in_samples/HMM_Micro_seed7_vs_all82.csv', header = F, stringsAsFactors = F) -> micro_seed7_tbl    #PF02305_seed
micro_seed7_tbl[ , c(2,4,7:19)] <- NULL
colnames(micro_seed7_tbl)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'bitscore')
micro_seed7_tbl <- micro_seed7_tbl[which(micro_seed7_tbl$bitscore >= 30), ]

#Inoviridae family 

read.csv('supp_figs/other_phages_in_samples/HMM_Inovir_gp2_vs_all82.csv', header = F, stringsAsFactors = F) -> inov_tbl2    #PF11726_seed
inov_tbl2[ , c(2,4,7:19)] <- NULL
colnames(inov_tbl2)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'bitscore')
inov_tbl2 <- inov_tbl2[which(inov_tbl2$bitscore >= 30), ]

#Levivirus genus 

read.csv('supp_figs/other_phages_in_samples/HMM_Levivirus_coat_vs_all82.csv', header = F, stringsAsFactors = F) -> levi_coat_tbl    #PF01819_seed
levi_coat_tbl[ , c(2,4,7:19)] <- NULL
colnames(levi_coat_tbl)[1:4] <- c('Cluster', 'Protein_ID', 'evalue', 'bitscore')
levi_coat_tbl <- levi_coat_tbl[which(levi_coat_tbl$bitscore >= 30), ]

#Make table of counts for counts of different phages.

###

alt_phage <- read.csv('supp_figs/other_phages_in_samples/count_table.csv', header = T, stringsAsFactors = F)
alt_phage$Phage <- as.factor(alt_phage$Phage)

alt_phage_plot <- ggplot(alt_phage, aes(x = alt_phage$Phage, y = alt_phage$Number, fill = alt_phage$Phage)) +
  geom_bar(colour="black", stat="identity", size=.3) +
  guides(fill=FALSE) +
  scale_fill_brewer(palette = 'Set3') +
  xlab("") + 
  ylab("Protein hits") +
  scale_x_discrete(labels = c('Caudovirales' = 'Caudovirales\n(Terminase)', 'Levi' = 'Levivirus\n(Coat protein)', 'Microviridae' = 'Microviridae\n(Capsid protein)', 'Inoviridae' = 'Inoviridae\n(Viral endonuclease)')) +
  NULL
alt_phage_plot

#pdf('abundance_of_other_phages.pdf', paper = 'A4', height = 29.4, width = 20)
alt_phage_plot
#dev.off()

###################################################

prod <- read.csv('supp_figs/tree_genome_architecture/genome_architecture/prodigal_headers.csv', header = T, stringsAsFactors = F)
hmm <- read.csv('supp_figs/tree_genome_architecture/genome_architecture/hmmscan_m5_plus.csv', header = T, stringsAsFactors = F)

prod_hmm <- merge(prod, hmm, by = 'Protein_ID', all.x = T)

prod_hmm <- prod_hmm[order(prod_hmm$HMM_score, decreasing = T), ]
prod_hmm <- prod_hmm[!duplicated(prod_hmm$Protein_ID), ]

prod_hmm <- prod_hmm[order(prod_hmm$Protein_numb, decreasing = F), ]
prod_hmm <- prod_hmm[order(prod_hmm$Genome_numb, decreasing = F), ]

prod_hmm$Hypothetical <- 'Hypothetical'
prod_hmm$Hypothetical_numb <- paste(prod_hmm$Hypothetical, prod_hmm$Protein_numb, sep = '_')

prod_hmm$HMM_cluster <- with(prod_hmm, ifelse(is.na(prod_hmm$HMM_cluster) & !is.na(prod_hmm$Hypothetical_numb), prod_hmm$Hypothetical_numb, prod_hmm$HMM_cluster))

hypothetical_proteins <- prod_hmm[!complete.cases(prod_hmm),]

prod_hmm <- prod_hmm[,-c(13:16)]

hypothetical_proteins <- hypothetical_proteins[,-c(12:15)]

#write.csv(hypothetical_proteins, 'supp_figs/tree_genome_architecture/genome_architecture/hypothetical_proteins_details.csv', row.names = F)

###

genomes <- prod_hmm[,c(2, 11, 12)]

genomes_rshp <- reshape(genomes, idvar = 'Genome_ID', timevar = 'Protein_numb', direction = 'wide')

genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.7, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.6, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.5, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.4, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.3, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.2, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.1, decreasing = F), ]

rownames(genomes_rshp) <- genomes_rshp$Genome_ID
genomes_rshp$Genome_ID <- NULL

# Manually checking for rows where genome orientation is reversed (i.e. RdRp is observed before MP).

genomes_rshp$numb <- 1:nrow(genomes_rshp)

genomes_rshp_fw <- genomes_rshp[-c(9,144:173,586:1044),]
genomes_rshp_rv <- genomes_rshp[c(9,144:173,586:1044),]

genomes_rshp_fw$numb <- NULL
genomes_rshp_rv$numb <- NULL

genomes_rshp_rv <- genomes_rshp_rv[,c(7,6,5,4,3,2,1)]
colnames(genomes_rshp_rv)[1:7] <- c('HMM_cluster.1', 
                                    'HMM_cluster.2', 
                                    'HMM_cluster.3',
                                    'HMM_cluster.4',
                                    'HMM_cluster.5',
                                    'HMM_cluster.6',
                                    'HMM_cluster.7')

genomes_rshp <- rbind(genomes_rshp_fw, genomes_rshp_rv)

genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.7, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.6, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.5, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.4, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.3, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.2, decreasing = F), ]
genomes_rshp <- genomes_rshp[order(genomes_rshp$HMM_cluster.1, decreasing = F), ]

genomes_rshp[is.na(genomes_rshp)] <- ''

genomes_rshp$arch <- paste(genomes_rshp$HMM_cluster.1,
                           genomes_rshp$HMM_cluster.2,
                           genomes_rshp$HMM_cluster.3,
                           genomes_rshp$HMM_cluster.4,
                           genomes_rshp$HMM_cluster.5,
                           genomes_rshp$HMM_cluster.6,
                           genomes_rshp$HMM_cluster.7,
                           sep = '£')

genomes_rshp$genomes <- rownames(genomes_rshp)

###

genome_arch <- genomes_rshp[,c(9,8)]
rownames(genome_arch) <- NULL

genome_arch$arch <- gsub('£££££', '', genome_arch$arch)
genome_arch$arch <- gsub('££££', '', genome_arch$arch)
genome_arch$arch <- gsub('£££', '', genome_arch$arch)
genome_arch$arch <- gsub('££', '', genome_arch$arch)

arch_splt <- as.data.frame(str_split_fixed(string = genome_arch$arch, pattern = '£', 7))

arch_splt$Genome_ID <- genome_arch$genomes

rownames(arch_splt) <- arch_splt$Genome_ID
arch_splt$Genome_ID <- NULL

colnames(arch_splt)[1:7] <- c('HMM_cluster.1', 
                              'HMM_cluster.2', 
                              'HMM_cluster.3',
                              'HMM_cluster.4',
                              'HMM_cluster.5',
                              'HMM_cluster.6',
                              'HMM_cluster.7')

arch_splt$arch <- paste(arch_splt$HMM_cluster.1,
                        arch_splt$HMM_cluster.2,
                        arch_splt$HMM_cluster.3,
                        arch_splt$HMM_cluster.4,
                        arch_splt$HMM_cluster.5,
                        arch_splt$HMM_cluster.6,
                        arch_splt$HMM_cluster.7,
                        sep = ' ')

arch_splt$arch <- gsub('     ', '', arch_splt$arch)
arch_splt$arch <- gsub('    ', '', arch_splt$arch)
arch_splt$arch <- gsub('   ', '', arch_splt$arch)
arch_splt$arch <- gsub('  ', '', arch_splt$arch)

arch_splt$arch <- gsub('Hypothetical_1', 'Hypothetical', arch_splt$arch)
arch_splt$arch <- gsub('Hypothetical_2', 'Hypothetical', arch_splt$arch)
arch_splt$arch <- gsub('Hypothetical_3', 'Hypothetical', arch_splt$arch)
arch_splt$arch <- gsub('Hypothetical_4', 'Hypothetical', arch_splt$arch)
arch_splt$arch <- gsub('Hypothetical_5', 'Hypothetical', arch_splt$arch)
arch_splt$arch <- gsub('Hypothetical_6', 'Hypothetical', arch_splt$arch)
arch_splt$arch <- gsub('Hypothetical_7', 'Hypothetical', arch_splt$arch)

#write.csv(arch_splt, 'architecture_structure.csv', row.names = T)

arch_tbl <- as.data.frame(table(arch_splt$arch))

arch_tbl <- arch_tbl[order(arch_tbl$Freq, decreasing = T), ]

rownames(arch_tbl) <- NULL

sum(arch_tbl$Freq)

colnames(arch_tbl)[1] <- 'Genome_architecture'

#write.csv(arch_tbl, 'supp_figs/tree_genome_architecture/genome_architecture/architecture_RNA_phages.csv', row.names = F)

###################################################
#Phylogenetic tree of genome architecture ####

treeBS <- read.tree('supp_figs/tree_genome_architecture/bootstrap_concat_aln_tree_BS100_1044seqs.tre')
metadata <- read.csv('supp_figs/tree_genome_architecture/taxonomic_table_orthoMCL_and_SDT.csv', header = T, stringsAsFactors = T)

tree <- rotate(treeBS, 1990) %>% rotate(2021)

p1 <- ggtree(tree, layout = 'fan')

p2 <- flip(p1, 2021, 1990)

p3 <- flip(p2, 1048, 1083)

p4 <- flip(p3, 1084, 1201)

p5 <- flip(p4, 1561, 1286)

p6 <- flip(p5, 1526, 1529)

p7 <- flip(p6, 1677, 1285)

p8 <- flip(p7, 1421, 1391)

p9 <- flip(p8, 1425, 1422)

col <- brewer.pal(8, 'Accent')

tree_plot <- p9 %<+% metadata + 
  geom_tippoint(aes(color = Subfamily, shape = Family), alpha = 0.8, size = 3) +
  theme(legend.position = 'right') +
  scale_color_manual(breaks = c('CP_A',
                                'CP_B',
                                'CP_C',
                                'CP_D',
                                'CP_E',
                                'CP_F',
                                'CP_G',
                                'CP_H'),
                     values = col) +
  NULL
tree_plot

arch <- read.csv('supp_figs/tree_genome_architecture/architecture_heatmap.csv', header = T, stringsAsFactors = T)

rownames(arch) <- arch$X
arch$X <- NULL

#pdf('arch_tree.pdf', paper = 'A4r', width = 29.7, height = 20)
gheatmap(tree_plot, arch, width = 0.5, colnames = F) + 
  theme(legend.position = 'right') + 
  scale_fill_manual(breaks = c('Alpha_2', 'Alpha_1', 'MP', 'CP', 'Beta', 'RdRp', 'Gamma'),
                    values = c('Alpha_2' = '#fdcdac',
                               'Alpha_1'= '#e6f5c9',
                               'MP'= '#98ff52',
                               'CP'= '#50d9fb', 
                               'Beta'= '#f4cae4',
                               'RdRp'= '#ff1d1d',
                               'Gamma'= '#cbd5e8')) +
  NULL
#dev.off()

###################################################

#Clean environment
rm(list = ls())

###################################################
