-
Notifications
You must be signed in to change notification settings - Fork 0
/
flupipe.Rmd
executable file
·1219 lines (1039 loc) · 52.3 KB
/
flupipe.Rmd
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: "Flupipe Report"
output:
html_document:
toc: true
toc_float: true
toc_depth: 6
mathjax: null
date: "`r format(Sys.time(), '%d %B, %Y')`"
params:
proj_folder: "none"
list_folder: "none"
min_cov: "none"
reference: false
rki_sample_name: true
run_name: "none"
version: "none"
---
<style>
.superwideimage{
overflow-x:scroll;
white-space: nowrap;
}
.superwideimage img{
max-width: none;
}
</style>
<style>
.superhighimage{
overflow:auto;
height: 500px;
width: 100%;
margin-top: 10px;
margin-bottom:
}
</style>
<style type="text/css">
.main-container {
max-width: 100% !important;
margin: auto;
}
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, error = FALSE, time_it = TRUE)
library("data.table")
library("formattable")
library("ggplot2")
library("kableExtra")
library("plyr")
library("rjson")
library("reshape2")
library("ShortRead")
library("dplyr")
min.coverage <- as.numeric(params$min_cov)
reference <- params$reference
stepsize = 20 # number of samples per plot
n_content_threshold = 5 # threshold of N content % that should be marked in the table
```
```{r get_cmd_line_parameters}
# find all folders of intermediate results
l.dirlist <- list.dirs(file.path(params$proj_folder, "intermediate_data"), recursive = F)
# get the precise folder name of each interesting subfolder needed for tables
trimmed_folder <- l.dirlist[grepl(pattern = "trimmed", x = l.dirlist)]
mapping_stats_folder <- l.dirlist[grepl(pattern = "mapping_stats", x = l.dirlist)]
mapping_folder <- l.dirlist[grepl(pattern = "04_mapp*", x = l.dirlist)]
kraken_folder <- l.dirlist[grepl(pattern = "classified", x = l.dirlist)]
# get folder name for fasta files
fasta.dir <- file.path(params$proj_folder, "consensuses_iupac")
if (!dir.exists(params$proj_folder)) {
stop("input folder does not exist")
}
if (!dir.exists(params$list_folder)) {
stop("output folder does not exist")
}
if (!dir.exists(trimmed_folder)) {
stop("trimmed folder does not exist")
}
if (!dir.exists(mapping_stats_folder)) {
stop("mapping stats folder does not exist")
}
if (!dir.exists(mapping_folder)) {
stop("mapping folder does not exist")
}
if (!dir.exists(fasta.dir)) {
stop("consensus folder with fasta files does not exist")
}
kraken_run <- FALSE
if (!dir.exists(kraken_folder) || length(kraken_folder) == 0) {
kraken_run <- FALSE
} else {
kraken_run <- TRUE
}
```
```{r def_functions}
# input of file listing. requires file names like /path/to/nCoV1.bamstats.txt
f.get_filenames <- function(l.input){
sapply(l.input, function(x){
filename <- unlist(strsplit(x, '/'))[length(unlist(strsplit(x, '/')))]
samplename <- unlist(strsplit(filename, '\\.'))[1]
return(samplename)
})
#returns named character vector of sample names, e.g. nCoV1
}
# modified color_bar to fix direction from "rtl" to "ltr"
f.color_bar <- function (color = "lightgray", fun = "proportion",
...)
{
fun <- match.fun(fun)
formattable::formatter("span", style = function(x) style(display = "inline-block",
direction = "ltr", `border-radius` = "4px",
`padding-right` = "2px", `background-color` = csscolor(color),
width = percent(fun(as.numeric(x), ...))))
}
# Function to collapse the values within a grouped dataframe
collapse_rows_df <- function(df, variable){
group_var <- enquo(variable)
df %>%
group_by(!! group_var) %>%
mutate(groupRow = 1:n()) %>%
ungroup() %>%
mutate(!!quo_name(group_var) := ifelse(groupRow == 1,
as.character(!! group_var), "")) %>%
select(-c(groupRow))
}
```
```{r read_data}
# this chunk reads mapping stats and trimming stats
l.infiles.trimming <- list.files(path = trimmed_folder,
pattern = "*.fastp.json$",
full.names = T,
recursive = T)
l.infiles.bamstats <- list.files(path = mapping_stats_folder,
pattern = "*.bamstats.pipe.txt$",
full.names = T,
recursive = T)
l.infiles.coverage <- list.files(path = mapping_stats_folder,
pattern = "*.coverage.tsv$",
full.names = T,
recursive = T)
l.infiles.fragsize <- list.files(path = mapping_stats_folder,
pattern = "*.fragsize.tsv$",
full.names = T,
recursive = T)
l.infiles.bamstats.coverage <- list.files(path = mapping_stats_folder,
pattern = "*.bamstats_coverage.txt$",
full.names = T,
recursive = T)
l.infiles.read.duplicates <- list.files(path = mapping_folder,
pattern = "*.dedup.txt$",
full.names = T,
recursive = T)
l.infiles.read.ranking.refs <- list.files(path = mapping_folder,
pattern = glob2rx("Ranking_top5_Refs_*.txt$"),
full.names = T,
recursive = T)
l.infiles.fasta.files <- list.files(path = fasta.dir,
pattern = glob2rx("*.fasta$"),
full.names = T,
recursive = T)
l.infiles.merged.read.length <- list.files(path = trimmed_folder,
pattern = "merged_length.tsv$",
full.names = T,
recursive = T)
# initialise empty list
l.infiles.kraken <- list()
if (kraken_run) {
l.infiles.kraken <- list.files(path = kraken_folder,
pattern = "*.report.txt$",
full.names = T,
recursive = T)
}
# put names to file names
names(l.infiles.trimming) <- f.get_filenames(l.infiles.trimming)
names(l.infiles.bamstats) <- f.get_filenames(l.infiles.bamstats)
names(l.infiles.coverage) <- f.get_filenames(l.infiles.coverage)
names(l.infiles.fragsize) <- f.get_filenames(l.infiles.fragsize)
names(l.infiles.kraken) <- f.get_filenames(l.infiles.kraken)
names(l.infiles.bamstats.coverage) <- f.get_filenames(l.infiles.bamstats.coverage)
names(l.infiles.read.duplicates) <- f.get_filenames(l.infiles.read.duplicates)
names(l.infiles.read.ranking.refs) <- f.get_filenames(l.infiles.read.ranking.refs)
names(l.infiles.fasta.files) <- f.get_filenames(l.infiles.fasta.files)
names(l.infiles.merged.read.length) <- f.get_filenames(l.infiles.merged.read.length)
if (length(l.infiles.merged.read.length) == 0) {
stop("no merged read length file identified")
}
if (length(l.infiles.trimming) == 0) {
stop("no trimming stat files identified")
}
if (length(l.infiles.bamstats) == 0) {
stop("no bam stat files identified")
}
if (length(l.infiles.coverage) == 0) {
stop("no coverage files identified")
}
if (length(l.infiles.fragsize) == 0) {
stop("no fragment size files identified")
}
if (length(l.infiles.bamstats.coverage) == 0) {
stop("no bamstats coverage size files identified")
}
if (length(l.infiles.read.duplicates) == 0) {
stop("no read duplicates size files identified")
}
if (length(l.infiles.read.ranking.refs) == 0) {
stop("no Ranking_top5_Refs files identified")
}
if (length(l.infiles.fasta.files) == 0) {
stop("no iupac consensus fasta files identified")
}
if (length(l.infiles.kraken) == 0) {
kraken_run <- FALSE
}
```
## Sequencing run
```{r conditional_sentence, results='asis'}
if (params$run_name != 'none') {
cat(paste0("Sequencing was performed in run: ", params$run_name, "\n"))
} else {
cat(paste0("No ID for a sequencing run was submitted. \n"))
}
```
```{r read_coverage_preanalyses}
# read file content
# dt.coverage is used again later for plotting
dt.coverage <- as.data.table(ldply(l.infiles.coverage, fread, sep='\t'))
colnames(dt.coverage) <- c("sample","chromosome", "position", "depth")
# rename chromosome column values
dt.coverage$chromosome <- sapply(dt.coverage$chromosome, function(x){
segment <- tail(unlist(strsplit(x,"|",fixed=TRUE)), n=1)
segment <- toString(segment)
return(segment)
})
dt.output <- dt.coverage[, sum(depth > 10), by = sample]
setnames(dt.output, "V1", "covered.bases")
dt.output$genome.length <- dt.coverage[,length(depth), by = sample]$V1
dt.output$genome.coverage <- dt.output$covered.bases / dt.output$genome.length
### taking directly the per chromosome results from bamstats coverage
### this data frame is used again later for the whole table including all samples
dt.bamstats.coverage <- as.data.table(ldply(l.infiles.bamstats.coverage, fread, sep='\t', select=c(1,4,6,7)))
dt.bamstats.coverage[,("coverage") := round(.SD,2), .SDcols="coverage"]
dt.bamstats.coverage[,("meandepth") := round(.SD,0), .SDcols="meandepth"]
colnames(dt.bamstats.coverage) <- c("sample","chromosome","reads mapped [%]", "coverage [%]", "mean depth [bp]")
# rename chromosome column values
dt.bamstats.coverage$chromosome <- sapply(dt.bamstats.coverage$chromosome, function(x){
segment <- tail(unlist(strsplit(x,"|",fixed=TRUE)), n=1)
segment <- toString(segment)
return(segment)
})
dt.bamstats.coverage <- reshape(dt.bamstats.coverage, idvar = "sample", timevar = "chromosome", direction = "wide")
# adding placeholder column(s) for missing segment(s)
ls.segment <- list("*HA","*NA","*MP","*NP","*NS","*PA","*PB1","*PB2")
substrRight <- function(x, n){substr(x, nchar(x)-n+1, nchar(x))}
if (ncol(dt.bamstats.coverage) != 25 ) {
for (s in ls.segment){
if (Reduce("|",grepl(s, names(dt.bamstats.coverage)))) {}
else {
dt.bamstats.coverage[,paste("reads mapped [%].", substrRight(s, 2))] <- NA
dt.bamstats.coverage[,paste("coverage [%].", substrRight(s, 2))] <- NA
dt.bamstats.coverage[,paste("mean depth [bp].", substrRight(s, 2))] <- NA
}
}
}
# reorder dataframe columns
dt.bamstats.coverage <- dt.bamstats.coverage[, c( "sample","reads mapped [%].HA","coverage [%].HA","mean depth [bp].HA",
"reads mapped [%].NA","coverage [%].NA","mean depth [bp].NA",
"reads mapped [%].MP","coverage [%].MP","mean depth [bp].MP",
"reads mapped [%].NP","coverage [%].NP","mean depth [bp].NP",
"reads mapped [%].NS","coverage [%].NS","mean depth [bp].NS",
"reads mapped [%].PA","coverage [%].PA","mean depth [bp].PA",
"reads mapped [%].PB1","coverage [%].PB1","mean depth [bp].PB1",
"reads mapped [%].PB2","coverage [%].PB2","mean depth [bp].PB2" )]
###################### Joining the 2 datasets ##################################
colnames(dt.output) <- c("sample", "ref.coverage [bp]", "genome.length", "ref.coverage [fraction]")
dt.output <- merge(dt.output, dt.bamstats.coverage, by = "sample")
```
```{r conditional_warning, results='asis'}
dt.output <- dt.output[grepl("NK|Empty", dt.output$sample, ignore.case = TRUE) & dt.output$`ref.coverage [bp]` >= 0.2, ]
if (nrow(dt.output) > 0) {
cat("## WARNING \n")
cat("Samples identified automatically as negative controls show unusual large coverage of the reference genome (more than 20%). Please check the following table, if this is expected for the samples. \n")
}
```
```{r conditional_table}
if (nrow(dt.output) > 0) {
dt.output$`ref.coverage [fraction]` <- round(dt.output$`ref.coverage [fraction]`, 2)
# add a row with all 0 and 1 to make colour scaling reproducible
df.tmp <- data.frame("sample" = c(0,1),
"genome.length" = c(0,1),
"ref.coverage [bp]" = c(0,1),
"ref.coverage [fraction]" = c(0,1),
"reads mapped [%].HA" = c(0,1),
"coverage [%].HA" = c(0,1),
"mean depth [bp].HA" = c(0,1),
"reads mapped [%].NA" = c(0,1),
"coverage [%].NA" = c(0,1),
"mean depth [bp].NA" = c(0,1),
"reads mapped [%].MP" = c(0,1),
"coverage [%].MP" = c(0,1),
"mean depth [bp].MP" = c(0,1),
"reads mapped [%].NP" = c(0,1),
"coverage [%].NP" = c(0,1),
"mean depth [bp].NP" = c(0,1),
"reads mapped [%].NS" = c(0,1),
"coverage [%].NS" = c(0,1),
"mean depth [bp].NS" = c(0,1),
"reads mapped [%].PA" = c(0,1),
"coverage [%].PA" = c(0,1),
"mean depth [bp].PA" = c(0,1),
"reads mapped [%].PB1" = c(0,1),
"coverage [%].PB1" = c(0,1),
"mean depth [bp].PB1" = c(0,1),
"reads mapped [%].PB2" = c(0,1),
"coverage [%].PB2" = c(0,1),
"mean depth [bp].PB2" = c(0,1)
)
dt.output <- rbind(dt.output, df.tmp, use.names=FALSE)
rm(df.tmp)
# highlight important rows
dt.output$sample <- cell_spec(dt.output$sample, color = ifelse(dt.output$`ref.coverage [fraction]` > 0.2, "red", "black"))
dt.output$`ref.coverage [fraction]` <- color_tile("white", "orange")(dt.output$`ref.coverage [fraction]`)
#remove added lines
dt.output <- head(dt.output, n = -2)
dt.output <- dt.output[,-c("genome.length")]
kbl(dt.output,
digits = 2,
caption = "Reference genome coverage in base pairs and as fraction of the total length. Bases with more than 10x sequencing depth are counted as covered. Negative control's names are highlighted in red if more than 20% of reference genome is covered, increasing coverage fraction is coloured orange (scaled from 0 to 1).",
escape = F) %>%
kable_styling(bootstrap_options = c("striped", "hover"), fixed_thead = T) %>%
scroll_box(height = "400px")
}
```
```{r conditional_cleanup}
rm(dt.output)
```
## Trimming statistics
Quality trimming and adapter clipping was performed using fastp (v 0.20.0).
### Read counts
Raw reads were subjected to adapter clipping.
The following table summarizes the read count per sample before and after trimming. Additionally, the percentage of remaining reads after trimming is listed.
```{r read_trimming}
l.trimming.data.json <- lapply(l.infiles.trimming, function(x){
fromJSON(file = x)
})
df.trimming.data <- ldply(l.trimming.data.json, function(e){
df.before <- as.data.frame(do.call(rbind, e$summary$before_filtering))
colnames(df.before) <- c("before.trimming")
df.after <- as.data.frame(do.call(rbind, e$summary$after_filtering))
colnames(df.after) <- c("after.trimming")
df.output <- data.frame(feature = rownames(df.before),
before = df.before$before.trimming,
after = df.after$after.trimming)
return(df.output)
})
# rename 1st column
tmp <- colnames(df.trimming.data)
tmp[1] <- c("sample")
colnames(df.trimming.data) <- tmp
df.filter.data <- ldply(l.trimming.data.json, function(e){
df.output <- data.frame(passed_filter = e$filtering_result$passed_filter_reads,
low_qual = e$filtering_result$low_quality_reads,
high_N = e$filtering_result$too_many_N_reads,
low_complex = e$filtering_result$low_complexity_reads,
short = e$filtering_result$too_short_reads
)
return(df.output)
})
# rename 1st column
tmp <- colnames(df.filter.data)
tmp[1] <- c("sample")
colnames(df.filter.data) <- tmp
```
```{r table_trimming}
df.summary <- data.frame(sample = unique(df.trimming.data$sample),
reads.before.clip = df.trimming.data$before[grepl("total_reads", df.trimming.data$feature)],
reads.after.clip = df.trimming.data$after[grepl("total_reads", df.trimming.data$feature)],
percentage.after.clip = df.trimming.data$after[grepl("total_reads", df.trimming.data$feature)]*100/df.trimming.data$before[grepl("total_reads", df.trimming.data$feature)]
)
df.table <- df.summary
# add coloured bar charts to table
df.table$reads.before.clip <- f.color_bar("lightgreen")(df.table$reads.before.clip)
df.table$reads.after.clip <- f.color_bar("lightgreen")(df.table$reads.after.clip)
df.table$percentage.after.clip <- Map(paste,format(round(df.table$percentage.after.clip,2),nsmall=2),"%")
kbl(x = df.table,
col.names = c("sample", "reads before trim", "reads after trim", "% of reads after trimming"),
digits = 2,
escape = F) %>%
kable_styling(bootstrap_options = c("striped", "hover"), fixed_thead = T, full_width = T) %>%
scroll_box(height = "400px")
# save table as csv for later use
write.csv( x=df.summary,
row.names = FALSE,
file = file.path(params$list_folder, "read_stats.csv")
)
```
<div class="superhighimage">
```{r count_trimming_samples}
sample.count <- length(unique(df.table$sample))
plot.width <- 20
```
For a better overview, the reads counts are plotted in a bar plot per sample. The number of raw reads is shown in light blue and dark blue visualizes trimmed reads.
```{r plot_trimming}
if (sample.count > stepsize) {
# for more than 20 samples split plot into multiple plots with each only 20 samples
for (s in 0:(ceiling(sample.count/stepsize)-1) ) {
x = s*stepsize+1
y = s*stepsize+stepsize
df.summary.subset <- na.omit(df.summary[x:y,])
df.plot <- melt(df.summary.subset, id.vars = "sample",
measure.vars = c("reads.before.clip", "reads.after.clip"))
g <- ggplot(data = df.plot, aes(sample, value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge", width = 0.6) +
labs(title = "read counts before & after trimming",
x = "sample", y = "count", fill = "trimming") +
scale_fill_manual(values = c("#56B4E9", "#0072B2"), labels = c("raw", "trimmed")) +
scale_y_continuous(labels = function(x) format(x, scientific = F)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1),
legend.position = "top") +
coord_flip()
print(g)
}
} else {
df.plot <- melt(df.summary, id.vars = "sample",
measure.vars = c("reads.before.clip", "reads.after.clip"))
ggplot(data = df.plot, aes(sample, value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge", width = 0.6) +
labs(title = "read counts before & after trimming",
x = "sample", y = "count", fill = "trimming") +
scale_fill_manual(values = c("#56B4E9", "#0072B2"), labels = c("raw", "trimmed")) +
scale_y_continuous(labels = function(x) format(x, scientific = F)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1),
legend.position = "top") +
coord_flip()
}
```
</div>
### Read Length Distribution
For the forward (R1) and reverse (R2) read the sequence length distribution is shown after trimming.
``` {r read_len_table}
header <- read.table(l.infiles.merged.read.length, nrow = 1, header = TRUE)
column_name <- substr(colnames(header),2, nchar(colnames(header)))
setnames(header, column_name)
####### rearranging columns so that R1 and R2 of the same sample are next to each other #######
rearrenged_colnames <- c()
for (h in 1:(length(colnames(header))/2)) {
a = length(colnames(header))/2+h
rearrenged_colnames <- append(rearrenged_colnames, colnames(header)[h])
rearrenged_colnames <- append(rearrenged_colnames, colnames(header)[a])
}
setcolorder(header, rearrenged_colnames)
reads <- as.data.table(ldply(l.infiles.merged.read.length, fread, sep='\t', skip=1, header=FALSE))
reads <- reads[,-1]
rearrenged_colnames_reads <- c()
for (h in 1:(length(colnames(reads))/2)) {
a = length(colnames(reads))/2+h
rearrenged_colnames_reads <- append(rearrenged_colnames_reads, colnames(reads)[h])
rearrenged_colnames_reads <- append(rearrenged_colnames_reads, colnames(reads)[a])
}
setcolorder(reads, rearrenged_colnames_reads)
setnames(reads, colnames(header))
```
``` {r reduce_data_read_len}
# reducing the dataframe by sampling every 100th read/row
reads = reads[seq(1, nrow(reads), 50), ]
```
<div class=superhighimage>
``` {r reshape_and_plot_read_len}
ss = stepsize*2 # since we have 2 columns per sample (R1 and R2)
min_val <- as.numeric(min(na.omit(reads))-50)
if (min_val<0){min_val <- as.numeric(0)}
max_val <- as.numeric(max(na.omit(reads))+50)
if (length(colnames(reads)) > ss) {
# for more than 20 samples split plot into multiple plots with each only 20 samples
for (s in 0:(ceiling(length(colnames(reads))/ss)-1) ) {
x = s*ss+1
y = s*ss+ss
if (y > length(colnames(reads))) {
y = length(colnames(reads))
}
####### Reshape dataframe for boxplot ########
reads.subset <- reads[,x:y]
reads.subset <- stack(as.data.frame(reads.subset))
reads.subset$ind <- as.character(reads.subset$ind)
reads.subset$sample <- substr(reads.subset$ind, 1, nchar(reads.subset$ind)-3)
reads.subset$read <- substr(reads.subset$ind, nchar(reads.subset$ind)-1, nchar(reads.subset$ind))
reads.subset <- reads.subset[,-2] # remove ind column
# print(reads.subset)
####### Plot each 20 samples #######
p <- ggplot(reads.subset) +
geom_boxplot(aes(x = values, y = sample, fill = read),
outlier.shape = NA, na.rm=TRUE) +
labs(title = "Sequence Length Distribution", x = "Sequence Legth (bp)",
y = "Sample") +
theme(axis.text.x = element_text(angle = 90, hjust = 1),
legend.position = "top") +
scale_fill_manual(values=c("lightgreen", "green4")) +
xlim(min_val, max_val)
print(p)
rm(reads.subset)
}
} else {
read_df <- stack(as.data.frame(reads))
read_df$ind <- as.character(read_df$ind)
read_df$sample <- substr(read_df$ind, 1, nchar(read_df$ind)-3)
read_df$read <- substr(read_df$ind, nchar(read_df$ind)-1, nchar(read_df$ind))
ggplot(read_df) +
geom_boxplot(aes(x = values, y = sample, fill = read), outlier.shape = NA, na.rm=TRUE) +
labs(title = "Sequence Length Distribution", x = "Sequence Legth [bp]", y = "Sample") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position = "top")+
scale_fill_manual(values=c("lightgreen", "green4")) +
xlim(min_val, max_val)
}
```
</div>
### Read Quality Distribution
For the forward (R1) and reverse (R2) read the sequence quality distribution is shown after trimming.
```{r read_trimming_for_phred}
df.trimming.phred.data <- ldply(l.trimming.data.json, function(e){
df.output <- data.frame(phred_score_R1 = c(e$"read1_after_filtering"$"quality_curves"$"mean"),
phred_score_R2 = c(e$"read2_after_filtering"$"quality_curves"$"mean"))
return(df.output)
})
colnames(df.trimming.phred.data) <- c("Sample", "R1", "R2")
```
<div class=superhighimage>
``` {r plot_phred_score}
samples <- unique(df.trimming.phred.data$Sample)
if (length(samples)>stepsize) {
for (s in 0:(ceiling(length(samples)/stepsize)-1)){
x= s*stepsize
y = ((s+1)*stepsize)-1
if (y>length(samples)){
y = length(samples)
}
df.subset <- subset(df.trimming.phred.data, Sample %in% samples[x:y])
df.subset <- melt(df.subset, id.vars = "Sample", measure.vars = c("R1", "R2"))
b <- ggplot(df.subset) +
geom_boxplot(aes(x = value, y = Sample, fill = variable), outlier.shape = NA, na.rm=TRUE, width = 0.4) +
labs(title = "Per Sequence Quality Scores", x = "Mean Sequence Quality (Phred Score)", y = "Sample", fill = "read") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position = "top") +
scale_fill_manual(values=c("lightgreen", "green4"))
print(b)
rm(df.subset)
}
} else {
df.trimming.phred.data <- melt(df.trimming.phred.data, id.vars = "Sample", measure.vars = c("R1", "R2"))
ggplot(df.trimming.phred.data) +
geom_boxplot(aes(x = value, y = Sample, fill = variable), outlier.shape = NA, na.rm=TRUE, width = 0.4) +
labs(title = "Per Sequence Quality Scores", x = "Mean Sequence Quality (Phred Score)", y = "Sample", fill = "read") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position = "top") +
scale_fill_manual(values=c("lightgreen", "green4"))
}
```
</div>
```{r trimming_cleanup}
rm(df.plot)
rm(df.summary)
rm(df.table)
rm(df.trimming.data)
rm(df.filter.data)
rm(reads)
rm(read_df)
rm(df.trimming.phred.data)
```
### Taxonomic Read Classification
The taxonomic classification of reads can not only serve to identify contamination, but also enable the filtering of reads assigned to certain taxa. In this step influena A, influenza B and Orthomyxoviridae reads were filtered and used for the next analysis step. Remaining reads were excluded from further analysis.
The assigned taxa are listed by sample n the following table.
```{r read_kraken}
# Kraken2 output column labels.
# Percentage of fragments covered by the clade rooted at this taxon
# Number of fragments covered by the clade rooted at this taxon
# Number of fragments assigned directly to this taxon
# A rank code, indicating (U)nclassified, (R)oot, (D)omain, (K)ingdom, (P)hylum, (C)lass, (O)rder, (F)amily, (G)enus, or (S)pecies. Taxa that are not at any of these 10 ranks have a rank code that is formed by using the rank code of the closest ancestor rank with a number indicating the distance from that rank. E.g., "G2" is a rank code indicating a taxon is between genus and species and the grandparent taxon is at the genus rank.
# NCBI taxonomic ID number
# Indented scientific name
df.kraken_output <- data.frame()
if (kraken_run) {
dt.kraken_data <- ldply(l.infiles.kraken, fread)
colnames(dt.kraken_data) <- c("Sample", "read_ratio", "read_count", "read_count_specific", "rank", "ncbi_taxid", "sciname")
# select unclassified and tax id's for Orthomyxoviridae (11308), Influenza A (11320) and B (11520), and Human (9606)
df.kraken_output <- dt.kraken_data[dt.kraken_data$ncbi_taxid %in% c(0,"11308","11320","11520","9606"), c("Sample", "read_ratio", "read_count", "ncbi_taxid", "sciname")]
# make tables wide for absolute and relative read counts
dt.kraken.count <- data.table::dcast(as.data.table(df.kraken_output), Sample ~ sciname, value.var = c("read_count"))
dt.kraken.count[is.na(dt.kraken.count)] <- 0
df.kraken_output <- data.table::dcast(as.data.table(df.kraken_output), Sample ~ sciname, value.var = c("read_ratio"))
df.kraken_output[is.na(df.kraken_output)] <- 0
# Add placeholder for missing columns
species <- c("Sample","Homo sapiens", "Influenza A virus", "Influenza B virus", "Orthomyxoviridae", "unclassified")
#df.kraken_output
for (sp in species) {
if (Reduce("|",grepl(sp, colnames(df.kraken_output)))) {
# do nothing if column exist
}
else {
df.kraken_output <- cbind(df.kraken_output, new_col = 0)
colnames(df.kraken_output)[which(names(df.kraken_output) == "new_col")] <- sp
}
}
#dt.kraken.count
for (sp in species) {
if (Reduce("|",grepl(sp, colnames(dt.kraken.count)))) {
# do nothing if column exist
}
else {
dt.kraken.count <- cbind(dt.kraken.count, new_col = 0)
colnames(dt.kraken.count)[which(names(dt.kraken.count) == "new_col")] <- sp
}
}
colnames(df.kraken_output) <- paste0(colnames(df.kraken_output), c("", " [%]", " [%]", " [%]", " [%]", " [%]" ))
df.kraken_output$`filter passed` <- rowSums(dt.kraken.count[,c("Homo sapiens", "Influenza A virus", "Influenza B virus")]) *2
#print(colnames(df.kraken_output))
df.kraken_output <- df.kraken_output[, c("Sample", "filter passed", "Homo sapiens [%]", "Influenza A virus [%]", "Influenza B virus [%]", "Orthomyxoviridae [%]", "unclassified [%]")]
}
```
```{r table_kraken, fig.cap="Read counts after species binning using Kraken."}
if (kraken_run) {
# save table as csv for later use
write.csv( x=df.kraken_output,
row.names = FALSE,
file = file.path(params$list_folder, "species_filtering.csv")
)
kbl(df.kraken_output) %>%
kable_styling(bootstrap_options = c("striped", "hover"), fixed_thead = T) %>%
scroll_box(height = "400px")
}
```
```{r reshape_kraken_barchart}
if (kraken_run) {
# reshape dataframe for plotting
# add column for diff of ortho and infA + infB (for barplot)
df.kraken_output$diff_orthomyxoviridae <- df.kraken_output$`Orthomyxoviridae [%]`-(df.kraken_output$`Influenza A virus [%]` + df.kraken_output$`Influenza B virus [%]`)
df.kraken_output.reshaped <- reshape(df.kraken_output,
varying=names(df.kraken_output)[3:8],
direction="long", idvar=c("Sample"),
v.names="ratio", timevar="tax")
df.kraken_output.reshaped$tax <- factor(df.kraken_output.reshaped$tax,
levels = c(1, 2, 3, 4, 5, 6),
labels = names(df.kraken_output)[3:8])
df.kraken_output.reshaped$Sample <- factor(df.kraken_output.reshaped$Sample)
df.kraken_output.reshaped$tax <- factor(df.kraken_output.reshaped$tax)
}
```
<div class=superhighimage>
```{r kraken_plot_barchart, fig.align='center', fig.cap="Taxonimical Classification of the Samples."}
if (kraken_run) {
df.kraken.barplot <- df.kraken_output.reshaped[df.kraken_output.reshaped$tax %in% c("Homo sapiens [%]", "Influenza A virus [%]", "Influenza B virus [%]", "unclassified [%]", "diff_orthomyxoviridae"), ]
samples <- unique(df.kraken.barplot$Sample)
if (length(samples)>stepsize) {
for (s in 0:(ceiling(length(samples)/stepsize)-1)){
x = s*stepsize
y = ((s+1)*stepsize)-1
if (y>length(samples)){y = length(samples)}
df.subset <- subset(df.kraken.barplot, Sample %in% samples[x:y])
g <- ggplot(data=df.subset, aes(fill=tax, y=Sample, x=ratio)) +
geom_bar(position="stack", stat="identity", width = 0.6) +
labs(title = "Taxanomic Classification", fill = "") +
theme(legend.position = 'top', legend.text = element_text(size = 7),
legend.title = element_text(size=8)) +
guides(fill = guide_legend(label.position = "bottom",
title.position = "left", title.vjust = 1)) +
scale_fill_brewer(palette="Set1", labels = c("Homo Sapiens", "Influenza A", "Influenza B", "unclassified", "Orthomyxoviridae"))
print(g)
}
} else {
ggplot(data=df.kraken.barplot, aes(fill=tax, y=Sample, x=ratio)) +
geom_bar(position="stack", stat="identity", width = 0.6) +
labs(title = "Taxanomic Classification", fill = "") +
theme(legend.position = 'top', legend.text = element_text(size = 7),
legend.title = element_text(size=8)) +
guides(fill = guide_legend(label.position = "bottom",
title.position = "left", title.vjust = 1)) +
scale_fill_brewer(palette="Set1", labels = c("Homo Sapiens", "Influenza A", "Influenza B", "unclassified", "Orthomyxoviridae"))
}
}
```
</div>
```{r kraken_cleanup}
if (kraken_run) {
rm(dt.kraken.count)
rm(df.kraken_output)
rm(dt.kraken_data)
rm(df.kraken_output.reshaped)
rm(df.kraken.barplot)
}
```
## Mapping statisics
Reads were mapped to the reference genome using BWA. For each sample the number of mapped read as well as the overall mapping rate and the rate of duplicated reads are listed in the following table. Additionally, the genome coverage, the mean read depth and the rate of mapped reads are listed for each genome fragment.
```{r read_mappingstats}
df.bamstat.data <- ldply(l.infiles.bamstats, fread, sep = '|')
colnames(df.bamstat.data) <- c("sample", "count", "unknown", "description")
```
```{r read_mappingstats_bamstats_coverage}
# # read file content
# dt.bamstats.coverage <- as.data.table(ldply(l.infiles.bamstats.coverage, fread, sep='\t', select=c(1,4,6,7)))
# dt.bamstats.coverage[,("coverage") := round(.SD,2), .SDcols="coverage"]
# dt.bamstats.coverage[,("meandepth") := round(.SD,0), .SDcols="meandepth"]
# colnames(dt.bamstats.coverage) <- c("sample","chromosome","reads mapped [%]", "coverage [%]", "mean depth [bp]")
#
# cc <- unlist(strsplit(dt.bamstats.coverage$chromosome,"|",fixed=TRUE))
# dt.bamstats.coverage$chromosome <- cc[4*(1:length(dt.bamstats.coverage$chromosome))]
#
# dt.bamstats.coverage <- reshape(dt.bamstats.coverage, idvar = "sample", timevar = "chromosome", direction = "wide")
#
# # adding placeholder column(s) for missing segment(s)
# ls.segment <- list("*HA","*NA","*MP","*NP","*NS","*PA","*PB1","*PB2")
# substrRight <- function(x, n){substr(x, nchar(x)-n+1, nchar(x))}
#
# if (ncol(dt.bamstats.coverage) != 25 ) {
# for (s in ls.segment){
# if (Reduce("|",grepl(s, names(dt.bamstats.coverage)))) {}
# else {
# dt.bamstats.coverage[,paste("reads mapped [%].", substrRight(s, 2))] <- NA
# dt.bamstats.coverage[,paste("coverage [%].", substrRight(s, 2))] <- NA
# dt.bamstats.coverage[,paste("mean depth [bp].", substrRight(s, 2))] <- NA
# }
# }
# }
#
# # reorder dataframe columns
# dt.bamstats.coverage <- dt.bamstats.coverage[, c( "sample","reads mapped [%].HA","coverage [%].HA","mean depth [bp].HA",
# "reads mapped [%].NA","coverage [%].NA","mean depth [bp].NA",
# "reads mapped [%].MP","coverage [%].MP","mean depth [bp].MP",
# "reads mapped [%].NP","coverage [%].NP","mean depth [bp].NP",
# "reads mapped [%].NS","coverage [%].NS","mean depth [bp].NS",
# "reads mapped [%].PA","coverage [%].PA","mean depth [bp].PA",
# "reads mapped [%].PB1","coverage [%].PB1","mean depth [bp].PB1",
# "reads mapped [%].PB2","coverage [%].PB2","mean depth [bp].PB2" )]
```
```{r read_duplicates}
# read file content
dt.read.duplicates <- as.data.table(ldply(l.infiles.read.duplicates, fread, sep='\t', select = c(9), skip=6, nrow=1))
colnames(dt.read.duplicates) <- c("sample","reads duplicated [%]")
dt.read.duplicates$`reads duplicated [%]` <- round(dt.read.duplicates$`reads duplicated [%]` * 100, digits = 2)
```
```{r table_bamstats}
df.output <- data.frame("sample" = unique(df.bamstat.data$sample),
"input" = df.bamstat.data$count[grepl("in total", df.bamstat.data$description)],
"mapped" = df.bamstat.data$count[grepl("properly paired", df.bamstat.data$description)])
df.output$mapping.rate <- round((df.output$mapped / df.output$input)*100, digits = 2)
colnames(df.output) <- c("sample", "reads in", "reads mapped", "mapping rate [%]")
# save table as csv for later use
write.csv( x=df.output,
row.names = FALSE,
file = file.path(params$list_folder, "mapping_stats.csv")
)
# merge read per segment, duplication data with bamstats table
df.mapping.table <- merge(df.output, dt.read.duplicates, by="sample")
##### bamstats coverage table from above is reused
df.mapping.table <- merge(df.mapping.table, dt.bamstats.coverage, by="sample")
# replace dots in column names with space
sub.dots <- function(df) {names(df) <- sub("\\.", " ", names(df));df}
df.mapping.table <- sub.dots(df.mapping.table)
# convert reads mapped per segment column values to mapping rate
seg_col_range <- seq(6,29, by=3) # taking every third segment column
df.mapping.table[, c(seg_col_range)] <- lapply(df.mapping.table[, c(seg_col_range)], function(x) round((x / as.numeric(df.mapping.table$`reads mapped`)*100), digits = 2))
df.mapping.table$`reads in` <- f.color_bar("lightgreen")(df.mapping.table$`reads in`)
df.mapping.table$`reads mapped` <- f.color_bar("lightgreen")(df.mapping.table$`reads mapped`)
write.csv( x=df.mapping.table,
row.names = FALSE,
file = file.path(params$list_folder, "mapping_statistics.csv")
)
kbl(df.mapping.table,
digits = 3,
escape = F) %>%
kable_styling(bootstrap_options = c("striped", "hover"), fixed_thead = T) %>%
scroll_box(height = "400px")
```
```{r bamstats_cleanup}
rm(df.bamstat.data)
rm(dt.bamstats.coverage)
rm(df.output)
rm(df.mapping.table)
```
### Coverage Distribution
The following plots show the read coverage of each sample after mapping. In 100 bp steps the mean read depth was calculated and plotted. Please be aware of the varying x and y axis scaling of the samples. The dotted read line shows the minimal required read depth.
```{r read_coverage}
# read file content
# dt.coverage <- as.data.table(ldply(l.infiles.coverage, fread, sep='\t'))
# colnames(dt.coverage) <- c("sample","chromosome", "position", "depth")
# reduce amount of data points to be plotted
dt.coverage[, bin:=rep(seq(1, ceiling(length(position) / 100)), each = 100, length.out = length(position)), by = "sample"]
dt.coverage[, mid.bin:=seq(1,length(position)) %% 100 ]
dt.coverage[, mean.cov:=mean(depth), by=c("sample", "bin")]
# adding placeholder row(s) for missing segment(s)
ls.segment <- list("*HA","*NA","*MP","*NP","*NS","*PA","*PB1","*PB2")
for (s in unique(dt.coverage$sample)){
tmp <- dt.coverage[dt.coverage$sample == as.character(s),]
for (l in ls.segment){
if (Reduce("|",grepl(l, unique(tmp$chromosome)))) {}
else {
new_row <- list(s, substrRight(l,2), 0, NA, NA, 50, 1)
dt.coverage <- rbind(dt.coverage, new_row)
}
}
rm(tmp)
}
dt.coverage <- dt.coverage %>% group_by(chromosome)
dt.coverage <- dt.coverage %>% arrange(factor(chromosome, levels = c("HA","NA","MP","NP","NS","PA","PB1","PB2")))
dt.coverage <- dt.coverage %>% group_by(sample)
dt.coverage$chromosome = factor(dt.coverage$chromosome, levels=c("HA","NA","MP","NP","NS","PA","PB1","PB2"))
```
#### Sequence depth distribution on reference genome
Sequence depth was calculated at each position and plotted. The aim for positive samples is an evenly distributed high sequence depth.
The plot shows the sequence depth distribution on each segment. The positions were divided into bins with size of 100. In each bin the mean of the depths were then calculated and plotted. Please be aware of the varying x axis scaling.
<div class=superhighimage>
```{r plot_coverage, fig.width=10, fig.height=3}
# https://stackoverflow.com/questions/39119917/how-to-add-a-legend-to-hline
sample.names <- unique(dt.coverage$sample)
for (s in c(sample.names)){
plt <- ggplot(dt.coverage[(dt.coverage$sample == s) & (dt.coverage$mid.bin == 50),],
aes(x=position, y=mean.cov, fill = chromosome, colour = chromosome)) +
labs(title = paste("coverage distribution of", s, sep = " "), y = "mean coverage",
fill = "chromosome") +
geom_bar(stat = "identity", width = 1) +
facet_grid(~chromosome, switch = 'y', scales = "free_x") +
scale_x_continuous(limits = c(0,NA)) +
theme(axis.text.x = element_text(angle = 45, size = 10, hjust = 1)) +
geom_hline(aes(yintercept=min.coverage,
linetype = paste("minimal coverage = ",as.character(min.coverage))),
colour = "red", linewidth = 0.5) +
scale_linetype_manual(name = "threshold", values = c(2),
guide = guide_legend(override.aes = list(color = c("red")))) +
theme(legend.key.size = unit(0.5, 'cm'), legend.title = element_text(size = 10),
legend.text = element_text(size=8))
print(plt)
}
```
```{r coverage_cleanup}
rm(dt.coverage)
```
</div>
### Consensus Sequenz
The consensus sequence was build using BCFtools. Only indels with a frequency above 90 % were integrated into the consensus sequence. Positions with a coverage below the given threshold were masked with an N in the consensus sequence. Variants that passed the filtering steps were explicitly integrated into the consensus sequence if they occurred with a frequency of 90 % or higher. Variants with a frequency between 10 and 90 % were depicted as ambiguous bases and below 10 % the reference base was used. High quality Variants at the beginning or end of a genome segment, with an allele frequency above 90 % that failed the strand-bias filtering step were masked with N.
`r if(!reference){"Reads are compared against reference sequence databases for each segment during the automatic reference detection step . The following table lists the five best references per segment. On the first position is the reference that was used for the mapping."}`
``` {r read_ranking_top5_refs}
if (!reference) {
# read file content
dt.top.refs <- as.data.table(ldply(l.infiles.read.ranking.refs, fread, sep=' ',
select = c(1,16,17), na.strings = ""))
colnames(dt.top.refs) <- c("sample","taxid", "magic number", "segment")
dt.top.refs$taxid <- substr(dt.top.refs$taxid, 20, nchar(dt.top.refs$taxid)-3)
dt.top.refs$sample <- substring(dt.top.refs$sample, 19)
dt.top.refs <- dt.top.refs %>% group_by(sample, segment) %>% arrange(desc(`magic number`))
dt.top.refs <- dt.top.refs %>% arrange(sample, segment)
dt.top.refs <- dt.top.refs[,-3]
dt.top.refs.na.filled <- data.table(sample = as.character(), taxid = as.character(), segment = as.character())
# add placeholder for missing top ref
for (smpl in unique(dt.top.refs$sample)) {