-
Notifications
You must be signed in to change notification settings - Fork 0
/
impact_of_seq_depth_analysis.R
1617 lines (1214 loc) · 54.3 KB
/
impact_of_seq_depth_analysis.R
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
# Impact of sequencing depth on the characterization of microbiome and resistome
# Rarefaction analysis of 2-4-8 study data
# Analysis of alpha-diversity and species richness
# Refactoring: enfrocing abstraction and tidyverse style guide
# Load packages -----------------------------------------------------------
library(readr)
library(tidyr)
library(dplyr)
library(stringr)
library(purrr)
library(foreach) # Is there a tidyverse alternative ? Perhaps iwalk?
library(ggplot2)
library(metagenomeSeq)
library(vegan)
library(scales)
library(PMCMR) # For posthoc statistical tests
library(here)
# Source utility functions ------------------------------------------------
# Load functions from another file
# Those functions were used throughout all this analyses
source(here('analysis_utility_functions.R'))
# Colour palettes ---------------------------------------------------------
# Same colour palette as the matplotlib_venn default color palette
# Consider adding them to the utility functions script
vennPalette <- c("#F8766D", "#00BA38", "#619CFF")
vennPalette <- rev(vennPalette)
# Colourblind friendly palette used in the submission
cbPalette <- c("#FFCD48", # Mango from Crayola palette
dichromat::colorschemes$Categorical.12[8], # Blue from dichromat package
dichromat::colorschemes$Categorical.12[12]) # Red from dichromat package
# Load and filter AMR and Kraken data -------------------------------------
# Results generated with Coverage Sampler and filtered with Python-Pandas
# Filtering involved keeping results with gene fraction >= 75% and
# removing all those results with genes that require SNP confirmation.
amrResultsFiltered <- read_csv(file.path(
'~',
'amr',
'2-4-8_results',
'2_4_8_study_RZ',
'amrResults_Aug2017_75_gene_frac/cov_sampler_parsed',
'amrFiltered_75_genefrac.csv')
)
amrReadstoHitRatio <- read_tsv('~/aafc/amr/amrplusplus_rarefaction_analysis/2_4_8_study_RZ/Results_Aug2017/reads_and_hits.tsv')
# Read Kraken concatenated and filtered file (no Eukaryotes, and no PhiX)
krakenResultsFiltered <- read.delim(file.path(
'~',
'amr',
'2-4-8_results',
'2_4_8_study_RZ',
'krakenResults_Aug2017',
'allKraken_FHQ',
'kraken_filtered',
'krakenConcat.tsv'),
stringsAsFactors = FALSE
)
# Remove D0.25_seqtk data from filtered data frame
amrResultsFiltered <- amrResultsFiltered %>%
filter(Sample_type != "D0.25_seqtk")
# Replace "Name" with "Gene" in headers of the filtered data frame
names(amrResultsFiltered) <- str_replace(names(amrResultsFiltered), "Name", "Gene")
# Convert AMR filtered results to "tidy" format in order to have a column with
# all AMR levels
amrResultsTidy <- amrResultsFiltered %>%
gather(Level, LevelName, c(1,6:8))
# Change the names of the AMR sequencing depths columns
# Make this more like functional programming, ideally with purrr
amrResultsTidy$Depth <- str_replace(amrResultsTidy$Sample, "\\d+_","")
amrResultsTidy$Depth <- str_replace(amrResultsTidy$Depth, "\\d$","")
amrResultsTidy$Depth <- str_replace(amrResultsTidy$Depth, "full", "D1")
amrResultsTidy$Depth <- str_replace(amrResultsTidy$Depth, "half", "D0.5")
amrResultsTidy$Depth <- str_replace(amrResultsTidy$Depth, "quar*", "D0.25")
# Load filtered AMR data --------------------------------------------------
# Start here if AMR results have been filtered already
# Tidy the dataset
amrResultsTidy <- amrResultsFiltered %>%
gather(Category, CategoryName, c(1:4))
amrResultsTidy$Category <- factor(amrResultsTidy$Category,
levels = c('Class',
'Mechanism',
'Group',
'Gene'))
amrCategories <- levels(amrResultsTidy$Category)
krakenTaxa <- levels(krakenResultsFiltered$TaxRank)
# Split results by categories ---------------------------------------------
# Will adopt the split, apply, combine strategy
# Using the names of the AMR categories and taxonomic ranks as names of the
# elements of the lists
amrResultsList <- amrResultsTidy %>%
split(.$Category) %>% #splitting dataframe using base R but with purrr's magrittr piping
set_names(nm=amrCategories)
krakenResultsList <- krakenResultsFiltered %>%
split(.$TaxRank) %>%
set_names(nm=krakenTaxa)
# Summarize results(sum) --------------------------------------------------
amrResultsSummary <- lapply(amrResultsList, function(x){
summarizeAMRbyCategory(x)
})
krakenResultsSummary <- lapply(krakenResultsList, function(x){
summarizeKrakenbyTaxID(x)
})
# Convert results to wide format ------------------------------------------
# Potentially can use the same function and a list/vector of AMR and Kraken
# results to avoid duplication
amrResultsWide <- lapply(amrResultsSummary, function(x){
widenAMR(x)
})
krakenResultsWide <- lapply(krakenResultsSummary, function(x){
widenKraken(x)
})
# Convert wide to matrix --------------------------------------------------
# TODO: Perhaps group these lapply statements calling anonymous functions
# into larger functions?
amrResultsMat <- lapply(amrResultsWide, function(x){
matrixAMR(x)
})
krakenResultsMat <- lapply(krakenResultsWide, function(x){
matrixKraken(x)
})
# Transpose matrices
# Awesome!!!
amrResultsMat <- lapply(amrResultsMat, function(x){
t(x)
})
krakenResultsMat <- lapply(krakenResultsMat, function(x){
t(x)
})
# CSS Normalization -------------------------------------------------------
# Transform dataframes into wide format
# Fill NAs with a value of zero
# Splitting by Depth
amrResultsbyDepth <- amrResultsFiltered %>%
split(.$Sample_type)
amrAnalytical <- lapply(amrResultsbyDepth, function(x){
amrAnalyticWide <- x %>%
select(Gene, Hits, Sample) %>%
spread(Sample, Hits, fill = 0, convert = TRUE)
return(amrAnalyticWide)
})
# lapply(amrResultsbyDepth, function(x){
# amrResultsWide <- x %>%
# group_by(Sample) %>%
# select(Sample, Hits, CategoryName) %>%
# mutate(id=1:n()) %>%
# spread(key=Sample, value=Hits, fill = 0) %>%
# select(-id)
# return(amrResultsWide)
# })
#
krakenResultsbyDepth <- krakenResultsFiltered %>%
split(.$Sample_Type)
krakenAnalytical <- lapply(krakenResultsbyDepth, function(x){
krakenAnalyticWide <- x %>%
select(TaxID, CladeReads, Sample) %>%
spread(Sample, CladeReads, fill = 0, convert = TRUE)
return(krakenAnalyticWide)
})
amrAnalytical <- lapply(amrAnalytical, function(x){
amrAnaMat <- matrixAMRanalytical(x)
return(amrAnaMat)
})
krakenAnalytical <- lapply(krakenAnalytical, function(x){
krakenAnaMat <- matrixKraken(x)
return(krakenAnaMat)
})
krakenTaxInfo <- krakenResultsFiltered %>% select(2:ncol(.))
krakenTaxInfo$TaxID <- as.character(krakenTaxInfo$TaxID)
amrExp <- lapply(amrAnalytical, function(x){
amrMR <- newMRexperiment(x[rowSums(x) > 0, ])
return(amrMR)
})
krakenExp <- lapply(krakenAnalytical, function(x){
krakenMR <- newMRexperiment(x[rowSums(x) > 0, ])
return(krakenMR)
})
amrNorm <- lapply(amrExp, function(x){
amrCSS <- cumNorm(x)
})
amrNorm <- lapply(amrNorm, function(x){
amrCSSdf <- data.frame(MRcounts(x, norm = T))
})
krakenNorm <- lapply(krakenExp, function(x){
krakenCSS <- cumNorm(x)
})
krakenNorm <- lapply(krakenNorm, function(x){
krakenCSSdf <- data.frame(MRcounts(x, norm = T))
})
amrAnnotations <- read_tsv('amr_genes.tabular_parsed.tab')
# amrQuarter <- amrResultsFiltered %>%
# filter(Sample_type == "D0.25") %>%
# select(Gene) %>%
# distinct(Gene)
#
# amrHalf <- amrResultsTidy %>%
# filter(Sample_type == "D0.5" & Category == "Gene") %>%
# select(CategoryName) %>%
# distinct(CategoryName)
#
# amrFull <- amrResultsTidy %>%
# filter(Sample_type == "D1" & Category == "Gene") %>%
# select(CategoryName) %>%
# distinct(CategoryName)
#
names(amrAnnotations) <- c("Gene", "Class", "Mechanism", "Group")
amrNormAnnot <- lapply(amrNorm, function(x){
x$Gene <- row.names(x)
amrAnnotated <- left_join(amrAnnotations, x, by="Gene") %>%
na.omit()
return(amrAnnotated)
})
krakenNormAnnot <- lapply(krakenNorm, function(x){
x$TaxID <- row.names(x)
krakenAnnotated <- left_join(krakenTaxInfo, x, by="TaxID") %>%
na.omit() %>%
select(-matches("Sample", "SampleType"))
return(krakenAnnotated)
})
# Tidy normalized, annotated datasets -------------------------------------
amrNormTidy <- lapply(amrNormAnnot, function(x){
x %>%
gather(key = samples, value = normCounts, 5:ncol(x)) %>%
gather(key = category, value = categoryNames, 1:4)
})
krakenNormTidy <- lapply(krakenNormAnnot, function(x){
x %>%
gather(key = samples, value = normCounts, 8:ncol(x))
})
# Split, apply, combine: aggregate AMR and Kraken -------------------------
# Join the data from all depths, then split by AMR category and taxonomy
amrAllDepths <- do.call("rbind", amrNormTidy)
amrAllDepths$SampleType <- str_extract(amrAllDepths$samples, "^[A-Z]+")
krakenAllDepths <- do.call("rbind", krakenNormTidy)
krakenAllDepths$SampleType <- str_extract(krakenAllDepths$samples, "^[A-Z]+")
amrNormAgg <- amrAllDepths %>%
split(.$category)
amrNormAgg <- lapply(amrNormAgg, function(x){
group_by(x, categoryNames, samples) %>%
summarise(normCountsSum = sum(normCounts))
})
amrNormDivMat <- lapply(amrNormAgg, function(x){
amrNormWide <- spread(x, key=categoryNames, value=normCountsSum, fill=0)
row.names(amrNormWide) <- amrNormWide$samples
amrNormWide <- amrNormWide %>%
select(2:ncol(amrNormWide))
return(amrNormWide)
})
# Normalized diversity indices --------------------------------------------
amrDiversity <- lapply(amrNormDivMat, function(x){
observed_richness <- specnumber(x, MARGIN=1)
invsimpson <- diversity(x, index="invsimpson", MARGIN=1)
simpson <- diversity(x, index="simpson", MARGIN=1)
shannon <- diversity(x, index="shannon", MARGIN=1)
evenness <- shannon/log(observed_richness)
return(list(observed_richness=observed_richness,
invsimpson = invsimpson,
simpson = simpson,
shannon = shannon,
evenness=evenness))
})
amrEstimated <- lapply(amrNormDivMat, function(x){
specpool(x, sampleMetadata$SampleType)
})
amrDiversityDF <- lapply(amrDiversity, function(x) data.frame(
ID=names(x$observed_richness),
InvSimpson=as.numeric(x$invsimpson),
Simpson = as.numeric(x$simpson),
Shannon=as.numeric(x$shannon),
Evenness=as.numeric(x$evenness)
))
amrDiversityDF <- do.call("rbind", amrDiversityDF)
amrDiversityDF <- amrDiversityDF %>%
mutate(Level=row.names(amrDiversityDF)) %>%
mutate(Level=str_extract(Level, "^\\w+")) %>%
mutate(Depth=str_extract(ID, "^[A-Z]+")) %>%
mutate(Depth=str_replace(Depth,"F", "D1")) %>%
mutate(Depth=str_replace(Depth,"H", "D0.5")) %>%
mutate(Depth=str_replace(Depth, "Q", "D0.25"))
amrDiversityDF$Level <- factor(amrDiversityDF$Level,
levels = c(
"Class",
"Mechanism",
"Group",
"Gene"
)
)
amrEstimatedDF <- do.call("rbind", amrEstimated)
amrEstimatedDF <- amrEstimatedDF %>%
mutate(amrLevel=row.names(amrEstimatedDF)) %>%
separate(amrLevel,
into = c("Level", "Depth"),
sep="\\.")
krakenNormAgg <- krakenAllDepths %>%
split(.$TaxRank)
krakenNormAgg <- lapply(krakenNormAgg, function(x){
group_by(x, TaxID, samples) %>%
summarise(normCountsSum = sum(normCounts))
})
krakenNormDivMat <- lapply(krakenNormAgg, function(x){
krakenNormWide <- spread(x, key=TaxID, value=normCountsSum, fill=0)
row.names(krakenNormWide) <- krakenNormWide$samples
krakenNormWide <- krakenNormWide %>%
select(2:ncol(krakenNormWide))
return(krakenNormWide)
})
krakenDiversity <- lapply(krakenNormDivMat, function(x){
observed_richness <- specnumber(x, MARGIN=1)
invsimpson <- diversity(x, index="invsimpson", MARGIN=1)
simpson <- diversity(x, index="simpson", MARGIN=1)
shannon <- diversity(x, index="shannon", MARGIN=1)
evenness <- shannon/log(observed_richness)
return(list(observed_richness=observed_richness,
invsimpson = invsimpson,
simpson = simpson,
shannon = shannon,
evenness=evenness))
})
krakenEstimated <- lapply(krakenNormDivMat, function(x){
specpool(x, sampleMetadata$SampleType)
})
krakenDiversityDF <- lapply(krakenDiversity, function(x) data.frame(
ID=names(x$observed_richness),
InvSimpson=as.numeric(x$invsimpson),
Simpson = as.numeric(x$simpson),
Shannon=as.numeric(x$shannon),
Evenness=as.numeric(x$evenness)
))
krakenDiversityDF <- do.call("rbind", krakenDiversityDF)
krakenDiversityDF <- krakenDiversityDF %>%
mutate(taxLevel=row.names(krakenDiversityDF)) %>%
separate(taxLevel, into=c("Level", "sample_number"), sep="\\.") %>%
select(-sample_number) %>%
filter(!Level %in% c("-", "D")) %>%
mutate(Depth = str_extract(ID, "^[A-Z]+"))
krakenDiversityDF$Level <- str_replace(krakenDiversityDF$Level, "P", "Phylum")
krakenDiversityDF$Level <- str_replace(krakenDiversityDF$Level, "C", "Class")
krakenDiversityDF$Level <- str_replace(krakenDiversityDF$Level, "O", "Order")
krakenDiversityDF$Level <- str_replace(krakenDiversityDF$Level, "F", "Family")
krakenDiversityDF$Level <- str_replace(krakenDiversityDF$Level, "G", "Genus")
krakenDiversityDF$Level <- str_replace(krakenDiversityDF$Level, "S", "Species")
krakenDiversityDF$Depth <- str_replace(krakenDiversityDF$Depth, "F", "D1")
krakenDiversityDF$Depth <- str_replace(krakenDiversityDF$Depth, "H", "D0.5")
krakenDiversityDF$Depth <- str_replace(krakenDiversityDF$Depth, "QD", "D0.25")
krakenDiversityDF$Level <- factor(krakenDiversityDF$Level,
levels = c('Phylum',
'Class',
'Order',
'Family',
'Genus',
'Species'))
krakenEstimatedDF <- do.call("rbind", krakenEstimated)
krakenEstimatedDF <- krakenEstimatedDF %>%
mutate(krakenLevel=row.names(krakenEstimatedDF)) %>%
separate(krakenLevel,
into = c("Level", "Depth"),
remove = TRUE)
write_csv(krakenEstimatedDF, '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/kraken_estimated_richness.csv')
write_csv(amrEstimatedDF, '~/amr/2-4-8_results/2_4_8_study_RZ/amrResults_Aug2017_75_gene_frac/amr_estimated_richness.csv')
# Normalized boxplots -----------------------------------------------------
amrShannonBoxplot <- amrDiversityDF %>%
amrShannon()
ggsave(filename = 'amrShannon.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/amrResults_Aug2017_75_gene_frac/alphaDiversity/',
plot = amrShannonBoxplot,
width = 10.50,
height = 8.50,
units = "in")
amrInvSimpsonBoxplot <- amrDiversityDF %>%
amrAlphaDiv()
ggsave(filename = 'amrInvSimpson.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/amrResults_Aug2017_75_gene_frac/alphaDiversity/',
plot = amrInvSimpsonBoxplot,
width = 10.50,
height = 8.50,
units = "in")
krakenShannonBoxplot <- krakenDiversityDF %>%
krakenShannon()
ggsave(filename = 'krakenShannon.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenShannonBoxplot,
width = 10.50,
height = 8.50,
units = "in")
krakenInvSimpsonBoxplot <- krakenDiversityDF %>%
krakenAlphaDiv()
ggsave(filename = 'krakenInvSimpson.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenInvSimpsonBoxplot,
width = 10.50,
height = 8.50,
units = "in")
# Construction of rarefaction curves --------------------------------------
# AMR curves built from the Coverage Sampler results
# This step requires optimization (parallel mapping or compiling, maybe?)
# Use microbenchmark to compare between the two approaches
#mbm <- microbenchmark(
# mapping = map(amrResultsMat, function(x){
# raremax <- min(rowSums(x))
# rarecurve(x, step=5, sample=raremax)}),
# multicore = mclapply(amrResultsMat, function(x){
# raremax <- min(rowSums(x))
# rarecurve(x, step=5, sample=raremax)}, mc.cores=12),
# times=2
#)
# Results
# Unit: seconds
# expr min lq mean median uq max neval
# mapping 432.4910 432.4910 439.0898 439.0898 445.6887 445.6887 2
# multicore 140.0049 140.0049 140.8782 140.8782 141.7515 141.7515 2
# mclapply wins!
# purrr version
#amrRarefy <- map(amrResultsMat, function(x){
# raremax <- min(rowSums(x))
# rarecurve_ROP(x, step=5, sample=raremax)
#})
# mclapply version (and the winner!)
amrRarCurve <- mclapply(amrResultsMat, function(x){
raremax <- min(rowSums(x))
rarecurve(x, step=10000, sample=raremax)
},mc.cores=10)
krakenRarCurve <- mclapply(krakenResultsMat, function(x){
raremax <- min(rowSums(x))
rarecurve(x, step=1000, sample=raremax)
},mc.cores=10)
krakenRarCurveNoSample <- mclapply(krakenResultsMat, function(x){
rarecurve(x, step=1000)
},mc.cores=10)
# Rename list of rarefied data using the sample names
# Need to think of a better way to extract the sample names
amrSamples <- rownames(amrResultsMat[["Class"]])
krakenSamples <- rownames(krakenResultsMat[["D"]])
# Review syntax here
# Might need to add function to utility function list
amrRarCurve <- mclapply(amrRarCurve, function(x){
set_names(x,amrSamples)}, mc.cores=3)
krakenRarCurve <- mclapply(krakenRarCurve, function(x){
set_names(x,krakenSamples)}, mc.cores=10)
# Generate list of dataframes
# Hacky, but it works. Need to make it cleaner and faster.
amrRarCurve <- amrRarCurve %>%
map(as_vector)
krakenRarCurve <- krakenRarCurve %>%
map(as_vector)
amrRarCurveDF <- map(amrRarCurve, function(x) as_tibble(x, attr(x, "names")))
krakenRarefyDF <- map(krakenRarCurve, function(x) as_tibble(x, attr(x, "names")))
# Split rownames in order to generate columns with useful information
amrRarCurveDF <- mclapply(amrRarCurveDF, function(x) {
x$Sample <- row.names(x)
x$Subsample <- str_extract(x$Sample, "N\\d+")
x$Subsample <- as.numeric(str_replace(x$Subsample, "N",""))
x$SampleID <- str_replace(x$Sample, "\\.N.*$", "")
x$Depth <- str_replace(x$Sample, "_.*", "")
x
},
mc.cores=3
)
krakenRarefyDF <- mclapply(krakenRarefyDF, function(x) {
x$Sample <- row.names(x)
x$Subsample <- str_extract(x$Sample, "\\.N\\d+")
x$Subsample <- as.numeric(str_replace(x$Subsample, "\\.N",""))
x$Depth <- str_replace(x$Sample, "_.*", "")
x$SampleID <- str_extract(x$Sample, "_.*\\.")
x$SampleID <- str_replace(x$SampleID, "_", "")
x$SampleID <- str_replace(x$SampleID, "\\.", "")
x$Sample <- str_replace(x$Sample, "\\.N.*$", "")
x
},
mc.cores=10
)
amrRarCurveDF <- do.call("rbind", amrRarCurveDF)
amrRarCurveDF$AMRLevel <- row.names(amrRarCurveDF)
amrRarCurveDF$AMRLevel <- str_extract(amrRarCurveDF$AMRLevel, "^\\w+")
amrRarCurveDF$Depth <- str_replace(amrRarCurveDF$Depth, "F", "D1")
amrRarCurveDF$Depth <- str_replace(amrRarCurveDF$Depth, "H", "D0.5")
amrRarCurveDF$Depth <- str_replace(amrRarCurveDF$Depth, "QD", "D0.25")
krakenRarefyDF <- do.call("rbind", krakenRarefyDF)
krakenRarefyDF$krakenLevel <- row.names(krakenRarefyDF)
krakenRarefyDF$krakenLevel <- str_extract(krakenRarefyDF$krakenLevel, "^.\\.")
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "\\.", "")
krakenRarefyDF$Depth <- str_replace(krakenRarefyDF$Depth, "F", "D1")
krakenRarefyDF$Depth <- str_replace(krakenRarefyDF$Depth, "H", "D0.5")
krakenRarefyDF$Depth <- str_replace(krakenRarefyDF$Depth, "QD", "D0.25")
amrRarCurveDF$AMRLevel <- factor(amrRarCurveDF$AMRLevel,
levels = c('Class', 'Mechanism', 'Group', 'Gene'))
amrAlphaRarefactionDF$Level <- factor(amrAlphaRarefactionDF$Level,
levels = c('Class', 'Mechanism', 'Group', 'Gene'))
# Need to apply more functional programming
krakenRarefyDF <- krakenRarefyDF %>% filter(!krakenLevel %in% c("-", "D"))
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "P", "Phyla")
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "C", "Classes")
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "O", "Orders")
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "F", "Families")
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "G", "Genera")
krakenRarefyDF$krakenLevel <- str_replace(krakenRarefyDF$krakenLevel, "S", "Species")
amrRarCurveDF <- amrRarCurveDF %>%
mutate(AMRLevel=str_replace(AMRLevel,"Class","Classes")) %>%
mutate(AMRLevel=str_replace(AMRLevel,"Mechanism","Mechanisms")) %>%
mutate(AMRLevel=str_replace(AMRLevel,"Group","Groups")) %>%
mutate(AMRLevel=str_replace(AMRLevel,"Gene","Genes"))
# Split AMR data frame and generate rarefaction curves for each AMR level
amrAllList <- amrRarCurveDF %>%
split(.$AMRLevel)
amrAllRarCurves <- amrAllList %>%
map(function(x){
amrRarefactionCurve(x)
})
# Split Kraken data frame and generate rarefaction curves for each taxonomic level
krakenAllRarCurveList <- krakenRarefyDF %>%
split(.$krakenLevel)
krakenAllRarCurvesLarger <- krakenAllRarCurveList %>%
map(function(x){
krakenRarefactionCurve(x)
})
foreach(i=krakenAllRarCurvesLarger) %do%
ggsave(filename=paste('rarefaction',unique(i$data$krakenLevel),'CB','noFacet','.png', sep='', collapse=''),
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/rarefaction',
plot = i,
height=8.50,
width=10.50,
units="in",
device="png")
amrAllAlphaBoxPlots <- amrAlphaRarefactionDF %>%
amrAlphaDiv()
ggsave('~/amr/2-4-8_results/2_4_8_study_RZ/amrResults_Aug2017_75_gene_frac/alphaDiversity/amrAlphaDiversityCB.png',
plot = amrAllAlphaBoxPlots,
width = 10.50,
height = 8.50,
units = "in")
# Alpha Diversity (rarefied) and Species Richness calculations -------------
krakenAlphaRarefaction <- mclapply(krakenResultsMat, function(x){
alpha_rarefaction(x, minlevel=0)
},mc.cores = 10)
amrAlphaRarefaction <- mclapply(amrResultsMat, function(x){
alpha_rarefaction(x, minlevel=0)
}, mc.cores=10)
# Consider change to data frame/tibble
krakenAlphaRarefaction <- lapply(krakenAlphaRarefaction2, function(x) data.table(
ID=names(x$raw_species_abundance),
RawSpeciesAbundance=as.numeric(x$raw_species_abundance),
RarSpeciesAbundance=as.numeric(x$rarefied_species_abundance),
AlphaDiv=as.numeric(x$alphadiv),
Shannon=as.numeric(x$shannon),
Evenness=as.numeric(x$evenness)
))
amrAlphaRarefaction <- lapply(amrAlphaRarefaction, function(x) data.table(
ID=names(x$raw_species_abundance),
RawSpeciesAbundance=as.numeric(x$raw_species_abundance),
RarSpeciesAbundance=as.numeric(x$rarefied_species_abundance),
AlphaDiv=as.numeric(x$alphadiv),
Shannon=as.numeric(x$shannon),
Evenness=as.numeric(x$evenness)
))
amrCategories <- levels(amrResultsTidy$Category)
foreach(i=amrAlphaRarefaction, j=amrCategories) %do%
rep(j,length(i$ID)) -> i$Level
#amrAlphaRarefaction[[1]]$Level <- rep(amrCategories[[1]], length(amrAlphaRarefaction[[1]]$ID))
#amrAlphaRarefaction[[2]]$Level <- rep(amrCategories[[2]], length(amrAlphaRarefaction[[2]]$ID))
#amrAlphaRarefaction[[3]]$Level <- rep(amrCategories[[3]], length(amrAlphaRarefaction[[3]]$ID))
#amrAlphaRarefaction[[4]]$Level <- rep(amrCategories[[4]], length(amrAlphaRarefaction[[4]]$ID))
foreach(i=krakenAlphaRarefaction, j=krakenTaxa) %do%
rep(j,length(i$ID)) -> i$Level
foreach(i=krakenAlphaRarefaction2, j=krakenTaxa) %do%
rep(j,length(i$ID)) -> i$Level
# Seems like unnecessary repetition to convert these to data frames when they
# could have been created as dataframes
amrAlphaRarefactionDF <- lapply(amrAlphaRarefaction, function(x){
x <- as.data.frame(x)
x
})
krakenAlphaRarefactionDF <- lapply(krakenAlphaRarefaction, function(x){
x <- as.data.frame(x)
x
})
krakenAlphaRarefaction2DF <- lapply(krakenAlphaRarefaction2, function(x){
x <- as.data.frame(x)
x
})
amrAlphaRarefactionDF <- do.call("rbind", amrAlphaRarefactionDF)
krakenAlphaRarefactionDF <- do.call("rbind", krakenAlphaRarefactionDF)
krakenAlphaRarefaction2DF <- do.call("rbind", krakenAlphaRarefaction2DF)
amrAlphaRarefactionDF$Depth <- str_replace(amrAlphaRarefactionDF$ID, "_.*", "")
krakenAlphaRarefactionDF$Depth <- str_replace(krakenAlphaRarefactionDF$ID, "_.*", "")
krakenAlphaRarefaction2DF$Depth <- str_replace(krakenAlphaRarefaction2DF$ID, "_.*", "")
# Generate one single dataframe and create column for AMR Level
krakenAlphaRarefactionDF$Depth <- str_replace(krakenAlphaRarefactionDF$Depth, "F", "D1")
krakenAlphaRarefactionDF$Depth <- str_replace(krakenAlphaRarefactionDF$Depth, "H", "D0.5")
krakenAlphaRarefactionDF$Depth <- str_replace(krakenAlphaRarefactionDF$Depth, "QD", "D0.25")
amrAlphaRarefactionDF$Depth <- str_replace(amrAlphaRarefactionDF$Depth, "F", "D1")
amrAlphaRarefactionDF$Depth <- str_replace(amrAlphaRarefactionDF$Depth, "H", "D0.5")
amrAlphaRarefactionDF$Depth <- str_replace(amrAlphaRarefactionDF$Depth, "QD", "D0.25")
krakenAlphaRarefaction2DF$Depth <- str_replace(krakenAlphaRarefaction2DF$Depth, "F", "D1")
krakenAlphaRarefaction2DF$Depth <- str_replace(krakenAlphaRarefaction2DF$Depth, "H", "D0.5")
krakenAlphaRarefaction2DF$Depth <- str_replace(krakenAlphaRarefaction2DF$Depth, "QD", "D0.25")
# Alpha Diversity (rarefied) and Species Richness boxplots -------------------
krakenAlphaRarefactionDF <- krakenAlphaRarefactionDF %>% filter(!Level %in% c("-", "D"))
krakenAlphaRarefaction2DF <- krakenAlphaRarefaction2DF %>% filter(!Level %in% c("-", "D"))
krakenAlphaRarefactionDF$Level <- str_replace(krakenAlphaRarefactionDF$Level, "P", "Phyla")
krakenAlphaRarefactionDF$Level <- str_replace(krakenAlphaRarefactionDF$Level, "C", "Classes")
krakenAlphaRarefactionDF$Level <- str_replace(krakenAlphaRarefactionDF$Level, "O", "Orders")
krakenAlphaRarefactionDF$Level <- str_replace(krakenAlphaRarefactionDF$Level, "F", "Families")
krakenAlphaRarefactionDF$Level <- str_replace(krakenAlphaRarefactionDF$Level, "G", "Genera")
krakenAlphaRarefactionDF$Level <- str_replace(krakenAlphaRarefactionDF$Level, "S", "Species")
krakenAlphaRarefaction2DF$Level <- str_replace(krakenAlphaRarefaction2DF$Level, "P", "Phyla")
krakenAlphaRarefaction2DF$Level <- str_replace(krakenAlphaRarefaction2DF$Level, "C", "Classes")
krakenAlphaRarefaction2DF$Level <- str_replace(krakenAlphaRarefaction2DF$Level, "O", "Orders")
krakenAlphaRarefaction2DF$Level <- str_replace(krakenAlphaRarefaction2DF$Level, "F", "Families")
krakenAlphaRarefaction2DF$Level <- str_replace(krakenAlphaRarefaction2DF$Level, "G", "Genera")
krakenAlphaRarefaction2DF$Level <- str_replace(krakenAlphaRarefaction2DF$Level, "S", "Species")
krakenAlphaRarefactionDF$Level <- factor(krakenAlphaRarefactionDF$Level,
levels = c('Phyla',
'Classes',
'Orders',
'Families',
'Genera',
'Species'))
amrAllSpRawBoxPlots <- amrAlphaRarefactionDF %>%
amrRawSpeciesRich()
ggsave(filename = 'amrSpeciesRichnessCB.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/amrResults_Aug2017_75_gene_frac/alphaDiversity',
plot = amrAllSpRawBoxPlots,
width = 10.50,
height = 8.50,
units = "in")
krakenAllAlphaBoxPlots <- krakenAlphaRarefaction2DF %>%
krakenAlphaDiv()
ggsave(filename = 'krakenAlphaDivCB.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenAllAlphaBoxPlots,
width = 10.50,
height = 8.50,
units = "in")
krakenAllShannonBoxPlots <- krakenAlphaRarefaction2DF %>%
krakenShannon()
ggsave(filename = 'krakenAlphaDivCB.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenAllAlphaBoxPlots,
width = 10.50,
height = 8.50,
units = "in")
krakenRarefiedNewNames <- krakenAlphaRarefaction2DF %>%
mutate(Level=str_replace(Level,"Phyla", "Phylum")) %>%
mutate(Level=str_replace(Level,"Classes", "Class")) %>%
mutate(Level = str_replace(Level, "Orders", "Order")) %>%
mutate(Level=str_replace(Level, "Families", "Family")) %>%
mutate(Level=str_replace(Level, "Genera", "Genus")) %>%
mutate(Level=str_replace(Level, "Species", "Species"))
krakenRarefiedNewNames$Level <- factor(krakenRarefiedNewNames$Level,
levels = c('Phylum',
'Class',
'Order',
'Family',
'Genus',
'Species'))
krakenAllSpRawBoxPlots <- krakenRarefiedNewNames %>%
krakenRawSpeciesRich()
ggsave(filename = 'krakenObservedRichness.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenAllSpRawBoxPlots,
width = 10.50,
height = 8.50,
units="in")
krakenAllSpRawBoxPlots <- krakenAlphaRarefaction2DF %>%
krakenRawSpeciesRich()
ggsave(filename = 'krakenSpRichnessCB.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenAllSpRawBoxPlots,
width = 10.50,
height = 8.50,
units="in")
# Kraken boxplots with POGS only
krakenAlphaRarPOGS <- krakenAlphaRarefaction2DF %>%
filter(Level %in% c("Phyla", "Orders", "Genera", "Species"))
krakenAlphaRarPOGS <- krakenAlphaRarPOGS %>%
mutate(taxLevel = Level) %>%
mutate(taxLevel = str_replace(taxLevel, "Phyla", "Phylum")) %>%
mutate(taxLevel =str_replace(taxLevel,"Orders", "Order")) %>%
mutate(taxLevel = str_replace(taxLevel,"Genera", "Genus")) %>%
mutate(Level = taxLevel)
krakenAlphaRarPOGS$Level <- factor(krakenAlphaRarPOGS$Level,
levels = c('Phylum', 'Order', 'Genus', 'Species'))
krakenPOGSspRawBoxPlots <- krakenAlphaRarPOGS %>%
krakenRawSpeciesRich()
ggsave(filename = 'krakenObservedRichnessPOGS_CB.png',
path = '~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017/alphaDiversity',
plot = krakenPOGSspRawBoxPlots,
width = 10.50,
height = 8.50,
units="in")
# Correlation plots -------------------------------------------------------
# Should make into a function for the package
amrReadstoHitRatio$Sample_type <- str_replace(amrReadstoHitRatio$Sample_type, "F", "D1")
amrReadstoHitRatio$Sample_type <- str_replace(amrReadstoHitRatio$Sample_type, "H", "D0.5")
amrReadstoHitRatio$Sample_type <- str_replace(amrReadstoHitRatio$Sample_type, "Q", "D0.25")
amrReadsvsHits <- cor(x = amrReadstoHitRatio$`Number of reads`, amrReadstoHitRatio$`AMR hits`, method = "spearman")
amrReadsvsHitsCorTest <- cor.test(x = amrReadstoHitRatio$`Number of reads`, amrReadstoHitRatio$`AMR hits`, method = "spearman")
amrReadsvsHitsCor <- ggplot(amrReadstoHitRatio, aes(`Number of reads`, `AMR hits`)) +
geom_point(aes(fill=Sample_type),
alpha=0.6,
size=10,
pch=21,
color="grey")
# geom_smooth(aes(group=1, weight=0.2),
# method="lm",
# se=FALSE,
# colour="grey",
# alpha=0.5)
amrReadsvsHitsCor +
ylab("Number of AMR Hits\n") +
xlab("\nNumber of reads") +
theme(axis.text.y=element_text(size=35),
axis.title.y=element_text(size=44),
axis.text.x=element_text(size=35),
axis.title.x=element_text(size=44),
legend.title=element_text(size=36),
legend.text=element_text(size=36, vjust=0.5),
legend.key = element_rect(size = 2),
legend.key.size = unit(2, "lines"),
legend.spacing = unit(0.2,"lines"),
panel.background = element_rect(fill = "grey90", colour = "grey80")) +
scale_fill_manual(values=rev(cbPalette),
name="Sequencing Depth\n")
ggsave('~/amr/2-4-8_results/2_4_8_study_RZ/amrResults_Aug2017_75_gene_frac/amrReadsvsHitsCorUpdated.png',
width=14,
height=8.50,
units="in")
# Generating kraken correlation plot
krakenReadsvsHitsCorTest <- cor.test(x = amrReadstoHitRatio$`Number of reads`, amrReadstoHitRatio$Phylum_hits, method = "spearman")
krakenReadsvsHitsCor <- ggplot(amrReadstoHitRatio, aes(`Number of reads`, Phylum_hits)) +
geom_point(aes(fill=Sample_type), alpha=0.6, size=10, pch=21, color="grey")
# geom_smooth(aes(group=1, weight=0.2), method="lm", se=FALSE, colour="grey", alpha=0.5)
krakenReadsvsHitsCor +
ylab("Number of Kraken Hits\n") +
xlab("\nNumber of reads") +
theme(axis.text.y=element_text(size=35),
axis.title.y=element_text(size=44),
axis.text.x=element_text(size=35),
axis.title.x=element_text(size=44),
legend.title=element_text(size=36),
legend.text=element_text(size=36, vjust=0.5),
legend.key = element_rect(size = 2),
legend.key.size = unit(2, "lines"),
legend.spacing = unit(0.2,"lines"),
panel.background = element_rect(fill = "grey90", colour = "grey80")) +
scale_fill_manual(values=rev(cbPalette),
name="Sequencing Depth\n")
ggsave(filename='krakenReadsvsHitsCorUpdated.png',
path='~/amr/2-4-8_results/2_4_8_study_RZ/krakenResults_Aug2017',
width=14,
height=8.50,
units="in")
# Kruskal-Wallis tests ----------------------------------------------------
# Resistome
amrAlphaRarefactionLevels <- amrAlphaRarefactionDF %>%
split(.$Level)