-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_metabarcoding.Rmd
1920 lines (1541 loc) · 76.4 KB
/
local_metabarcoding.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: "iMapPESTS local metabarcoding workflow"
author: "A.M. Piper"
date: "`r Sys.Date()`"
output:
html_document:
highlighter: null
theme: "flatly"
code_download: true
code_folding: show
toc: true
toc_float:
collapsed: false
smooth_scroll: true
df_print: paged
pdf_document: default
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
# Knitr global setup - change eval to true to run code
library(knitr)
knitr::opts_chunk$set(echo = TRUE, eval=FALSE, message=FALSE,error=FALSE, fig.show = "hold", fig.keep = "all")
opts_chunk$set(dev = 'png')
```
# Demultiplex sequencing reads
For this workflow to run, we need to first demultiplex the miseq run again as the miseq does not put indexes in fasta headers by default, and also obtain some necessary files from the sequencing folder. The below code is written for the Agriculture Victoria BASC server, and the locations will be different if you are using a different HPC cluster.
The output directory should be unique for each sequencing run, named as the flowcell id, within a directory called data
For example:
root/
├── data/
├── CJL7D/
BASH:
```{bash demultiplex 1 mismatch}
#load module
module load bcl2fastq2/2.20.0-foss-2018b
#raise amount of available file handles
ulimit -n 4000
###Run1
#Set up input and outputs
inputdir=/group/sequencing/190412_M03633_0313_000000000-CGK9B #CHANGE TO YOUR SEQ RUN
outputdir=/group/pathogens/Alexp/Metabarcoding/imappests/data/CGK9B #CHANGE TO YOUR DATA FOLDER RUN
samplesheet=/group/pathogens/Alexp/Metabarcoding/imappests/data/CGK9B/SampleSheet_CGK9B.csv #CHANGE TO YOUR SAMPLESHEET
# convert samplesheet to unix format
dos2unix $samplesheet
#Demultiplex
bcl2fastq -p 12 --runfolder-dir $inputdir \
--output-dir $outputdir \
--sample-sheet $samplesheet \
--no-lane-splitting --barcode-mismatches 1
# Copy other necessary files and move fastqs
cd $outputdir
cp -r $inputdir/InterOp $outputdir
cp $inputdir/RunInfo.xml $outputdir
cp $inputdir/runInfo.xml $outputdir
cp $inputdir/runParameters.xml $outputdir
cp $inputdir/RunParameters.xml $outputdir
cp $samplesheet $outputdir
mv **/*.fastq.gz $outputdir
# Append fcid to start of sample names if missing
fcid=$(echo $inputdir | sed 's/^.*-//')
for i in *.fastq.gz; do
if ! [[ $i == $fcid* ]]; then
new=$(echo ${fcid} ${i}) #append together
new=$(echo ${new// /_}) #remove any whitespace
mv -v "$i" "$new"
fi
done
```
# Optional: Run R on BASC
You may wish to run this workflow through the BASC command line in order to take advantage of more processing power. To do this, you can start a new SLURM interactive session. Press the CODE button to the lower right to display the code for this optional step.
```{bash, class.source = 'fold-hide'}
# Create new interactive SLURM session
sinteractive --ntasks=1 --cpus-per-task=10 --mem-per-cpu=10GB --time=72:00:00
module load R/4.1.0-foss-2021a
module load pkgconfig/1.5.1-GCCcore-9.3.0-Python-3.8.2
module load GDAL/3.3.0-foss-2021a
module load BLAST+/2.11.0-gompi-2020a
module load Pandoc/2.5
# Load R
R
# Run quit() to quit R once you are finished
```
# Install and load R packages and setup directories {.tabset}
This pipeline depends on various R packages to be installed prior to running. There are now two ways of doing this, the recommended "Renv" option ensures that the exact same software versions are installed to what was used during development. The alternative "Manual" option represents the older default for this pipeline prior to June 2021 and may lead to errors due to packages changing over time.
## Renv
This approach downloads all required package versions to a local cache. This can take a while the first time you run it, and it may be best to restart afterwards
The seqateurs R package also provides wrappers around other software packages for QC. For convenience we will download and install these software in a new folder called "bin"
```{r renv install}
install.packages("renv")
library(renv)
# Download the renv lockfile, which keeps track of package versions
rlock <- readLines("https://github.com/alexpiper/iMapPESTS/blob/master/renv.lock?raw=true")
writeLines(rlock, "renv.lock")
# Restore the renv to install package dependencies
renv::restore(prompt = FALSE)
# Packages to load
.packages <- c(
"devtools",
"ggplot2",
"gridExtra",
"data.table",
"tidyverse",
"stringdist",
"patchwork",
"vegan",
"seqinr",
"patchwork",
"stringi",
"phangorn",
"magrittr",
"galah",
"dada2",
"phyloseq",
"DECIPHER",
"Biostrings",
"ShortRead",
"ggtree",
"savR",
"ngsReports",
"seqateurs",
"taxreturn",
"afdscraper",
"speedyseq"
)
# Load all packages
sapply(.packages, require, character.only = TRUE)
#Install bbmap if its not in $path or in bin folder
if(Sys.which("bbduk") == "" & !file.exists("bin/bbmap/bbduk.sh")){
seqateurs::bbmap_install(dest_dir = "bin")
}
#Install fastqc if its not in $path or in bin folder
if(Sys.which("fastqc") == "" & !file.exists("bin/FastQC/fastqc")){
seqateurs::fastqc_install(dest_dir = "bin")
}
#Install BLAST if its not in $path or in bin folder
if(.findExecutable("blastn") == "" & (length(fs::dir_ls("bin", glob="*blastn.exe",recurse = TRUE)) ==0)){
taxreturn::blast_install(dest_dir = "bin")
}
# Create directories
if(!dir.exists("data")){dir.create("data", recursive = TRUE)}
if(!dir.exists("reference")){dir.create("reference", recursive = TRUE)}
if(!dir.exists("output/logs")){dir.create("output/logs", recursive = TRUE)}
if(!dir.exists("output/results")){dir.create("output/results", recursive = TRUE)}
if(!dir.exists("output/rds")){dir.create("output/rds", recursive = TRUE)}
if(!dir.exists("sample_data")){dir.create("sample_data", recursive = TRUE)}
if(!dir.exists("output/results/final")) {dir.create("output/results/final", recursive = TRUE)}
if(!dir.exists("output/results/unfiltered")) {dir.create("output/results/unfiltered", recursive = TRUE)}
if(!dir.exists("output/results/filtered")) {dir.create("output/results/filtered", recursive = TRUE)}
```
## Manual {-}
This approach manually obtains packages from CRAN, Bioconductor and Github. This method is no longer recomended.
The seqateurs R package also provides wrappers around other software packages for QC. For convenience we will download and install these software in a new folder called "bin"
```{r Manual install}
#Set required packages
.cran_packages <- c(
"devtools",
"ggplot2",
"gridExtra",
"data.table",
"tidyverse",
"stringdist",
"patchwork",
"vegan",
"seqinr",
"patchwork",
"stringi",
"phangorn",
"magrittr",
"galah"
)
.bioc_packages <- c(
"phyloseq",
"DECIPHER",
"Biostrings",
"ShortRead",
"ggtree",
"savR",
"dada2",
"ngsReports"
)
.inst <- .cran_packages %in% installed.packages()
if(any(!.inst)) {
install.packages(.cran_packages[!.inst])
}
.inst <- .bioc_packages %in% installed.packages()
if(any(!.inst)) {
if (!requireNamespace("BiocManager", quietly = TRUE)){
install.packages("BiocManager")
}
BiocManager::install(.bioc_packages[!.inst], ask = F)
}
#Load all published packages
sapply(c(.cran_packages,.bioc_packages), require, character.only = TRUE)
# Install and load github packages
devtools::install_github("alexpiper/seqateurs", dependencies = TRUE)
library(seqateurs)
devtools::install_github("alexpiper/taxreturn", dependencies = TRUE)
library(taxreturn)
devtools::install_github("alexpiper/afdscraper", dependencies = TRUE)
library(afdscraper)
devtools::install_github("mikemc/speedyseq", dependencies = TRUE)
library(speedyseq)
#Install bbmap if its not in $path or in bin folder
if(Sys.which("bbduk") == "" & !file.exists("bin/bbmap/bbduk.sh")){
seqateurs::bbmap_install(dest_dir = "bin")
}
#Install fastqc if its not in $path or in bin folder
if(Sys.which("fastqc") == "" & !file.exists("bin/FastQC/fastqc")){
seqateurs::fastqc_install(dest_dir = "bin")
}
#Install BLAST if its not in $path or in bin folder
if(.findExecutable("blastn") == "" & (length(fs::dir_ls("bin", glob="*blastn.exe",recurse = TRUE)) ==0)){
taxreturn::blast_install(dest_dir = "bin")
}
# Create directories
if(!dir.exists("data")){dir.create("data", recursive = TRUE)}
if(!dir.exists("reference")){dir.create("reference", recursive = TRUE)}
if(!dir.exists("output/logs")){dir.create("output/logs", recursive = TRUE)}
if(!dir.exists("output/results")){dir.create("output/results", recursive = TRUE)}
if(!dir.exists("output/rds")){dir.create("output/rds", recursive = TRUE)}
if(!dir.exists("sample_data")){dir.create("sample_data", recursive = TRUE)}
if(!dir.exists("output/results/final")) {dir.create("output/results/final", recursive = TRUE)}
if(!dir.exists("output/results/unfiltered")) {dir.create("output/results/unfiltered", recursive = TRUE)}
if(!dir.exists("output/results/filtered")) {dir.create("output/results/filtered", recursive = TRUE)}
```
# Create sample sheet
The directory structure should now look something like this:
root/
├── data/
│ ├── CJL7D/
│ │ ├── R1.fastq.gz
│ │ ├── R2.fastq.gz
│ │ ├── runInfo.xml
│ │ ├── runParameters.xml
│ │ ├── SampleSheet.csv
│ │ └── InterOp/
│ └── fcid2/
├── sample_data/
├── reference
├── bin
├── output/
└── doc/
The reference and bin folders can be copied from previous runs.
In order to track samples and relevant QC statistics throughout the metabarcoding pipeline, we will first create a new samplesheet from our input samplesheets. This function requires both the SampleSheet.csv used for the sequencing run, and the runParameters.xml, both of which should have been automatically obtained from the demultiplexed sequencing run folder in the bash step above
```{r create samplesheet}
runs <- dir("data/") #Find all directories within data
SampleSheet <- list.files(paste0("data/", runs), pattern= "SampleSheet", full.names = TRUE)
runParameters <- list.files(paste0("data/", runs), pattern= "[Rr]unParameters.xml", full.names = TRUE)
# Create samplesheet containing samples and run parameters for all runs
samdf <- create_samplesheet(SampleSheet = SampleSheet, runParameters = runParameters, template = "V4") %>%
distinct()
# Merge in existing sample_info metadata file if you have one
sample_info <- readxl::read_excel("sample_data/sample_infoV4.xlsx", sheet="SAMPLESHEET")
samdf <- coalesce_join(samdf, sample_info, by="sample_id")
# Create logfile containing samples and run parameters for all runs
logdf <- create_logsheet(SampleSheet = SampleSheet, runParameters = runParameters) %>%
distinct()
#Check logdf and samdf are the same length
if(!nrow(samdf) == nrow(logdf)){
warning("Samdf and logdf do not contain the same number of rows!")
}
# Check if sampleids contain fcid, if not; attatch
samdf <- samdf %>%
mutate(sample_id = case_when(
!str_detect(sample_id, fcid) ~ paste0(fcid,"_",sample_id),
TRUE ~ sample_id
))
logdf <- logdf %>%
mutate(sample_id = case_when(
!str_detect(sample_id, fcid) ~ paste0(fcid,"_",sample_id),
TRUE ~ sample_id
))
# Check if samples match samplesheet
fastqFs <- purrr::map(list.dirs("data", recursive=FALSE),
list.files, pattern="_R1_", full.names = TRUE) %>%
unlist() %>%
str_remove(pattern = "^(.*)\\/") %>%
str_remove(pattern = "(?:.(?!_S))+$")
fastqFs <- fastqFs[!str_detect(fastqFs, "Undetermined")]
#Check missing in samplesheet
if (length(setdiff(fastqFs, samdf$sample_id)) > 0) {warning("The fastq file/s: ", setdiff(fastqFs, samdf$sample_id), " are not in the sample sheet") }
#Check missing fastqs
if (length(setdiff(samdf$sample_id, fastqFs)) > 0) {
warning(paste0("The fastq file: ",
setdiff(samdf$sample_id, fastqFs),
" is missing, dropping from samplesheet \n"))
samdf <- samdf %>%
filter(!sample_id %in% setdiff(samdf$sample_id, fastqFs))
logdf <- logdf %>%
filter(!sample_id %in% setdiff(logdf$sample_id, fastqFs))
}
#Write out updated sample CSV for use
write_csv(samdf, "sample_data/Sample_info.csv")
write_csv(logdf, "output/logs/logdf.csv")
```
# Quality checks:
We will conduct 3 quality checks. Firstly a check of the entire sequence run, followed by a sample level quality check to identify potential issues with specific samples. And then a calculation of the index switching rate by summarising correctly assigned vs missasigned indices.
```{r QC}
#Load sample sheet
samdf <- read.csv("sample_data/Sample_info.csv", stringsAsFactors = FALSE)
runs <- unique(samdf$fcid)
flowcells <- vector("list", length=length(runs))
for (i in 1:length(runs)){
## Run level quality check using savR
path <- paste0("data/", runs[i], "/")
flowcells[[i]] <- savR(path)
fc <- flowcells[[i]]
qc.dir <- paste0("output/logs/", runs[i],"/" )
dir.create(qc.dir, recursive = TRUE)
write_csv(correctedIntensities(fc), paste0(qc.dir, "correctedIntensities.csv"))
write_csv(errorMetrics(fc), paste0(qc.dir, "errorMetrics.csv"))
write_csv(extractionMetrics(fc), paste0(qc.dir, "extractionMetrics.csv"))
write_csv(qualityMetrics(fc), paste0(qc.dir, "qualityMetrics.csv"))
write_csv(tileMetrics(fc), paste0(qc.dir, "tileMetrics.csv"))
avg_intensity <- fc@parsedData[["savCorrectedIntensityFormat"]]@data %>%
group_by(tile, lane) %>%
summarise(Average_intensity = mean(avg_intensity)) %>%
ungroup() %>%
mutate(side = case_when(
str_detect(tile, "^11") ~ "Top",
str_detect(tile, "^21") ~ "Bottom"
))%>%
ggplot(aes(x=lane, y=as.factor(tile), fill=Average_intensity)) +
geom_tile() +
facet_wrap(~side, scales="free") +
scale_fill_viridis_c()
pdf(file=paste(qc.dir, "/avgintensity.pdf", sep=""), width = 11, height = 8 , paper="a4r")
plot(avg_intensity)
try(dev.off(), silent=TRUE)
pdf(file=paste(qc.dir, "/PFclusters.pdf", sep=""), width = 11, height = 8 , paper="a4r")
pfBoxplot(fc)
try(dev.off(), silent=TRUE)
for (lane in 1:fc@layout@lanecount) {
pdf(file=paste(qc.dir, "/QScore_L", lane, ".pdf", sep=""), width = 11, height = 8 , paper="a4r")
qualityHeatmap(fc, lane, 1:fc@directions)
try(dev.off(), silent=TRUE)
}
}
#Update log DF
logdf <- read_csv("output/logs/logdf.csv")
# Track reads
logdf <- logdf %>%
left_join(
flowcells %>%
purrr::map(~{.x@parsedData[["savTileFormat"]]@data %>%
dplyr::filter(code %in% c(100,101)) %>%
dplyr::mutate(code = case_when(
code == 100 ~ "reads_total",
code == 101 ~ "reads_pf"
))}) %>%
purrr::set_names(runs) %>%
bind_rows(.id="fcid") %>%
group_by(fcid, code) %>%
summarise(reads = sum(value)) %>%
pivot_wider(names_from = code,
values_from = reads),
by="fcid")
write_csv(logdf, "output/logs/logdf.csv")
## Sample level quality check using fastqc
for (i in 1:length(runs)){
path <- paste0("data/", runs[i], "/")
qc.dir <- paste0("output/logs/", runs[i],"/FASTQC" )
dir.create(qc.dir, recursive=TRUE)
qc_out <- seqateurs::fastqc(fq.dir = path, qc.dir = qc.dir, fastqc.path = "bin/FastQC/fastqc", threads=2)
writeHtmlReport(qc.dir, overwrite = TRUE, gcType ="Genome", quiet=FALSE)
}
## Calculate index switching
for (i in 1:length(runs)){
path <- paste0("data/", runs[i], "/")
qc.dir <- paste0("output/logs/", runs[i] )
run_data <- samdf %>%
filter(fcid == runs[i])
indices <- sort(list.files(path, pattern="_R1_", full.names = TRUE)) %>%
purrr::set_names() %>%
purrr::map(seqateurs::summarise_index) %>%
bind_rows(.id="Sample_Name")%>%
arrange(desc(Freq)) %>%
dplyr::mutate(Sample_Name = Sample_Name %>%
str_remove(pattern = "^(.*)\\/") %>%
str_remove(pattern = "(?:.(?!_S))+$"))
if(!any(str_detect(indices$Sample_Name, "Undetermined"))){
stop("Error, an Undetermined reads fastq must be present to calculate index switching")
}
combos <- indices %>%
dplyr::filter(!str_detect(Sample_Name, "Undetermined")) %>%
dplyr::select(index, index2) %>%
tidyr::expand(index, index2)
#get unused combinations resulting from index switching
switched <- left_join(combos, indices, by=c("index", "index2")) %>%
drop_na()
other_reads <- anti_join(indices,combos, by=c("index", "index2")) %>%
summarise(sum = sum(Freq)) %>%
pull(sum)
#Summary of index switching rate
exp_rate <- switched %>%
filter(!str_detect(Sample_Name, "Undetermined"))
obs_rate <- switched %>%
filter(str_detect(Sample_Name,"Undetermined"))
switch_rate <- (sum(obs_rate$Freq)/sum(exp_rate$Freq))
message("Index switching rate calculated as: ", switch_rate)
#Plot switching
gg.switch <- switched %>%
# mutate(index = factor(index, levels = index),
# index2 = factor(index2, levels = index)) %>%
ggplot(aes(x = index, y = index2), stat="identity") +
geom_tile(aes(fill = Freq),alpha=0.8) +
scale_fill_viridis_c(name="log10 Reads", begin=0.1, trans="log10")+
theme(axis.text.x = element_text(angle=90, hjust=1),
plot.title=element_text(hjust = 0.5),
plot.subtitle =element_text(hjust = 0.5)#,
#legend.position = "none"
) +
labs(title= runs[i], subtitle = paste0(
"Total Reads: ", sum(indices$Freq),
", Switch rate: ", sprintf("%1.4f%%", switch_rate*100),
", other Reads: ", other_reads))
pdf(file=paste(qc.dir, "/switchrate.pdf", sep=""), width = 11, height = 8 , paper="a4r")
plot(gg.switch)
try(dev.off(), silent=TRUE)
}
```
# Trim Primers {.tabset}
DADA2 requires Non-biological nucleotides i.e. primers, adapters, linkers, etc to be removed. Following demultiplexing however primer sequences still remain in the reads and must be removed prior to use with the DADA2 algorithm.
For this workflow we will be using the Kmer based adapter trimming software BBDuk (Part of BBTools package https://jgi.doe.gov/data-and-tools/bbtools/) to trim the primers from our raw data files. the seqateurs R package contains a wrapper fucntion to call bbduk from R to trim primers.
If multiple primers have been multiplexed per library, use the multiplexed primer option below, otherwise proceed with the regular single primer workflow.
## Single primer
This workflow is for a single primer-pair per library. For this workflow to run, the pcr_primers, for_primer_seq and rev_primer_seq fields in the sample sheet must contain the primer information.
```{r single primer trimming , message=FALSE}
#Load sample sheet
samdf <- read.csv("sample_data/Sample_info.csv", stringsAsFactors = FALSE)
logdf <- read_csv("output/logs/logdf.csv")
runs <- unique(samdf$fcid)
#Create lists to track reads
trimmed <- vector("list", length = length(runs))
demux <- vector("list", length = length(runs))
#Check primers are present
if(any(is.na(samdf$for_primer_seq), is.na(samdf$rev_primer_seq))){warning("Some primer sequences are missing from samdf, check manually")}
i=1
for (i in 1:length(runs)){
path <- paste0("data/", runs[i])
qc.dir <- paste0("output/logs/", runs[i])
run_data <- samdf %>%
dplyr::filter(fcid == runs[i])
#Get primer sequences
primers <- na.omit(c(unique(run_data$for_primer_seq), unique(run_data$rev_primer_seq)))
# check if any samples need a second round of demultiplexing
twintagged <- any(str_detect(primers, ";"))
if (twintagged == TRUE) stop("Multiple primers are listed per sample in the sample data sheet, use the multi-primer workflow instead")
fastqFs <- sort(list.files(paste0(path), pattern="_R1_", full.names = TRUE))
fastqRs <- sort(list.files(paste0(path), pattern="_R2_", full.names = TRUE))
if(length(fastqFs) != length(fastqRs)) stop(paste0("Forward and reverse files for ",runs[i]," do not match."))
# If there is multiple primer combination per run, do each seperately
primer_runs <- unique(run_data$pcr_primers)
for (p in 1:length(primer_runs)){
primer_data <- run_data %>% dplyr::filter(pcr_primers == primer_runs[p])
Fprimers <- unlist(str_split(unique(primer_data$for_primer_seq), ";"))
Rprimers <- unlist(str_split(unique(primer_data$rev_primer_seq), ";"))
# Subset fastqs to only those samples with target primers
fastqFs_primer <- fastqFs[sapply(fastqFs, function(x){any(str_detect(x, primer_data$sample_id))})]
fastqRs_primer <- fastqRs[sapply(fastqRs, function(x){any(str_detect(x, primer_data$sample_id))})]
trimmed[[i]] <- purrr::map2_dfr(fastqFs_primer, fastqRs_primer, function(x,y){
bbtrim2(install="bin/bbmap", fwd = x, rev = y,
primers = c(Fprimers, Rprimers), checkpairs = FALSE,
degenerate = TRUE, out.dir=file.path(path, "01_trimmed"), trim.end = "left",
kmer=NULL, tpe=TRUE, tbo=TRUE,
ordered = TRUE, mink = FALSE, hdist = 2,
maxlength =(max(run_data$for_read_length,
run_data$rev_read_length) - sort(nchar(c(Fprimers, Rprimers)),
decreasing = FALSE)[1]) +5,
force = TRUE, quiet=FALSE)
})
}
# Check sequence lengths
pre_trim <- plot_lengths(dir=path, aggregate=TRUE, sample=1e5) +
labs(title = runs[i], subtitle = "Pre-trimming")
post_trim <- plot_lengths(dir=paste0(path, "/01_trimmed/"), aggregate=TRUE, sample=1e5)+
labs(title = runs[i], subtitle = "Post-trimming")
pdf(file=file.path(qc.dir, "readlengths.pdf"), width = 11, height = 8 , paper="a4r")
plot(pre_trim)
plot(post_trim)
try(dev.off(), silent=TRUE)
trim_summary <- trimmed[[i]] %>%
mutate(perc_reads_remaining = signif(((output_reads / input_reads) * 100), 2),
perc_bases_remaining = signif(((output_bases / input_bases) * 100), 2)
) %>%
filter(!is.na(perc_reads_remaining))
message(paste0(signif(mean(trim_summary$perc_reads_remaining, na.rm = TRUE), 2),
"% of reads and ",
signif(mean(trim_summary$perc_bases_remaining, na.rm = TRUE), 2),
"% of bases remaining for ", runs[i]," after trimming"))
# Print warning for each sample
for(w in 1:nrow(trim_summary)){
if (trim_summary[w,]$perc_reads_remaining < 10) {message(paste0("WARNING: Less than 10% bases remaining for ",trim_summary[w,]$sample), ", check primer sequences are correct")}
}
}
# Track reads
logdf <- logdf %>%
left_join(
trimmed %>%
purrr::set_names(runs) %>%
bind_rows(.id="fcid") %>%
mutate(sample_id = str_replace(basename(sample), pattern="_S.*$", replacement=""),
reads_demulti = input_reads/2,
reads_trimmed = output_reads/2) %>%
dplyr::select(fcid, sample_id, reads_demulti, reads_trimmed),
by=c("sample_id", "fcid"))
write_csv(logdf, "output/logs/logdf.csv")
```
## Multiplexed primers
This workflow is for multiple primer-pairs per library. These could either be targeting different gene regions, taxa, or be twin-tagged replicate primers.
For the multiplexed workflow to run, the pcr_primers, for_primer_seq and rev_primer_seq fields in the sample sheet must contain all primers separated by a semicolon ';' For example:
pcr_primers
Sterno18SF2-Sterno18SR2;Sterno12SF2-Sterno12SR2;SternoCOIF1-SternoCOIR1
for_primer_seq
ATGCATGTCTCAGTGCAAG;CAYCTTGACYTAACAT;ATTGGWGGWTTYGGAAAYTG
rev_primer_seq
TCGACAGTTGATAAGGCAGAC;TAAAYYAGGATTAGATACCC;TATRAARTTRATWGCTCCTA
```{r multiplexed primer trimming , message=FALSE}
#Load sample sheet
samdf <- read.csv("sample_data/Sample_info.csv", stringsAsFactors = FALSE)
logdf <- read_csv("output/logs/logdf.csv")
runs <- unique(samdf$fcid)
#Create lists to track reads
trimmed <- vector("list", length = length(runs))
demux <- vector("list", length = length(runs))
#Check primers are present
if(any(is.na(samdf$for_primer_seq), is.na(samdf$rev_primer_seq))){warning("Some primer sequences are missing from samdf, check manually")}
# check if any samples need a second round of demultiplexing
i=1
for (i in 1:length(runs)){
path <- paste0("data/", runs[i])
qc.dir <- paste0("output/logs/", runs[i])
run_data <- samdf %>%
dplyr::filter(fcid == runs[i])
#Get primer sequences
primers <- na.omit(c(unique(run_data$for_primer_seq), unique(run_data$rev_primer_seq)))
#Check if samples were twin tagged - these require extra round of demultiplexing
twintagged <- any(str_detect(primers, ";"))
if (twintagged == TRUE) {
# Create output directory
demuxpath <- file.path(path, "00_demux")
dir.create(demuxpath)
# Get list of fasta files
fastqFs <- sort(list.files(path, pattern="*R1_001.*", full.names = TRUE))
fastqRs <- sort(list.files(path, pattern="*R2_001.*", full.names = TRUE))
# If there is multiple primer combination per run, do each seperately
primer_runs <- unique(run_data$pcr_primers)
for (p in 1:length(primer_runs)){
primer_data <- run_data %>% dplyr::filter(pcr_primers == primer_runs[p])
Fprimers <- unlist(str_split(unique(primer_data$for_primer_seq), ";"))
Rprimers <- unlist(str_split(unique(primer_data$rev_primer_seq), ";"))
primer_names <- unlist(str_split(unique(primer_data$pcr_primers), ";"))
# Subset fastqs to only those samples with target primers
fastqFs_primer <- fastqFs[sapply(fastqFs, function(x){any(str_detect(x, primer_data$sample_id))})]
fastqRs_primer <- fastqRs[sapply(fastqRs, function(x){any(str_detect(x, primer_data$sample_id))})]
demux <- purrr::map2_dfr(fastqFs_primer, fastqRs_primer, function(x,y){
bbdemux2(install="bin/bbmap", fwd=x, rev=y, Fbarcodes = Fprimers,
Rbarcodes = Rprimers, names=primer_names, degenerate=TRUE, out.dir=demuxpath,
threads=1 , mem=4, hdist=0, force=TRUE)
})
# Rename output files to match imappests format (FCID_sample_ext1_pcr1_CALngsF1-CALngsR1_S12_R1R2_001.fastq.gz)
old_names <- sort(list.files(paste0(demuxpath), pattern="_R1R2_", full.names = TRUE))
old_names <- old_names[sapply(old_names, function(x){any(str_detect(x, primer_data$sample_id))})]
new_names <- old_names %>%
basename() %>%
str_remove(".fastq.gz") %>%
str_split("_", n=Inf) %>%
purrr::map_chr(function(x){
paste0(paste0( c(x[1:4], x[length(x)], x[5:(length(x)-1)]), collapse = "_"),".fastq.gz")
})
file.remove(file.path(dirname(old_names), new_names))
file.rename(old_names, file.path(dirname(old_names), new_names))
# Trim primers from demultiplexed fastq
demux_fastqs <- sort(list.files(paste0(demuxpath), pattern="_R1R2_", full.names = TRUE))
demux_fastqs <- demux_fastqs[sapply(demux_fastqs, function(x){any(str_detect(x, primer_data$sample_id))})]
trimmed[[i]] <- purrr::map_dfr(demux_fastqs, function(x){
bbtrim2(install="bin/bbmap", fwd = x,
primers = c(Fprimers, Rprimers), checkpairs = FALSE,
degenerate = TRUE, out.dir=file.path(path, "01_trimmed"), trim.end = "left",
kmer=NULL, tpe=TRUE, tbo=TRUE,
ordered = TRUE, mink = FALSE, hdist = 2,
maxlength =(max(run_data$for_read_length, run_data$rev_read_length) - sort(nchar(c(Fprimers, Rprimers)), decreasing = FALSE)[1]) +5, force = TRUE, quiet=FALSE)
})
# Re-split interleaved fastq's
trimmedpath <- file.path(path, "01_trimmed")
trimmed_fastqs <- sort(list.files(trimmedpath, pattern="_R1R2_", full.names = TRUE))
purrr::walk(trimmed_fastqs, function(x){
bbsplit2(install="bin/bbmap", file=x, force=TRUE)
})
}
} else if (twintagged == FALSE) {
fastqFs <- sort(list.files(paste0(path), pattern="_R1_", full.names = TRUE))
fastqRs <- sort(list.files(paste0(path), pattern="_R2_", full.names = TRUE))
if(length(fastqFs) != length(fastqRs)) stop(paste0("Forward and reverse files for ",runs[i]," do not match."))
# If there is multiple primer combination per run, do each seperately
primer_runs <- unique(run_data$pcr_primers)
for (p in 1:length(primer_runs)){
primer_data <- run_data %>% dplyr::filter(pcr_primers == primer_runs[p])
Fprimers <- unlist(str_split(unique(primer_data$for_primer_seq), ";"))
Rprimers <- unlist(str_split(unique(primer_data$rev_primer_seq), ";"))
# Subset fastqs to only those samples with target primers
fastqFs_primer <- fastqFs[sapply(fastqFs, function(x){any(str_detect(x, primer_data$sample_id))})]
fastqRs_primer <- fastqRs[sapply(fastqRs, function(x){any(str_detect(x, primer_data$sample_id))})]
trimmed[[i]] <- purrr::map2_dfr(fastqFs_primer, fastqRs_primer, function(x,y){
bbtrim2(install="bin/bbmap", fwd = x, rev = y,
primers = c(Fprimers, Rprimers), checkpairs = FALSE,
degenerate = TRUE, out.dir=file.path(path, "01_trimmed"), trim.end = "left",
kmer=NULL, tpe=TRUE, tbo=TRUE,
ordered = TRUE, mink = FALSE, hdist = 2,
maxlength =(max(run_data$for_read_length, run_data$rev_read_length) - sort(nchar(c(Fprimers, Rprimers)), decreasing = FALSE)[1]) +5, force = TRUE, quiet=FALSE)
})
}
}
# Check sequence lengths
pre_trim <- plot_lengths(dir=path, aggregate=TRUE, sample=1e5) +
labs(title = runs[i], subtitle = "Pre-trimming")
post_trim <- plot_lengths(dir=paste0(path, "/01_trimmed/"), aggregate=TRUE, sample=1e5)+
labs(title = runs[i], subtitle = "Post-trimming")
pdf(file=file.path(qc.dir, "readlengths.pdf"), width = 11, height = 8 , paper="a4r")
plot(pre_trim)
plot(post_trim)
try(dev.off(), silent=TRUE)
trim_summary <- trimmed[[i]] %>%
mutate(perc_reads_remaining = signif(((output_reads / input_reads) * 100), 2),
perc_bases_remaining = signif(((output_bases / input_bases) * 100), 2)
) %>%
filter(!is.na(perc_reads_remaining))
message(paste0(signif(mean(trim_summary$perc_reads_remaining, na.rm = TRUE), 2),
"% of reads and ",
signif(mean(trim_summary$perc_bases_remaining, na.rm = TRUE), 2),
"% of bases remaining for ", runs[i]," after trimming"))
# Print warning for each sample
for(w in 1:nrow(trim_summary)){
if (trim_summary[w,]$perc_reads_remaining < 10) {message(paste0("WARNING: Less than 10% bases remaining for ",trim_summary[w,]$sample), ", check primer sequences are correct")}
}
}
#Update the sample sheet and logging sheet to deal with any newly demultiplexed files
demultiplexed_samples <- samdf %>%
dplyr::select(sample_id, pcr_primers)
samdf <- samdf %>%
group_by(sample_id) %>%
group_split() %>%
purrr::map(function(x){
if(any(str_detect(x$pcr_primers, ";"))){
primer_names <- unlist(str_split(unique(x$pcr_primers), ";"))
x %>%
mutate(count = length(primer_names)) %>% #Replicate the samples
uncount(count) %>%
mutate(pcr_primers = unlist(str_split(unique(x$pcr_primers), ";")),
for_primer_seq = unlist(str_split(unique(x$for_primer_seq), ";")),
rev_primer_seq = unlist(str_split(unique(x$rev_primer_seq), ";")),
sample_id = paste0(sample_id, "_",pcr_primers)
)
} else (x)
}) %>%
bind_rows()
logdf <- logdf %>%
left_join(demultiplexed_samples) %>%
group_by(sample_id) %>%
group_split() %>%
purrr::map(function(x){
if(any(str_detect(x$pcr_primers, ";"))){
x %>%
mutate(count = length(primer_names)) %>% #Replicate the samples
uncount(count) %>%
mutate(pcr_primers = unlist(str_split(unique(x$pcr_primers), ";")),
sample_id = paste0(sample_id, "_",pcr_primers)
)
} else (x)
}) %>%
bind_rows()
# Track reads
logdf <- logdf %>%
left_join(
trimmed %>%
purrr::set_names(runs) %>%
bind_rows(.id="fcid") %>%
mutate(sample_id = str_replace(basename(sample), pattern="_S.*$", replacement=""),
reads_demulti = input_reads/2,
reads_trimmed = output_reads/2) %>%
dplyr::select(fcid, sample_id, reads_demulti, reads_trimmed),
by=c("sample_id", "fcid"))
write_csv(logdf, "output/logs/logdf.csv")
```
# Plot read quality & lengths {-}
```{r QA plot, eval = FALSE, cache= TRUE}
#Load sample sheet
samdf <- read.csv("sample_data/Sample_info.csv", stringsAsFactors = FALSE)
runs <- unique(samdf$fcid)
# Plotting parameters
readQC_aggregate <- TRUE
readQC_subsample <- 12
amplicon = 205 # Set to maximum size between the two primers. If working with variable barcode lengths, set to the expected or average amplicon length
for (i in 1:length(runs)){
run_data <- samdf %>%
filter(fcid == runs[i])
path <- paste0("data/", runs[i], "/01_trimmed" )
##Get trimmed files, accounting for empty files (28 indicates empty sample)
trimmedFs <- sort(list.files(path, pattern="_R1_", full.names = TRUE))
trimmedFs <- trimmedFs[!str_detect(trimmedFs, "Undetermined")]
trimmedFs <- trimmedFs[file.size(trimmedFs) > 28]
#Choose a random subsample for quality checks
sampleF <- sample(trimmedFs, readQC_subsample) #NOTE - need to have option to pass
sampleR <- sampleF %>% str_replace(pattern="_R1_", replacement = "_R2_")
#Estimate an optimat trunclen
truncLen <- estimate_trunclen(sampleF, sampleR, maxlength=amplicon)
#Plot qualities
gg.Fqual <- plot_quality(sampleF) +
geom_vline(aes(xintercept=truncLen[1]), colour="blue") +
annotate("text", x = truncLen[1]-10, y =2, label = paste0("Suggested truncLen = ", truncLen[1]), colour="blue") +
ggtitle(paste0(runs[i], " Forward Reads")) +
scale_x_continuous(breaks=seq(0,300,25))
gg.Fee <- plot_maxEE(sampleF) +
geom_vline(aes(xintercept=truncLen[1]), colour="blue")+
annotate("text", x = truncLen[1]-10, y =-3, label = paste0("Suggested truncLen = ", truncLen[1]), colour="blue") +
ggtitle(paste0(runs[i], " Forward Reads")) +
scale_x_continuous(breaks=seq(0,300,25)) +
theme(legend.position = "bottom")
gg.Rqual <- plot_quality(sampleR) +
geom_vline(aes(xintercept=truncLen[2]), colour="blue")+
annotate("text", x = truncLen[1]-10, y =2, label = paste0("Suggested truncLen = ", truncLen[2]), colour="blue") +
ggtitle(paste0(runs[i], " Reverse Reads")) +
scale_x_continuous(breaks=seq(0,300,25)) +
theme(legend.position = "bottom")
gg.Ree <- plot_maxEE(sampleR) +
geom_vline(aes(xintercept=truncLen[2]), colour="blue")+
annotate("text", x = truncLen[1]-10, y =-3, label = paste0("Suggested truncLen = ", truncLen[2]), colour="blue") +
ggtitle(paste0(runs[i], " Reverse Reads")) +
scale_x_continuous(breaks=seq(0,300,25)) +
theme(legend.position = "bottom")
Qualplots <- (gg.Fqual + gg.Rqual) / (gg.Fee + gg.Ree)
#output plots
pdf(paste0("output/logs/",runs[i],"/",runs[i], "_prefilt_quality.pdf"), width = 11, height = 8 , paper="a4r")
plot(Qualplots)
try(dev.off(), silent=TRUE)
}
```
This has output a prefilt_quality.pdf plot for each of the runs analysed in the logs folder. On the top is the quality score per cycle, and on the bottom is the cumulative expected errors (calculated as EE = sum(10^(-Q/10)) on a log scale. For the quality plot, the median quality score at each position is shown by the green line, and the quartiles of the quality score distribution by the orange lines. For the maxEE lines, the red lines showing the expected error filter options. The blue vertical line on both plots shows the suggested truncLen option automatically determined.
Ensure that the blue suggested trunclen looks reasonable before continuing. Truncating length will reduce the number of reads violating the expected error filter, and therefore increase the number of reads proceding through the pipeline. The reverse reads will generally have lower quality, and therefore a lower truncLen than the forward reads.
# Filter reads {.tabset}
This stage will use read truncation and max expected error function to remove low quality reads and read tails. All reads containing N bases will also be removed. this will output _postfilt_quality.pdf in the logs folder to determine how sucessfull it has been in cleaning up the quality.
## Non-length variable
```{r filter and trunclen}
samdf <- read.csv("sample_data/Sample_info.csv", stringsAsFactors = FALSE)
runs <- unique(samdf$fcid)
filtered_out <- vector("list", length=length(runs))
# Set important variables for trimming
maxEE <- 1 #Filter reads above Expected errors (EE = sum(10^(-Q/10))). Set higher for poor quality sequences.
rm.lowcomplex <- 0 # Remove low-complexity, set higher for NovaSeq and other 2 colour platforms
amplicon = 205 # Set to maximum size between the two primers. If working with variable barcode lengths, set to readlength
# Estimate best length to truncate forward and reverse reads to
#truncLen <- estimate_trunclen(sampleF, sampleR, maxlength=amplicon)
for (i in 1:length(runs)){
run_data <- samdf %>%
filter(fcid == runs[i])
path <- paste0("data/", runs[i], "/01_trimmed" )
filtpath <- paste0("data/", runs[i], "/02_filtered" ) # Filtered forward files go into the path/filtered/ subdirectory
dir.create(filtpath)
fastqFs <- sort(list.files(path, pattern="_R1_001.*"))
fastqRs <- sort(list.files(path, pattern="_R2_001.*"))
if(length(fastqFs) != length(fastqRs)) stop(paste0("Forward and reverse files for ",runs[i]," do not match."))
filtered_out[[i]] <- filterAndTrim(fwd = file.path(path, fastqFs), filt = file.path(filtpath, fastqFs),
rev = file.path(path, fastqRs), filt.rev = file.path(filtpath, fastqRs),
maxEE = maxEE, truncLen = truncLen, rm.lowcomplex = rm.lowcomplex,
rm.phix = TRUE, matchIDs = TRUE, id.sep = "\\s",
multithread = TRUE, compress = TRUE, verbose = TRUE)
# post filtering plot
filtFs <- sort(list.files(filtpath, pattern="R1_001.*", full.names = TRUE))
sampleF <- sample(filtFs, readQC_subsample)
sampleR <- sampleF %>% str_replace(pattern="R1_001", replacement = "R2_001")
p1 <- plotQualityProfile(sampleF, aggregate = readQC_aggregate) +
ggtitle(paste0(runs[i]," Forward Reads")) +
scale_x_continuous(breaks=seq(0,300,25))
p2 <- plotQualityProfile(sampleR, aggregate = readQC_aggregate) +
ggtitle(paste0(runs[i]," Reverse Reads"))+
scale_x_continuous(breaks=seq(0,300,25))
#output plots
if (!dir.exists("output/logs/")){ dir.create("output/logs/")}
pdf(paste0("output/logs/", runs[i],"/",runs[i], "_postfilt_quality.pdf"), width = 11, height = 8 , paper="a4r")
plot(p1)
plot(p2)
try(dev.off(), silent=TRUE)
filtered_summary <- filtered_out[[i]] %>%
as.data.frame() %>%
rownames_to_column("sample") %>%
mutate(reads_remaining = signif(((reads.out / reads.in) * 100), 2)) %>%
filter(!is.na(reads_remaining))
message(paste0(signif(mean(filtered_summary$reads_remaining, na.rm = TRUE), 2), "% of reads remaining for ", runs[i]," after filtering"))
# Print warning for each sample
for(w in 1:nrow(filtered_summary)){
if (filtered_summary[w,]$reads_remaining < 10) {
message(paste0("WARNING: Less than 10% reads remaining for ", filtered_summary[w,]$sample), "Check filtering parameters ")
}
}
}
#Update log DF
logdf <- read_csv("output/logs/logdf.csv")
logdf <- logdf %>%
left_join(filtered_out %>%
map(as_tibble, rownames=NA) %>%
map(rownames_to_column, var="sample_id") %>%
purrr::set_names(runs) %>%
bind_rows(.id="fcid") %>%
mutate(sample_id = str_replace(basename(sample_id), pattern="_S.*$", replacement="")) %>%
dplyr::select(fcid, sample_id, reads_qualfilt = reads.out),
by=c("sample_id", "fcid"))
write_csv(logdf, "output/logs/logdf.csv")
```
## length variable marker
The main difference between the filtering and trimming for a length variable marker, is we do not want to truncate the reads to a certain length, and instead use a minimum and maximum length.