-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnalysis.Rmd
More file actions
4221 lines (3607 loc) · 190 KB
/
Copy pathAnalysis.Rmd
File metadata and controls
4221 lines (3607 loc) · 190 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Metagenomic analysis of secondary cooling water microbial communities"
author: "Ruben Props"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
code_folding: show
highlight: haddock
keep_md: yes
theme: united
toc: yes
toc_float:
collapsed: no
smooth_scroll: yes
toc_depth: 2
css: report_styles.css
df_print: paged
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE, warning = FALSE}
knitr::opts_chunk$set(eval = TRUE,
echo = TRUE,
cache = TRUE,
include = TRUE,
collapse = FALSE,
dependson = NULL,
engine = "R", # Chunks will always have R code, unless noted
error = TRUE,
fig.path="Figures/cached/", # Set the figure options
fig.align = "center"
)
# Load libraries
library('tidyr')
library('dplyr')
library('ggplot2')
library("grid")
library("xlsx")
library("gridExtra")
library("janitor")
library("reshape2")
library("easyGgplot2")
library("KEGGREST")
library("ggpubr")
source("./Functions/functions.R")
library("phyloseq")
library("SpiecEasi")
library("seqtime")
library("ggrepel")
library("scales")
library("MetQy")
library("UpSetR")
library("DOSE")
library("clusterProfiler")
library("RColorBrewer")
library("data.table")
col_RAMLI <- "#887CAF"
# col_RAMLI <- "#e2a2fd"
col_bac1 <- "#720000"
col_bac2 <- "#D46A6A"
```
# A. 16S analysis
## Network analysis on relative abundances
In the first analysis we utilize the raw counts. As such this network will be built using relative abundance data.
```{r network-analysis-relative, warning = FALSE, dpi = 500, fig.width = 8, fig.height = 8, dev = c("png","pdf"), include = FALSE}
# Set seed
set.seed(777)
# Import data
otus <- as.matrix(read.csv2("16S_data/OTU_table_raw.csv", fill = TRUE, header = TRUE,
row.names = 1))
taxa <- tax_table(as.matrix(read.csv2("16S_data/tax_table_raw.csv", fill = TRUE, header = TRUE,row.names = 1))
)
phy_df <- phyloseq(otu_table(otus, taxa_are_rows = FALSE), taxa)
# filterobj <- filterTaxonMatrix(otus, minocc = 20,
# keepSum = TRUE, return.filtered.indices = TRUE)
# otus.f <- filterobj$mat
# taxa.f <- taxa[setdiff(1:nrow(taxa), filterobj$filtered.indices),]
# dummyTaxonomy <- colnames(tax_df); dummyTaxonomy[1] <- "Kingdom_dummy"
# taxa.f <- rbind(taxa.f, dummyTaxonomy)
# rownames(taxa.f)[nrow(taxa.f)] <- "0"
# rownames(otus.f)[nrow(otus.f)] <- "0"
#
# # Next, we assemble a new phyloseq object with the filtered OTU and taxonomy tables.
# updatedotus <- otu_table(otus.f, taxa_are_rows = TRUE)
# updatedtaxa <- tax_table(taxa.f)
# phyloseqobj.f <- phyloseq(updatedotus, updatedtaxa)
# Prevalence filtering
phy_df_filtered <- filter_taxa(phy_df, function(x) sum(x > 30) > (0.25*length(x)), TRUE)
sp_easi <- spiec.easi(phy_df_filtered, method='mb', lambda.min.ratio=1e-2,
nlambda=20, icov.select.params=list(rep.num=50))
ig.mb <- adj2igraph(sp_easi$refit, vertex.attr = list(name=taxa_names(phy_df_filtered)))
vsize <- Biobase::rowMedians(clr(otu_table(phy_df_filtered), 1))+15
Lineage_rel <- tax_table(phy_df_filtered)[,"Lineage"]
Lineage_rel <- factor(Lineage_rel, levels = unique(Lineage_rel))
vweights <- summary(symBeta(getOptBeta(sp_easi), mode='maxabs'))
MAGs <- c(); MAGs[taxa_names(phy_df_filtered)=="Otu00001"] <- "Ramlibacter sp. MAG"
MAGs[taxa_names(phy_df_filtered)=="Otu00002"] <- "Bacteroidetes sp. MAG1"
MAGs[taxa_names(phy_df_filtered)=="Otu00003"] <- "Bacteroidetes sp. MAG2"
MAGs[is.na(MAGs)] <- ""
# png(file = "./Figures/Figures_network/NETWORK-REL-CX-C30-A25.png", width = 9, height = 9, res = 500, units = "in")
plot_network_custom(ig.mb, phy_df_filtered, type='taxa',
line_weight = 2, hjust = 0.5,
point_size = 0.1, alpha = 0.01, label_size = 3.95)+
# scale_fill_brewer(palette = "Paired")+
# scale_color_brewer(palette = "Paired")+
scale_fill_manual(values = c("#e2a2fd", brewer.pal(n = 12, "Paired")[c(3:8,1:2,11,12)]) )+
geom_point(aes(size = vsize, fill = Lineage_rel), alpha = 0.5,
colour="black", shape=21)+
guides(size = FALSE,
fill = guide_legend(title = "Lineage", override.aes = list(size = 5),
nrow = 4),
color = FALSE)+
theme(legend.position="bottom", legend.text=element_text(size=12),
text = element_text(size = 12),
plot.margin = unit(c(1,1,1,1), "cm"))+
scale_size(range = c(5, 15))+
geom_label_repel(aes(label = MAGs), fontface = 'bold', color = 'black',
box.padding = 0.35, point.padding = 0.5,
segment.color = 'black',
size = 4,
# Width of the line segments.
segment.size = 1.5,
# Draw an arrow from the label to the data point.
arrow = arrow(length = unit(0.015, 'npc')),
nudge_x = -0.1,
nudge_y = 0.6
)
# dev.off()
```
## Network analysis on absolute abundances
The second network will be built using absolute abundance data by multiplying the relative taxon abundances by the total cell density. The final obtained counts will expressed as nr. of cells measured in 50 µL samples. We also only consider the OTUs that were left after the prevalence filtering conducted in the network construction with relative abundance data.
```{r network-analysis-absolute, warning = FALSE, dpi = 500, fig.width = 8, fig.height = 8, dev = c("png","pdf")}
# Import cell count data
cell_counts <- read.csv("16S_data/cell_counts.csv")
cell_counts$sample_title <- as.factor(cell_counts$sample_title)
# Import metadata
meta_16S <- read.csv("16s_data/Metadata.csv")[1:77,]; rownames(meta_16S) <- meta_16S$sample_title
# Calculate proportions
phy_df_rel <- transform_sample_counts(phy_df, function(x) x/sum(x))
# Add metadata
sample_data(phy_df_rel) <- sample_data(meta_16S)
# Select samples for which corresponding counts are available
cell_counts <- cell_counts[cell_counts$sample_title %in% sample_names(phy_df_rel), ]
cell_counts <- droplevels(cell_counts)
phy_df_abs <- prune_samples(sample_names(phy_df_rel) %in% cell_counts$sample_title, phy_df_rel)
# Multiply with cell counts in 50 µL of sample
otu_table(phy_df_abs) <- otu_table(phy_df_abs) * cell_counts$Number_of_cells
# Select taxa that were selected based on prevalence in previous chunk
phy_df_abs <- prune_taxa(taxa_names(phy_df_filtered), phy_df_abs)
# Round absolute abundances to integers
otu_table(phy_df_abs) <- round(otu_table(phy_df_abs), 0)
# Construct network
sp_easi_abs <- spiec.easi(phy_df_abs, method='mb', lambda.min.ratio=1e-2,
nlambda=20, icov.select.params=list(rep.num=50))
ig.mb_abs <- adj2igraph(sp_easi_abs$refit, vertex.attr = list(name=taxa_names(phy_df_abs)))
vsize_abs <- Biobase::rowMedians(clr(otu_table(phy_df_abs), 1))+15
Lineage_abs <- tax_table(phy_df_abs)[,"Lineage"]
Lineage_abs <- factor(Lineage_abs, levels = unique(Lineage_abs))
vweights_abs <- summary(symBeta(getOptBeta(sp_easi_abs), mode='maxabs'))
MAGs <- c(); MAGs[taxa_names(phy_df_abs)=="Otu00001"] <- "Ramlibacter sp. MAG"
MAGs[taxa_names(phy_df_abs)=="Otu00002"] <- "Bacteroidetes sp. MAG1"
MAGs[taxa_names(phy_df_abs)=="Otu00003"] <- "Bacteroidetes sp. MAG2"
MAGs[is.na(MAGs)] <-""
```
```{r network-analysis-absolute-plot, warning = FALSE, dpi = 500, fig.width = 8, fig.height = 8, dev = c("png","pdf")}
# Plot network inferred from absolute abundances
# png(file = "./Figures/Figures_network/NETWORK-ABS-CX-C30-A25.png", width = 9, height = 9, res = 500, units = "in")
plot_network_custom(ig.mb_abs, phy_df_abs, type='taxa',
line_weight = 2, hjust = 0.5,
point_size = 0.1, alpha = 0.01, label_size = 3.95)+
# scale_fill_brewer(palette = "Paired")+
# scale_color_brewer(palette = "Paired")+
# scale_fill_manual(values = c("#e2a2fd", brewer.pal(n = 12, "Paired")[c(3:8,1:2,11,12)]) )+
scale_fill_manual(values = c(col_RAMLI, brewer.pal(n = 12, "Paired")[c(6,3,4,4,7,8,1:2,11,12)]) )+
geom_point(aes(size = vsize_abs, fill = Lineage_abs), alpha = 0.5,
colour="black", shape=21)+
guides(size = FALSE,
fill = guide_legend(title = "Lineage", override.aes = list(size = 5),
nrow = 4),
color = FALSE)+
theme(legend.position="bottom", legend.text=element_text(size=12),
text = element_text(size = 12),
plot.margin = unit(c(1,1,1,1), "cm"))+
scale_size(range = c(5, 15))+
geom_label_repel(aes(label = MAGs), fontface = 'bold', color = 'black',
box.padding = 0.35, point.padding = 0.5,
segment.color = 'black',
size = 4,
# Width of the line segments.
segment.size = 1.5,
# Draw an arrow from the label to the data point.
arrow = arrow(length = unit(0.015, 'npc')),
nudge_x = -0.1,
nudge_y = 0.6
)
# dev.off()
```
## Plots
```{r OTU1-dynamics, warning = FALSE, dpi = 500, fig.width = 9, fig.height = 5.5, dev = c("png")}
# Plot absolute OTU dynamics of OTU1
df_abs <- psmelt(phy_df_abs)
col_RAMLI <- "#887CAF"
# Need to account for dilution factor of 2 and 50 µL volume measured
p_abs_otu1 <- df_abs %>% dplyr::filter(OTU == "Otu00001") %>%
ggplot(aes(x = Timepoint, y = 2*Abundance/50))+
facet_grid(.~Reactor.cycle, scales = "free")+
scale_shape_manual(values = c(21,24))+
geom_line(size = 1.5, linetype = 2, color = adjustcolor("#000000", 0.5))+
geom_point(size = 4, fill = col_RAMLI, aes(shape = Reactor_status,
alpha = Reactor_status),
color = "black")+
scale_alpha_manual(values = c(0.5,1))+
theme_bw()+
ylab(expression("Otu00001 abundance - cells µL"^"-1"))+
xlab("Time relative to reactor start - days")+
scale_y_continuous(breaks = seq(0,50e3,5e3)*2/50, limits = c(0,30e3)*2/50)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
strip.text.x=element_text(size=18),
legend.position = "top")+
guides(shape = guide_legend(title="Reactor status", ncol =1),
alpha = FALSE)
print(p_abs_otu1)
```
```{r OTU1-box-abs, warning = FALSE, dpi = 500, fig.width = 6.5, fig.height = 5, dev = c("png", "pdf")}
# Boxplot of absolute abundances
col_RAMLI <- "#887CAF"
p_abs_box <- df_abs %>%
dplyr::filter(OTU %in% c("Otu00001","Otu00002","Otu00003")) %>%
ggplot(aes(x = OTU, y = 2*Abundance/50, fill = OTU))+
geom_jitter(size = 2,
color = "black", shape = 21, width = 0.1, alpha = 0.5)+
geom_violin(alpha = 0.4, adjust = 1, draw_quantiles = TRUE,
trim = TRUE)+
stat_summary(fun.data=mean_sdl, fun.args = list(mult = 1),
geom="pointrange", color="black")+
# geom_boxplot(width = 0.5, alpha = 0.4, outlier.shape = NA)+
scale_fill_manual(values = c(col_RAMLI, col_bac1, col_bac2))+
theme_bw()+
ylab(expression("Cells µL"^"-1"))+
xlab("")+
# ylab("")+
scale_y_continuous(breaks = seq(0,50e3,10e3)*2/50, limits = c(-5e3,40e3)*2/50)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
axis.text.x=element_text(size=14),
title=element_text(size=16), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
strip.text.x=element_text(size=18),
legend.position = "sqrt")+
guides(shape = guide_legend(title="Reactor status", ncol =1),
fill = FALSE)+
theme(axis.line = element_line(size = 1, colour = "grey80"),
panel.border = element_blank())
# ggtitle(expression("Cells mL"^"-1"))
# ggtitle(expression("Absolute abundance (cells mL"^"-1)"))
print(p_abs_box)
```
```{r OTU1-box-rel, dpi = 500, fig.width = 6.5, fig.height = 5, dev = c("png", "pdf")}
# psmelt relative abundance data
df_rel <- psmelt(phy_df_rel)
col_RAMLI <- "#887CAF"
# Boxplot of relative abundances
p_rel_box <- df_rel %>%
dplyr::filter(OTU %in% c("Otu00001","Otu00002","Otu00003")) %>%
ggplot(aes(x = OTU, y = 100*Abundance, fill = OTU))+
geom_jitter(size = 2,
color = "black", shape = 21, width = 0.1, alpha = 0.5)+
geom_violin(alpha = 0.4, adjust = 1, draw_quantiles = TRUE)+
stat_summary(fun.data=mean_sdl, fun.args = list(mult = 1),
geom="pointrange", color="black")+
# geom_boxplot(width = 0.5, alpha = 0.4, outlier.shape = NA)+
scale_fill_manual(values = c(col_RAMLI, col_bac1, col_bac2))+
theme_bw()+
# ylab(expression("Relative abundance - %"))+
xlab("")+
ylab("")+
scale_y_continuous(breaks = 100*seq(0,1,0.2), limits = 100*c(-0.05,1))+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
axis.text.x=element_text(size=14, angle = 0),
title=element_text(size=16), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
strip.text.x=element_text(size=18),
legend.position = "top")+
guides(shape = guide_legend(title="Reactor status", ncol =1),
fill = FALSE)+
theme(axis.line = element_line(size = 1, colour = "grey80"),
panel.border = element_blank())+
ggtitle("Relative abundance (%)")
print(p_rel_box)
```
## Physicochemistry
```{r physico-data, warning = FALSE, dpi = 500, fig.width = 6, fig.height = 6, dev = c("png", "svg")}
# Assess correlations
Physico_df_trim_abs_OTU1 <- df_abs[, c("OTU", "Timepoint","Dilution_factor",
"Formate", "Acetate", "Sulfate",
"Nitrate", "Chloride", "Temperature",
"Conductivity", "pH", "Sample", "Abundance")] %>%
dplyr::filter(!is.na(Formate), OTU == "Otu00001")
colnames(Physico_df_trim_abs_OTU1)[13] <- "OTU1 - abundance"
Physico_df_trim_abs_OTU2 <- df_abs[, c("OTU", "Sample", "Abundance")] %>%
dplyr::filter(OTU == "Otu00002")
colnames(Physico_df_trim_abs_OTU2)[3] <- "OTU2 - abundance"
Physico_df_trim_abs_OTU3 <- df_abs[, c("OTU", "Sample", "Abundance")]%>%
dplyr::filter(OTU == "Otu00003")
colnames(Physico_df_trim_abs_OTU3)[3] <- "OTU3 - abundance"
Physico_df_trim_abs_merged <- left_join(Physico_df_trim_abs_OTU1,
Physico_df_trim_abs_OTU2,
by = "Sample")
Physico_df_trim_abs_merged <- left_join(Physico_df_trim_abs_merged,
Physico_df_trim_abs_OTU3,
by = "Sample")
# Same for relative abundances
Physico_df_trim_rel_OTU1 <- df_rel[, c("OTU", "Timepoint","Dilution_factor",
"Formate", "Acetate", "Sulfate",
"Nitrate", "Chloride", "Temperature",
"Conductivity", "pH", "Sample", "Abundance")] %>%
dplyr::filter(!is.na(Formate), OTU == "Otu00001")
colnames(Physico_df_trim_rel_OTU1)[13] <- "OTU1 - abundance"
Physico_df_trim_rel_OTU2 <- df_rel[, c("OTU", "Sample", "Abundance")] %>%
dplyr::filter(OTU == "Otu00002")
colnames(Physico_df_trim_rel_OTU2)[3] <- "OTU2 - abundance"
Physico_df_trim_rel_OTU3 <- df_rel[, c("OTU", "Sample", "Abundance")]%>%
dplyr::filter(OTU == "Otu00003")
colnames(Physico_df_trim_rel_OTU3)[3] <- "OTU3 - abundance"
Physico_df_trim_rel_merged <- left_join(Physico_df_trim_rel_OTU1,
Physico_df_trim_rel_OTU2,
by = "Sample")
Physico_df_trim_rel_merged <- left_join(Physico_df_trim_rel_merged,
Physico_df_trim_rel_OTU3,
by = "Sample")
# Physico_df_trim_rel <- df_rel[, c("OTU", "Timepoint","Dilution_factor",
# "Formate", "Acetate", "Sulfate",
# "Nitrate", "Chloride", "Temperature",
# "Conductivity", "pH", "Abundance")] %>%
# dplyr::filter(!is.na(Formate), OTU == otu)
# Get P-values of correlations between OTUs and physicochemistry
p.mat_abs <- cor.mtest(Physico_df_trim_abs_merged[, -c(1:3, 12,14,16)],
method = "kendall")
p.mat_rel <- cor.mtest(Physico_df_trim_rel_merged[, -c(1:3, 12,14,16)],
method = "kendall")
# Making correlation plots
corrplot::corrplot(cor(Physico_df_trim_abs_merged[, -c(1:3, 12,14,16)],
method = "kendall"),
type="upper",
tl.col="black", tl.srt=45,
p.mat = p.mat_abs, sig.level = 0.05,
diag=FALSE,
title = paste("Absolute abundances"))
corrplot::corrplot(cor(Physico_df_trim_rel_merged[, -c(1:3, 12,14,16)],
method = "pearson"),
type="upper",
tl.col="black", tl.srt=45,
p.mat = p.mat_rel, sig.level = 0.05,
diag=FALSE,
title = paste("Relative abundances"))
# Calculate element-wise N/P ratio assuming 1 µg/L of PO4
molP <- (1/94.9714)/1000 # in mmol/L of upper detection limit
min((Physico_df_trim_rel_OTU1$Nitrate/62.0049)/molP) # in mmol/L
sd((Physico_df_trim_rel_OTU1$Nitrate/62.0049)/molP)
# mean((14*Physico_df_trim_rel_OTU1$Nitrate/62.0049))
# sd((14*Physico_df_trim_rel_OTU1$Nitrate/62.0049))
```
# B. MetaG analysis
```{r read-format data, warning = FALSE, dpi = 500, fig.width = 7, fig.height = 6}
# Read data
mean_coverage <- read.table("./SAMPLES-SUMMARY/bins_across_samples/mean_coverage.txt", header = TRUE)
std_coverage <- read.table("./SAMPLES-SUMMARY/bins_across_samples/std_coverage.txt", header = TRUE)
bin_size <- read.table("./SAMPLES-SUMMARY/general_bins_summary.txt", header = TRUE)[, c(1, 3, 6, 9)]
total_reads <- read.table("./Mapping_files/sample_reads.tsv", header = TRUE)
read_length <- 300
# From wide to long format
mean_coverage_long <- gather(mean_coverage, Sample_ID, coverage,
SAMPLE_16:SAMPLE_65, factor_key=TRUE)
std_coverage_long <- gather(std_coverage, Sample_ID, std_coverage,
SAMPLE_16:SAMPLE_65,
factor_key=TRUE)
coverage_data <- data.frame(mean_coverage_long,
std_coverage = std_coverage_long[,3])
# Read and add metadata
# meta <- read.csv2("metadata.csv")
# meta$Sample_ID <- gsub(meta$Sample_ID, pattern = ".", replacement = "_", fixed = TRUE)
data_total <- left_join(coverage_data, total_reads, by = "Sample_ID")
data_total <- left_join(data_total, bin_size, by = "bins")
# data_total <- left_join(data_total, meta, by = "Sample_ID")
data_total$bins <- plyr::revalue(data_total$bins, c("BetIa_bin"="Ramlibacter sp. MAG",
"bacIa_vizbin1"="Bacteroidetes sp. MAG1",
"bacIa_vizbin2"="Bacteroidetes sp. MAG2"))
# Calculate relative abundance of the bins
data_total$mean_rel_abundance <- 100*(data_total$coverage*data_total$bin_size)/(read_length*data_total$Total_reads)
data_total$upper_rel_abundance <- 100*((data_total$coverage+data_total$std_coverage)*data_total$bin_size)/(read_length*data_total$Total_reads)
data_total$lower_rel_abundance <- 100*((data_total$coverage-data_total$std_coverage)*data_total$bin_size)/(read_length*data_total$Total_reads)
data_total$mean_rel_abundance_map <- 100*(data_total$coverage*data_total$bin_size)/(read_length*data_total$Mapped_reads)
data_total$upper_rel_abundance_map <- 100*((data_total$coverage+data_total$std_coverage)*data_total$bin_size)/(read_length*data_total$Mapped_reads)
data_total$lower_rel_abundance_map <- 100*((data_total$coverage-data_total$std_coverage)*data_total$bin_size)/(read_length*data_total$Mapped_reads)
# Add additional column that assigns PNCs to correct MAG
data_total$Genome_id <- factor(rep(c("Ramlibacter sp. MAG", "Ramlibacter sp. MAG", "Ramlibacter sp. MAG", "Bacteroidetes sp. MAG2", "Bacteroidetes sp. MAG1", "Bacteroidetes sp. MAG2"), 4))
# Plot genome size for all three genomes
data_total[data_total$bins %in% c("Bacteroidetes sp. MAG1",
"Bacteroidetes sp. MAG2","Ramlibacter sp. MAG"), ] %>%
ggplot(aes(x = bins, y = bin_size/(4*1e6), fill = Genome_id))+
theme_bw()+
geom_bar(width = 0.5, stat="identity", alpha = 0.7)+
coord_flip()+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme(axis.text.x = element_text(angle = 0, size = 16),
axis.text.y = element_text(size = 16),
axis.title.x = element_text(size = 18),
legend.title = element_text("Genome bin"), legend.position = "top")+
xlab("")+
ylab("Genome size (Mbp)")+
guides(fill = FALSE)+
geom_hline(yintercept = 1, size = 2, linetype="dotted")
# Plot irep for all 3 genomes
data_total[data_total$bins %in% c("Bacteroidetes sp. MAG1",
"Bacteroidetes sp. MAG2","Ramlibacter sp. MAG"), ] %>%
ggplot(aes(x = bins, y = mean_irep/4, fill = Genome_id))+
theme_bw()+
geom_bar(width = 0.5, stat="identity", alpha = 0.7)+
coord_flip()+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme(axis.text.x = element_text(angle = 0, size = 16),
axis.text.y = element_text(size = 16),
axis.title.x = element_text(size = 18),
legend.title = element_text(""), legend.position = "top")+
xlab("")+
ylab("Index of Replication (iRep)")+
guides(fill = FALSE)+
geom_hline(yintercept = 1.34, size = 2, linetype="dotted")
```
# 1. Phylogenetic tree
## Ramlibacter sp.
<!--  -->
# *2. Investigate MAG- and 16S-based abundances*
It is clear that there is significant %GC coverage bias present. The estimated relative abundances
from metagenomics do not quantitatively match with the V3-V4 16S rRNA gene amplicon data. This is probably due to the significant %GC bias that is associate with the MAG-based assessment.
$$Relative\ abundance =100*(\frac{mean\ coverage * bin\ size}{read\ length*total\ sample\ reads })$$
Another option is to calculate relative to mapped number of reads:
$$Relative\ abundance =100*(\frac{mean\ coverage * bin\ size}{read\ length*total\ sample\ reads * \%mapped\ reads})$$
Import reference relative abundances from 16S data set in order to directly compare with metagenomic data set.
```{r import-reference, warning = FALSE}
df_16S <- read.delim("./Mapping_files/relative_abundance_16S.tsv",
header = TRUE, sep = "\t")
df_16S_long <- gather(df_16S, Sample_ID, relative_abundance_16S,
SAMPLE_16:SAMPLE_65, factor_key=TRUE)
```
```{r plot-data, warning = FALSE, fig.width = 7.5, fig.height = 22.5, dpi=500}
# Subset for only the three complete genomes (not PNCs).
data_total_sb <- data_total[data_total$bins %in% c("Ramlibacter sp. MAG", "Bacteroidetes sp. MAG1", "Bacteroidetes sp. MAG2"),]
p_meta <- ggplot(data = data_total_sb, aes(x = bins, y = mean_rel_abundance, fill = bins))+
geom_point(size = 4, shape = 21, alpha = 0.7)+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme_bw()+
geom_errorbar(aes(ymin=lower_rel_abundance,
ymax=upper_rel_abundance,
width=.1))+
facet_grid(.~Sample_ID)+
# ylim(0,1)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
axis.text.x = element_text(angle = 45, hjust = 1),
strip.text.x=element_text(size=18))+
ylab("Mean relative abundance (%)")+
ylim(-1,100)+
ggtitle("Metagenomic - total reads")
# Corrected for mapped N° of reads
p_meta_mapped <- ggplot(data = data_total_sb, aes(x = bins, y = mean_rel_abundance_map, fill = bins))+
geom_point(size = 4, shape = 21, alpha = 0.7)+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme_bw()+
geom_errorbar(aes(ymin=lower_rel_abundance_map,
ymax=upper_rel_abundance_map,
width=.1))+
facet_grid(.~Sample_ID)+
# ylim(0,1)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
axis.text.x = element_text(angle = 45, hjust = 1),
strip.text.x=element_text(size=18))+
ylab("Mean relative abundance (%)")+
ylim(-1,100)+
ggtitle("Metagenomic - mapped reads")
p_16S <- ggplot(data = df_16S_long, aes(x = bins, y = relative_abundance_16S, fill = bins))+
geom_point(size = 4, shape = 21, alpha = 0.7)+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme_bw()+
facet_grid(.~Sample_ID)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
axis.text.x = element_text(angle = 45, hjust = 1),
strip.text.x=element_text(size=18))+
ylab("Mean relative abundance (%)")+
ylim(-1,100)+
ggtitle("V3-V4 16S")
grid_arrange_shared_legend(p_meta, p_meta_mapped, p_16S, ncol = 1, nrow = 3)
```
# *3. Investigate sequence characteristics within coding DNA sequences (CDS)*
```{r %GC-gene-analysis_v1, warning = FALSE, fig.width = 22.5, fig.height = 7.5, dpi=500, include = FALSE}
# First we need the files that map the gene ID to the sequence ID (linux cmd: https://github.com/rprops/MetaG_lakeMI/wiki/11.-Genome-annotation)
# These are stored in the IMG_annotation data for each genome bin
# Next, extract the %GC of each gene from the gff file
extract_gc_from_gff("./IMG_annotation/IMG_2724679690_Ramlibacter_bin/121950.assembled.gff", outputFolder = "GC_analysis")
extract_gc_from_gff("./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/121951.assembled.gff", outputFolder = "GC_analysis")
extract_gc_from_gff("./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/121960.assembled.gff", outputFolder = "GC_analysis")
# Use these files to make dataframes mapping function (COGs/Pfams/KO) and %GC
RAMLI_gc_cog <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121950.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690.cog.tab.txt", gc_thresh = 0.1, output = FALSE)
BAC1_gc_cog <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121951.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691.cog.tab.txt", gc_thresh = 0.1, output = FALSE)
BAC2_gc_cog <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121960.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698.cog.tab.txt", gc_thresh = 0.1, output = FALSE)
RAMLI_gc_pfam <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121950.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690.pfam.tab.txt", gc_thresh = 0.1, output = FALSE)
BAC1_gc_pfam <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121951.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691.pfam.tab.txt", gc_thresh = 0.1, output = FALSE)
BAC2_gc_pfam <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121960.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698.pfam.tab.txt", gc_thresh = 0.1, output = FALSE)
RAMLI_gc_KO <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121950.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690.ko.tab.txt", gc_thresh = 0.1, output = FALSE)
BAC1_gc_KO <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121951.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691.ko.tab.txt", gc_thresh = 0.1, output = FALSE)
BAC2_gc_KO <- gc2function(seq_id_gc = "GC_analysis/seqid_GC_121960.assembled.gff.tsv", gene_id_seq_id ="./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698_gene_oid_2_seq_id.txt",
functions = "./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698.ko.tab.txt", gc_thresh = 0.1, output = FALSE)
```
# *4. Analysis of gene length distribution*
Here we use the dataframe made in the previous section to see if there is a significant difference in the gene length of the COGs within these three consensus genomes.
Observation: They have very small genes: on average < 500bp.
```{r gene-length-analysis_COG, warning = FALSE, fig.width = 10, fig.height = 3.5, dpi=500, include = FALSE}
# Ramlibacter sp. MAG gene length distribution
p_RAMLI_length <- easyGgplot2::ggplot2.histogram(data = RAMLI_gc_cog, xName = 'gene_length',
groupName = 'Genome', alpha = 0.5,
legendPosition = "top", binwidth = 0.15,
groupColors = col_RAMLI,addMeanLine=TRUE, meanLineColor="black",
meanLineType="dashed")+ theme_bw()+ ylim(0,15)+
labs(x = "Gene length (bp)", y = "Count")+ theme(legend.position="none")+
ggtitle("Ramlibacter sp. MAG")+ xlim(0,2000)
# Bacteroidetes MAG1 gene length distribution
p_BAC1_length <- easyGgplot2::ggplot2.histogram(data = BAC1_gc_cog, xName = 'gene_length',
groupName = 'Genome', alpha = 0.5,
legendPosition = "top", binwidth = 0.15,
groupColors = col_bac1,addMeanLine=TRUE, meanLineColor="black",
meanLineType="dashed")+ theme_bw()+ ylim(0,15)+
labs(x = "Gene length (bp)", y = "Count")+ theme(legend.position="none")+
ggtitle("Bacteroidetes MAG1")+ xlim(0,2000)
# Bacteroidetes MAG2 gene length distribution
p_BAC2_length <- easyGgplot2::ggplot2.histogram(data = BAC2_gc_cog, xName = 'gene_length',
groupName = 'Genome', alpha = 0.5,
legendPosition = "top", binwidth = 0.15,
groupColors = col_bac2,addMeanLine=TRUE, meanLineColor="black",
meanLineType="dashed")+ theme_bw()+ ylim(0,15)+
labs(x = "Gene length (bp)", y = "Count")+ theme(legend.position="none")+
ggtitle("Bacteroidetes MAG2")+ xlim(0,2000)
grid.arrange(p_RAMLI_length, p_BAC1_length, p_BAC2_length, ncol = 3)
```
We can do the same for the Pfams.
```{r gene-length-analysis_Pfam, warning = FALSE, fig.width = 10, fig.height = 3.5, dpi=500, include = FALSE}
# Ramlibacter sp. MAG gene length distribution
p_RAMLI_length <- easyGgplot2::ggplot2.histogram(data = RAMLI_gc_pfam, xName = 'gene_length',
groupName = 'Genome', alpha = 0.5,
legendPosition = "top", binwidth = 0.15,
groupColors = col_RAMLI,addMeanLine=TRUE, meanLineColor="black",
meanLineType="dashed")+ theme_bw()+ ylim(0,25)+
labs(x = "Gene length (bp)", y = "Count")+ theme(legend.position="none")+
ggtitle("Ramlibacter sp. MAG")+ xlim(0,3000)
# Bacteroidetes MAG1 gene length distribution
p_BAC1_length <- easyGgplot2::ggplot2.histogram(data = BAC1_gc_pfam, xName = 'gene_length',
groupName = 'Genome', alpha = 0.5,
legendPosition = "top", binwidth = 0.15,
groupColors = col_bac1,addMeanLine=TRUE, meanLineColor="black",
meanLineType="dashed")+ theme_bw()+ ylim(0,25)+
labs(x = "Gene length (bp)", y = "Count")+ theme(legend.position="none")+
ggtitle("Bacteroidetes MAG1")+ xlim(0,3000)
# Bacteroidetes MAG2 gene length distribution
p_BAC2_length <- easyGgplot2::ggplot2.histogram(data = BAC2_gc_pfam, xName = 'gene_length',
groupName = 'Genome', alpha = 0.5,
legendPosition = "top", binwidth = 0.15,
groupColors = col_bac2,addMeanLine=TRUE, meanLineColor="black",
meanLineType="dashed")+ theme_bw()+ ylim(0,25)+
labs(x = "Gene length (bp)", y = "Count")+ theme(legend.position="none")+
ggtitle("Bacteroidetes MAG2")+ xlim(0,3000)
grid.arrange(p_RAMLI_length, p_BAC1_length, p_BAC2_length, ncol = 3)
```
# 5. Identify unique functional genes (COG/Pfams)
```{r identify-unique-cog, include = FALSE}
# Find unique functions in Ramlibacter sp. MAG vs Bacteroidetes MAG1
unique_RAMLI_BAC1 <- dplyr::anti_join(RAMLI_gc_cog, BAC1_gc_cog, by = "cog_id")
cat("There are", paste(nrow(unique_RAMLI_BAC1)), "unique COGs in Ramlibacter sp. MAG vs Bacteroidetes MAG1")
# Find unique functions in Ramlibacter sp. MAG vs Bacteroidetes MAG2
unique_RAMLI_BAC2 <- dplyr::anti_join(RAMLI_gc_cog, BAC2_gc_cog, by = "cog_id")
cat("There are", paste(nrow(unique_RAMLI_BAC2)), "unique COGs in Ramlibacter sp. MAG vs Bacteroidetes MAG2")
# Find unique functions in Bacteroidetes MAG1 vs Bacteroidetes MAG2
unique_BAC1_BAC2 <- dplyr::anti_join(BAC1_gc_cog, BAC2_gc_cog, by = "cog_id")
cat("There are", paste(nrow(unique_BAC1_BAC2)), "unique COGs in Bacteroidetes MAG1 vs Bacteroidetes MAG2")
# Find unique functions in Bacteroidetes MAG1 vs Bacteroidetes MAG2
unique_BAC2_BAC1 <- dplyr::anti_join(BAC2_gc_cog, BAC1_gc_cog, by = "cog_id")
cat("There are", paste(nrow(unique_BAC2_BAC1)), "unique COGs in Bacteroidetes MAG2 vs Bacteroidetes MAG1")
```
```{r identify-unique-pfam, include = FALSE}
# Find unique functions in Ramlibacter sp. MAG vs Bacteroidetes MAG1
unique_pfam_RAMLI_BAC1 <- dplyr::anti_join(RAMLI_gc_pfam, BAC1_gc_pfam, by = "pfam_id")
cat("There are", paste(nrow(unique_pfam_RAMLI_BAC1)), "unique Pfams in Ramlibacter sp. MAG vs Bacteroidetes MAG1")
# Find unique functions in Ramlibacter sp. MAG vs Bacteroidetes MAG2
unique_pfam_RAMLI_BAC2 <- dplyr::anti_join(RAMLI_gc_pfam, BAC2_gc_pfam, by = "pfam_id")
cat("There are", paste(nrow(unique_pfam_RAMLI_BAC2)), "unique Pfams in Ramlibacter sp. MAG vs Bacteroidetes MAG2")
# Find unique functions in Bacteroidetes MAG1 vs Bacteroidetes MAG2
unique_pfam_BAC1_BAC2 <- dplyr::anti_join(BAC1_gc_pfam, BAC2_gc_pfam, by = "pfam_id")
cat("There are", paste(nrow(unique_pfam_BAC1_BAC2)), "unique Pfams in Bacteroidetes MAG1 vs Bacteroidetes MAG2")
# Find unique functions in Bacteroidetes MAG1 vs Bacteroidetes MAG2
unique_pfam_BAC2_BAC1 <- dplyr::anti_join(BAC2_gc_pfam, BAC1_gc_pfam, by = "pfam_id")
cat("There are", paste(nrow(unique_pfam_BAC2_BAC1)), "unique Pfams in Bacteroidetes MAG2 vs Bacteroidetes MAG1")
```
# 6. COG functional categories
Get COG ID to COG functional category mapping file here: ftp://ftp.ncbi.nih.gov/pub/wolf/COGs/COG0303/cogs.csv
The exact statistical analysis to compare genomes based on these profiles should be performed in STAMP.
```{r COG functional categories, dpi = 300, warning = FALSE, fig.width = 5, fig.height = 15, include = FALSE}
# Import COG mapping file
cogid_2_cogcat <- read.csv("./Mapping_files/cogid_2_cogcat.csv", sep = ",", header = FALSE, fill = TRUE,col.names = c("COG_ID", "COG_class", "function"))[, 1:2]
cogid_2_cogcat <- cogid_2_cogcat[(cogid_2_cogcat$COG_class)!="", ]
cogid_2_cogcat <- droplevels(cogid_2_cogcat)
# Read COG category file
cog_categories <- read.table("./Mapping_files/cog_categories.tsv", header = TRUE, sep = "\t")
# Merge COG metadata
cog_meta <- dplyr::left_join(cog_categories, cogid_2_cogcat, by = c("COG_class" = "COG_class"))
cog_meta <- droplevels(cog_meta)
# Merge genome information of all genome bins
merged_gc_cog <- rbind(RAMLI_gc_cog, BAC1_gc_cog, BAC2_gc_cog)
merged_gc_cog <- data.frame(merged_gc_cog, genome_id = c(rep("Ramlibacter sp. MAG", nrow(RAMLI_gc_cog)),
rep("Bacteroidetes MAG1", nrow(BAC1_gc_cog)),
rep("Bacteroidetes MAG2", nrow(BAC2_gc_cog)))
)
# Merge this metadata with the genome data from before
# COGs with multiple classifications are currently still NA - work on this.
merged_gc_cog <- dplyr::left_join(merged_gc_cog, cog_meta, by = c("cog_id" = "COG_ID"))
merged_gc_cog <- merged_gc_cog[!is.na(merged_gc_cog$COG_functional_category),]
# Visualize distribution across major metabolism functional COG groups per genome.
p_cog_func_group <- ggplot(data = merged_gc_cog,
aes(x=COG_functional_category, fill = COG_functional_cluster))+
geom_bar(stat="count", width=0.7, color = "black", size = 0.75)+
theme_bw()+
facet_grid(genome_id~.)+
scale_fill_brewer(palette = "Accent")+
labs(x = "Gene length (bp)", y = "Count")+
theme(legend.position="bottom", axis.text.x = element_text(angle = 90, hjust = 1),
legend.text = element_text(size = 5))+
guides(fill=guide_legend(nrow=2,byrow=TRUE))
print(p_cog_func_group)
p_cog_func_clust <- ggplot(data = merged_gc_cog,
aes(x=COG_functional_cluster, fill = COG_functional_cluster))+
geom_bar(stat="count", width=0.7, color = "black", size = 0.75)+
theme_bw()+
facet_grid(genome_id~.)+
scale_fill_brewer(palette = "Accent")+
labs(x = "Gene length (bp)", y = "Count")+
theme(legend.position="bottom",axis.text.x = element_text(angle = 90, hjust = 1),
legend.text = element_text(size = 5))+
guides(fill=guide_legend(nrow=2,byrow=TRUE))
print(p_cog_func_clust)
```
# 7. KO pathways
* Get reference file that maps KO ids to pathways here: http://www.genome.jp/kegg-bin/get_htext?ko0000.keg (download htext).
```{r KO pathways, dpi = 300, warning = FALSE, fig.width = 12, fig.height = 13, include = FALSE}
# Import data
ko_path_df <- format_ko(path = "./Mapping_files/ko00000.keg")
# Annotate merged ko file
merged_gc_ko <- rbind(RAMLI_gc_KO, BAC1_gc_KO, BAC2_gc_KO)
merged_gc_ko <- data.frame(merged_gc_ko,
genome_id = c(rep("Ramlibacter sp. MAG", nrow(RAMLI_gc_KO)),
rep("Bacteroidetes MAG1", nrow(BAC1_gc_KO)),
rep("Bacteroidetes MAG2", nrow(BAC2_gc_KO)))
)
merged_gc_ko$ko_id <- gsub(merged_gc_ko$ko_id, pattern = "KO:", replacement = "")
merged_gc_ko <- dplyr::left_join(merged_gc_ko, ko_path_df[, c(1, 4:6)], by = "ko_id")
# Remove EC column because it allows duplicates for same functional classification
merged_gc_ko <- merged_gc_ko %>% select(-EC) %>% distinct()
# Fill up NA slots with "Unknown" pathway
merged_gc_ko$ko_level_A[is.na(merged_gc_ko$ko_level_A)] <- "Unknown"
merged_gc_ko$ko_level_B[is.na(merged_gc_ko$ko_level_B)] <- "Unknown"
merged_gc_ko$ko_level_C[is.na(merged_gc_ko$ko_level_C)] <- "Unknown"
```
# 8. Synonymous Codon Usage Bias analysis using CodonO
* Get CodonO for linux here: http://sysbio.cvm.msstate.edu/software/CodonO/download
* Run `CU.linux input.genes.fna`
* Output from CodonO:
inputfile.ok ---- the SCUO units for each input sequence based on its order
inputfile.fik ---- the composition ratio of the i-th amino acid in the k-th sequence
inputfile.hijk ---- the frequency of the j-th degenerate codon for amino acid i in each sequence
* This output was not sufficient to perform any analysis. Therefore I used the web browser to calculate the synonymous codon bias in the genes of the three genomes.
** Codon bias is proportional to mRNA production (Wan et al 2004)
** However, strong correlation between SCUO and %GC has been reported, thereby
confounding possible "biological" effects.. Beware..
```{r Codon bias, dpi = 300, warning = FALSE, fig.width = 7, fig.height = 8}
# Import and format data for Ramlibacter sp. MAG
SCUO_RAMLI <- read.table("./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/2724679690.genes.fna.codonO.output",
sep = ",", blank.lines.skip = TRUE, allowEscapes = FALSE, skipNul = TRUE
)
SCUO_RAMLI$V1 <- gsub(SCUO_RAMLI$V1, pattern = "\t", replacement = "")
Gene_RAMLI <- do.call(rbind, strsplit(SCUO_RAMLI$V1[grep("Ga0*", SCUO_RAMLI$V1)], " "))[,2]
SCUO_RAMLI$V1 <- gsub(SCUO_RAMLI$V1, pattern = " ", replacement = "")
SCUO_RAMLI <- data.frame(GC = SCUO_RAMLI$V1[grep(x = SCUO_RAMLI$V1, pattern = "GC*.*=")],
SCUO = rep(SCUO_RAMLI$V1[grep(x = SCUO_RAMLI$V1, pattern = "SCUO*")], each = 4),
Gene = rep(Gene_RAMLI, each = 4)
)
SCUO_RAMLI$GC <- as.numeric(gsub(SCUO_RAMLI$GC, pattern = ".*=", replacement = ""))
SCUO_RAMLI$SCUO <- as.numeric(gsub(SCUO_RAMLI$SCUO, pattern = ".*=", replacement = ""))
# Import and format data for Bacteroidetes MAG1
SCUO_BAC1 <- read.table("./IMG_annotation/IMG_2724679691_Bacteroidetes_bin1/Annotation/2724679691.genes.fna.codonO.output",
sep = ",", blank.lines.skip = TRUE, allowEscapes = FALSE, skipNul = TRUE)
SCUO_BAC1$V1 <- gsub(SCUO_BAC1$V1, pattern = "\t", replacement = "")
Gene_BAC1 <- do.call(rbind, strsplit(SCUO_BAC1$V1[grep("Ga0*", SCUO_BAC1$V1)], " "))[,2]
SCUO_BAC1$V1 <- gsub(SCUO_BAC1$V1, pattern = " ", replacement = "")
SCUO_BAC1 <- data.frame(GC = SCUO_BAC1$V1[grep(x = SCUO_BAC1$V1, pattern = "GC*.*=")],
SCUO = rep(SCUO_BAC1$V1[grep(x = SCUO_BAC1$V1, pattern = "SCUO*")], each = 4),
Gene = rep(Gene_BAC1, each = 4)
)
SCUO_BAC1$GC <- as.numeric(gsub(SCUO_BAC1$GC, pattern = ".*=", replacement = ""))
SCUO_BAC1$SCUO <- as.numeric(gsub(SCUO_BAC1$SCUO, pattern = ".*=", replacement = ""))
# Import and format data for Bacteroidetes MAG2
SCUO_BAC2 <- read.table("./IMG_annotation/IMG_2724679698_Bacteroidetes_bin2/Annotation/2724679698.genes.fna.codonO.output",
sep = ",", blank.lines.skip = TRUE, allowEscapes = FALSE, skipNul = TRUE)
SCUO_BAC2$V1 <- gsub(SCUO_BAC2$V1, pattern = "\t", replacement = "")
Gene_BAC2 <- do.call(rbind, strsplit(SCUO_BAC2$V1[grep("Ga0*", SCUO_BAC2$V1)], " "))[,2]
SCUO_BAC2$V1 <- gsub(SCUO_BAC2$V1, pattern = " ", replacement = "")
SCUO_BAC2 <- data.frame(GC = SCUO_BAC2$V1[grep(x = SCUO_BAC2$V1, pattern = "GC*.*=")],
SCUO = rep(SCUO_BAC2$V1[grep(x = SCUO_BAC2$V1, pattern = "SCUO*")], each = 4),
Gene = rep(Gene_BAC2, each = 4)
)
SCUO_BAC2$GC <- as.numeric(gsub(SCUO_BAC2$GC, pattern = ".*=", replacement = ""))
SCUO_BAC2$SCUO <- as.numeric(gsub(SCUO_BAC2$SCUO, pattern = ".*=", replacement = ""))
# Merge data to one dataframe
SCUO_merged_gen <- data.frame(rbind(SCUO_RAMLI, SCUO_BAC1, SCUO_BAC2),
Genome_ID = c(rep("Ramlibacter sp. MAG", nrow(SCUO_RAMLI)), rep("Bacteroidetes MAG1", nrow(SCUO_BAC1)),
rep("Bacteroidetes MAG2", nrow(SCUO_BAC2))),
GCx = rep(c("GC_mean", "GC1", "GC2", "GC3"),
(nrow(SCUO_RAMLI) + nrow(SCUO_BAC1) + nrow(SCUO_BAC2))/4
)
)
# Merge codon bias data with KO pathway annotation
SCUO_merged <- dplyr::left_join(SCUO_merged_gen, merged_gc_ko[, c(1:2,4 ,14:21)], by = c("Gene" = "contig_geneID"))
# Visualize differences in codon bias
p_SCUO.1 <- ggplot(data = SCUO_merged, aes (x = 100*GC, y = SCUO, fill = Genome_ID))+
geom_point(size = 4, shape = 21, alpha = 0.7)+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme_bw()+
facet_wrap(~GCx, ncol = 2)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
axis.text.x = element_text(angle = 0, hjust = 1),
strip.text.x=element_text(size=18),
legend.position = "bottom")+
ylab("SCUO")+
xlab("%GC")+
ylim(0,1)
print(p_SCUO.1)
# Visualize differences in codon bias per codon position
p_SCUO.2 <- SCUO_merged %>% filter(GCx != "GC_mean") %>%
ggplot(aes (x = GCx, y = 100*GC, fill = Genome_ID))+
geom_jitter(size = 4, shape = 21, alpha = 0.1, width = 0.2)+
geom_boxplot(alpha = 0.2, size = 1.2, color = "darkorange")+
scale_fill_manual("", values = c(col_bac1, col_bac2, col_RAMLI))+
theme_bw()+
facet_wrap(~Genome_ID, ncol = 2)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
strip.text.x=element_text(size=18),
legend.position = "bottom")+
ylab("%GC")+
xlab("Codon position")+
guides(fill = FALSE)+
ylim(0,100)
print(p_SCUO.2)
# Subset to genes for which ko annotation is available
SCUO_merged_sb <- SCUO_merged[!is.na(SCUO_merged$ko_level_A), ]
SCUO_merged_sb <- SCUO_merged_sb[SCUO_merged_sb$GCx == "GC_mean", ]
# Look at pathways enriched in high %GC
# SCUO_merged_sb[]
SCUO_merged_gen_gcmean <- SCUO_merged_gen %>% dplyr::filter(GCx == "GC_mean")
p_SCUO.3 <- ggplot(data = SCUO_merged_gen_gcmean, aes (x = Genome_ID, y = SCUO))+
geom_jitter(size = 3, alpha = 0.3, shape = 21, aes(fill = Genome_ID))+
geom_boxplot(alpha=0, size =1.5, color = "darkorange")+
# scale_fill_brewer(palette = "Accent")+
scale_fill_manual(values = c(col_bac1, col_bac2, col_RAMLI))+
theme_bw()+
# facet_wrap(Genome_ID~GCx)+
theme(axis.text=element_text(size=14), axis.title=element_text(size=20),
title=element_text(size=20), legend.text=element_text(size=14),
legend.background = element_rect(fill="transparent"),
axis.text.x = element_text(angle = 45, hjust = 1),
strip.text.x=element_text(size=18))+
ylab("Codon bias - SCUO")+
xlab("")+
ylim(0,1)+
guides(fill=FALSE)+
scale_x_discrete(labels=c("Bacteroidetes MAG1" = paste("Bacteroidetes MAG1 (n=",table(SCUO_merged_gen_gcmean$Genome_ID)[1],")", sep = ""),
"Bacteroidetes MAG2" = paste("Bacteroidetes MAG2 (n=",table(SCUO_merged_gen_gcmean$Genome_ID)[2],")", sep = ""),
"Ramlibacter sp. MAG" = paste("Ramlibacter sp. MAG (n=",table(SCUO_merged_gen_gcmean$Genome_ID)[3],")", sep = ""))
)
#
print(p_SCUO.3)
tmp <- SCUO_merged_sb$genome_id
tmp2 <- cbind(SCUO_merged_sb$ko_id,
c(rep(col_RAMLI, table(tmp)[3]), rep(col_bac1, table(tmp)[1]), rep(col_bac2, table(tmp)[2]))
)
write.table(tmp2, file = "All_KO.tsv", quote = FALSE,
col.names = FALSE, row.names = FALSE)
# merge with annotation
tmp_SCUO <- dplyr::left_join(SCUO_merged_gen,
merged_gc_ko, by = c("Gene" = "contig_geneID"))
tmp_result_scuo <- tmp_SCUO %>% dplyr::filter(GCx == "GC_mean") %>%
dplyr::filter(grepl("ribosomal", ko_name) & genome_id == "Ramlibacter sp. MAG") %>%
dplyr::select(SCUO, Gene, ko_name, genome_id) %>%
distinct %>%
ggplot(., aes(x = genome_id, y = SCUO))+
geom_boxplot()
tmp_SCUO %>% dplyr::filter(GCx == "GC_mean") %>%
dplyr::filter(grepl("ribosomal", ko_name) & genome_id == "Ramlibacter sp. MAG") %>%
dplyr::select(SCUO, Gene, ko_name, genome_id) %>%
distinct %>%
summarise(mean(SCUO), sd(SCUO))
```
```{r compare-ramli-CB, dpi = 500, warning = FALSE, fig.width = 10, fig.height = 4, dev = c("png","pdf")}
# Import codonO results of reference genomes
ref_SCUO <- codonO_2_df(pathx = "./IMG_annotation/References/codonO_output/")
# reimport codonO results of RAMLI genome
Ramli_SCUO <- codonO_2_df(pathx = "./IMG_annotation/IMG_2724679690_Ramlibacter_bin/Annotation/",
patternx = "codonO")
# Merge dataframes
ref_RAMLI_SCUO <- rbind(ref_SCUO, Ramli_SCUO)
# Replace genome names by better annotated names
map_scuo <- read.delim("./Mapping_files/codonO_ref_names.tsv", stringsAsFactors = FALSE)
ref_RAMLI_SCUO$Genome <- as.character(ref_RAMLI_SCUO$Genome)
for(i in 1:nrow(map_scuo)){
ref_RAMLI_SCUO$Genome[ref_RAMLI_SCUO$Genome %in% map_scuo$codon_file[i]] <- map_scuo$ref_name[i]
}
ref_RAMLI_SCUO$Genome[ref_RAMLI_SCUO$Genome %in% "2724679690.genes.fna.codonO.output"] <- "Ramli. sp. MAG"