-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctional_approach.Rmd
1326 lines (1048 loc) · 48.6 KB
/
functional_approach.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
```
# 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 can cause 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}
# 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
options(install.opts = list(roxygen2 = "--no-multiarch"),
renv.consent = TRUE)
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, class.source="bg-warning"}
#Set required packages
.cran_packages <- c(
"devtools",
"ggplot2",
"gridExtra",
"data.table",
"tidyverse",
"stringdist",
"patchwork",
"vegan",
"seqinr",
"patchwork",
"stringi",
"phangorn",
"magrittr",
"galah",
"future",
"furrr"
)
.bioc_packages <- c(
"dada2",
"phyloseq",
"DECIPHER",
"Biostrings",
"ShortRead",
"ggtree",
"savR",
"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,
INSTALL_opts = c("--no-multiarch"))
library(seqateurs)
devtools::install_github("benjjneb/dada2", ref="v1.20", dependencies = TRUE, INSTALL_opts = c("--no-multiarch", "--no-test-load"))
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)
seq_dir <- paste0("data/", runs[i], "/")
qc_dir <- paste0("output/logs/", runs[i],"/" )
test <- run_seq_qc(seq_dir, qc_dir)
test2 <- run_sample_qc(seq_dir, qc_dir, multithread=FALSE, quiet=FALSE)
test3 <- run_switching_calc(seq_dir, qc_dir, multithread=FALSE, quiet=FALSE)
```
# 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.
```{r single primer trimming , message=FALSE}
#Load sample sheet
samdf <- read.csv("sample_data/Sample_info.csv", stringsAsFactors = FALSE)
seq_dir <- "data/JRJ9F/"
qc_dir <- "output/logs/JRJ9F/"
#Get primer sequences
# Plotting parameters
readQC_aggregate <- TRUE
readQC_subsample <- 12
run_data <- samdf
primers <- na.omit(c(unique(run_data$for_primer_seq), unique(run_data$rev_primer_seq)))
test <- samdf %>%
dplyr::slice(1:5)
# Could potentially do away with the logdf altogether if we just add columns to the manifest
library(tictoc)
truncLen <- estimate_trunclen(fastqFs, fastqRs, maxlength=205)
# Run whole pipeline in one go
# rather than seq_dir,
# Do input_dir, and output_dir
library(patchwork)
library(seqateurs)
test2 <- test %>%
#dplyr::select(sample_id, for_primer_seq, rev_primer_seq) %>%
mutate(
# Primer trimming
primer_trim = purrr::pmap(dplyr::select(., sample_id, for_primer_seq, rev_primer_seq, pcr_primers),
.f = ~run_primer_trim2(sample_id = ..1, for_primer_seq=..2, rev_primer_seq=..3, pcr_primers = ..4,
input_dir = "data/JRJ9F/", output_dir = "data/JRJ9F/01_trimmed",
qc_dir="output/logs/JRJ9F/", quiet = FALSE)
),
# Pre-filtering quality plots
prefilt_qualplots = purrr::pmap(dplyr::select(., sample_id),
.f = ~plot_read_quals(sample_id = ..1,
input_dir = "data/JRJ9F/01_trimmed/", truncLen=NULL, quiet = FALSE)
),
# Read filtering
read_filter = purrr::pmap(dplyr::select(., sample_id),
.f = ~run_read_filter(sample_id = ..1,
input_dir = "data/JRJ9F/01_trimmed", output_dir = "data/JRJ9F/02_filtered",
maxEE = 1, truncLen = 150, rm.lowcomplex = 0,
quiet = FALSE)
),
# Post-filtering quality plots
postfilt_qualplots = purrr::pmap(dplyr::select(., sample_id),
.f = ~plot_read_quals(sample_id = ..1,
input_dir = "data/JRJ9F/02_filtered/", truncLen=NULL, quiet = FALSE)
))
test2 %>%
group_by(fcid) %>%
nest() %>%
mutate()
# Next group by fcid and nest
x <- test2$data
run_dada2 <- function(fcid, output_dir, qc_dir, quiet=FALSE){
output_dir <- normalizePath(output_dir)
qc_dir <- normalizePath(qc_dir)
# Create output directory if it doesnt exist
if(!dir.exists(output_dir)) {dir.create(output_dir)}
# Create qc_dir if it doesnt exist
if(!dir.exists(qc_dir)) {dir.create(qc_dir, recursive = TRUE)}
# Find samples with that fcid
fastqFs <- fs::dir_ls(path = input_dir, glob = paste0("*",sample_id, "*_R1_*"))
fastqRs <- fs::dir_ls(path = input_dir, glob = paste0("*",sample_id, "*_R2_*"))
if(length(fastqFs) != length(fastqRs)) stop(paste0("Forward and reverse files for ",sample_id," do not match."))
#Check if there were more than 1 primer per sample
multi_primer <- any(stringr::str_detect(for_primer_seq, ";"), stringr::str_detect(rev_primer_seq, ";"))
if (multi_primer) {
for_primer_seq <- unlist(stringr::str_split(for_primer_seq, ";"))
rev_primer_seq <- unlist(stringr::str_split(rev_primer_seq, ";"))
primer_names <- unlist(stringr::str_split(pcr_primers, ";"))
# Define outfiles
fwd_out <- purrr::map(primer_names, ~{
normalizePath(paste0(output_dir,"/", str_replace(basename(fastqFs), ".fastq", paste0("_",.x, ".fastq"))))
}) %>%
unlist()
rev_out <- purrr::map(primer_names, ~{
normalizePath(paste0(output_dir,"/", str_replace(basename(fastqRs), ".fastq", paste0("_",.x, ".fastq"))))
}) %>%
unlist()
} else if (!multi_primer) {
fwd_out <- normalizePath(paste0(output_dir,"/", basename(fastqFs)))
rev_out <- normalizePath(paste0(output_dir,"/", basename(fastqRs)))
}
# Demultiplex reads and trim primers
res <- trim_primers(fwd = fastqFs,
rev = fastqRs,
fwd_out = fwd_out,
rev_out = rev_out,
for_primer_seq = for_primer_seq,
rev_primer_seq = rev_primer_seq,
n = n, qualityType = qualityType, check_paired = check_paired,
compress =compress, quiet=quiet
)
return(res)
}
# Run infer variants on nested FC DF
# Unnest
# run merge variants on whole dataframe
# Run ASV filtering on whole dataframe
# Run assing taxonomy on whole dataframe
# Run phylogenetics on whole datafame
# Set parameters
nbases = 1e+08 # Minimum number of total bases to use for error rate - increase if samples are deep sequenced (>1M reads per sample)
randomize = TRUE # Pick samples randomly to learn errors
pool = "pseudo" # Higher accuracy for low abundance at expense of runtime. Set to FALSE for a faster run
dada_out <- vector("list", length=length(runs))
i=1
for (i in 1:length(runs)){
run_data <- samdf %>%
filter(fcid == runs[i])
#Check if run used twin tags
filtpath <- paste0("data/", runs[i], "/02_filtered" )
filtFs <- list.files(filtpath, pattern="R1_001.*", full.names = TRUE)
filtRs <- list.files(filtpath, pattern="R2_001.*", full.names = TRUE)
# Learn error rates from a subset of the samples and reads (rather than running self-consist with full dataset)
errF <- learnErrors(filtFs, multithread = TRUE, nbases = nbases, randomize = randomize, qualityType = "FastqQuality", verbose=TRUE)
errR <- learnErrors(filtRs, multithread = TRUE, nbases = nbases, randomize = randomize, qualityType = "FastqQuality", verbose=TRUE)
#write out errors for diagnostics
write_csv(as.data.frame(errF$trans), paste0("output/logs/", runs[i],"/",runs[i],"_errF_observed_transitions.csv"))
write_csv(as.data.frame(errF$err_out), paste0("output/logs/", runs[i],"/",runs[i],"_errF_inferred_errors.csv"))
write_csv(as.data.frame(errR$trans), paste0("output/logs/", runs[i],"/",runs[i],"_errR_observed_transitions.csv"))
write_csv(as.data.frame(errR$err_out), paste0("output/logs/", runs[i],"/",runs[i],"_errR_inferred_errors.csv"))
##output error plots to see how well the algorithm modelled the errors in the different runs
p1 <- plotErrors(errF, nominalQ = TRUE) + ggtitle(paste0(runs[i], " Forward Reads"))
p2 <- plotErrors(errR, nominalQ = TRUE) + ggtitle(paste0(runs[i], " Reverse Reads"))
pdf(paste0("output/logs/", runs[i],"/",runs[i],"_errormodel.pdf"), width = 11, height = 8 , paper="a4r")
plot(p1)
plot(p2)
try(dev.off(), silent=TRUE)
#Error inference and merger of reads
dadaFs <- dada(filtFs, err = errF, multithread = TRUE, pool = pool, verbose = TRUE)
dadaRs <- dada(filtRs, err = errR, multithread = TRUE, pool = pool, verbose = TRUE)
# merge reads
mergers <- mergePairs(dadaFs, filtFs, dadaRs, filtRs, verbose = TRUE, minOverlap = 12, trimOverhang = TRUE)
mergers <- mergers[sapply(mergers, nrow) > 0]
bind_rows(mergers, .id="Sample") %>%
mutate(Sample = str_replace(Sample, pattern="_S.*$", replacement="")) %>%
write_csv(paste0("output/logs/",runs[i],"/",runs[i], "_mergers.csv"))
#Construct sequence table
seqtab <- makeSequenceTable(mergers)
saveRDS(seqtab, paste0("output/rds/", runs[i], "_seqtab.rds"))
# Track reads
getN <- function(x) sum(getUniques(x))
dada_out[[i]] <- cbind(sapply(dadaFs, getN), sapply(dadaRs, getN), sapply(mergers, getN)) %>%
magrittr::set_colnames(c("dadaFs", "dadaRs", "merged")) %>%
as.data.frame() %>%
rownames_to_column("sample_id") %>%
mutate(sample_id = str_replace(basename(sample_id), pattern="_S.*$", replacement=""))
}
#Update log DF
logdf <- read_csv("output/logs/logdf.csv")
logdf <- logdf %>%
left_join(dada_out %>%
purrr::set_names(runs) %>%
bind_rows(.id="fcid") %>%
mutate(reads_denoised = case_when(
dadaFs < dadaRs ~ dadaFs,
dadaFs > dadaRs ~ dadaRs)) %>%
dplyr::select(fcid, sample_id, reads_denoised, reads_merged = merged),
by=c("sample_id", "fcid"))
write_csv(logdf, "output/logs/logdf.csv")
```
# Merge Runs, Remove Chimeras and filter {.tabset}
Following denoising and merging of reads, if there were multiple flowcells of data analyse the sequence tables from these will be merged together. Next the sequences are checked for chimeras, and all sequences containing stop codons are removed. The final cleaned sequence table is saved as output/rds/seqtab_final.rds
Note: this will change if you are using a coding marker or not
## Coding marker
```{r chimera filt coding}
seqtabs <- list.files("output/rds/", pattern="seqtab.rds", full.names = TRUE)
# If multiple seqtabs present, merge.
if(length(seqtabs) > 1){
st.all <- mergeSequenceTables(tables=seqtabs)
} else if(length(seqtabs) == 1) {
st.all <- readRDS(seqtabs)
}
#Remove chimeras
seqtab_nochim <- removeBimeraDenovo(st.all, method="consensus", multithread=TRUE, verbose=TRUE)
message(paste(sum(seqtab_nochim)/sum(st.all),"of the abundance remaining after chimera removal"))
#cut to expected size allowing for some codon indels
seqtab_cut <- seqtab_nochim[,nchar(colnames(seqtab_nochim)) %in% 200:210]
message(paste0("Identified ",
length(colnames(seqtab_nochim)) - length(colnames(seqtab_cut)),
" incorrectly sized sequences out of ", length(colnames(seqtab_nochim)) , " input sequences."))
message(paste(sum(seqtab_cut)/sum(seqtab_nochim),"of the abundance remaining after cutting to expected size"))
#Filter sequences containing stop codons
seqs <- DNAStringSet(getSequences(seqtab_cut))
codon_filt <- codon_filter(seqs)
seqtab_final <- seqtab_cut[,colnames(seqtab_cut) %in% codon_filt]
message(paste0("Identified ",
length(colnames(seqtab_cut)) - length(colnames(seqtab_final)),
" sequences containing stop codon out of ", length(colnames(seqtab_cut)) , " input sequences."))
message(paste(sum(seqtab_final)/sum(seqtab_cut),"of the abundance remaining after removing seqs with stop codons "))
saveRDS(seqtab_final, "output/rds/seqtab_final.rds")
# summarise cleanup
cleanup <- st.all %>%
as.data.frame() %>%
pivot_longer( everything(),
names_to = "OTU",
values_to = "Abundance") %>%
group_by(OTU) %>%
summarise(Abundance = sum(Abundance)) %>%
mutate(length = nchar(OTU)) %>%
mutate(type = case_when(
!OTU %in% getSequences(seqtab_nochim) ~ "Chimera",
!OTU %in% getSequences(seqtab_cut) ~ "Incorrect size",
!OTU %in% getSequences(seqtab_final) ~ "Stop codons",
TRUE ~ "Real"
))
write_csv(cleanup, "output/logs/ASV_cleanup_summary.csv")
#Update log DF
logdf <- read_csv("output/logs/logdf.csv")
logdf <- logdf %>%
left_join(as.data.frame(cbind(rowSums(st.all),
rowSums(seqtab_nochim),
rowSums(seqtab_cut),
rowSums(seqtab_final))) %>%
rownames_to_column("sample_id") %>%
mutate(sample_id = str_replace(basename(sample_id), pattern="_S.*$", replacement="")) %>%
dplyr::select(sample_id, reads_chimerafilt = V2, reads_sizefilt = V3, reads_codonfilt = V4),
by=c("sample_id"))
write_csv(logdf, "output/logs/logdf.csv")
# Output length distribution plots
gg.abundance <- ggplot(cleanup, aes(x=length, y=Abundance, fill=type))+
geom_bar(stat="identity") +
labs(title = "Abundance of sequences")
gg.unique <- ggplot(cleanup, aes(x=length, fill=type))+
geom_histogram() +
labs(title = "Number of unique sequences")
pdf(paste0("output/logs/seqtab_length_dist.pdf"), width = 11, height = 8 , paper="a4r")
plot(gg.abundance / gg.unique)
try(dev.off(), silent=TRUE)
```
## Non-coding marker
If you are not using a coding marker, then stop codons should not be checked for
```{r chimera filt Non-coding}
seqtabs <- list.files("output/rds/", pattern="seqtab.rds", full.names = TRUE)
# If multiple seqtabs present, merge.
if(length(seqtabs) > 1){
st.all <- mergeSequenceTables(tables=seqtabs)
} else if(length(seqtabs) == 1) {
st.all <- readRDS(seqtabs)
}
#Remove chimeras
seqtab_nochim <- removeBimeraDenovo(st.all, method="consensus", multithread=TRUE, verbose=TRUE)
message(paste(sum(seqtab_nochim)/sum(st.all),"of the abundance remaining after chimera removal"))
#cut to expected size allowing for some codon indels
seqtab_final <- seqtab_nochim[,nchar(colnames(seqtab_nochim)) %in% 200:210]
message(paste0("Identified ",
length(colnames(seqtab_nochim)) - length(colnames(seqtab_cut)),
" incorrectly sized sequences out of ", length(colnames(seqtab_nochim)) , " input sequences."))
message(paste(sum(seqtab_final)/sum(seqtab_nochim),"of the abundance remaining after cutting to expected size"))
saveRDS(seqtab_final, "output/rds/seqtab_final.rds")
# summarise cleanup
cleanup <- st.all %>%
as.data.frame() %>%
pivot_longer( everything(),
names_to = "OTU",
values_to = "Abundance") %>%
group_by(OTU) %>%
summarise(Abundance = sum(Abundance)) %>%
mutate(length = nchar(OTU)) %>%
mutate(type = case_when(
!OTU %in% getSequences(seqtab_nochim) ~ "Chimera",
!OTU %in% getSequences(seqtab_final) ~ "Incorrect size",
TRUE ~ "Real"
))
write_csv(cleanup, "output/logs/chimera_summary.csv")
#Update log DF
logdf <- read_csv("output/logs/logdf.csv")
logdf <- logdf %>%
left_join(as.data.frame(cbind(rowSums(st.all),
rowSums(seqtab_nochim),
rowSums(seqtab_final))) %>%
rownames_to_column("sample_id") %>%
mutate(sample_id = str_replace(basename(sample_id), pattern="_S.*$", replacement="")) %>%
dplyr::select(sample_id, reads_chimerafilt = V2, reads_sizefilt = V3),
by=c("sample_id"))
write_csv(logdf, "output/logs/logdf.csv")
# Output length distribution plots
gg.abundance <- ggplot(cleanup, aes(x=length, y=Abundance, fill=type))+
geom_bar(stat="identity") +
labs(title = "Abundance of sequences")
gg.unique <- ggplot(cleanup, aes(x=length, fill=type))+
geom_histogram() +
labs(title = "Number of unique sequences")
pdf(paste0("output/logs/seqtab_length_dist.pdf"), width = 11, height = 8 , paper="a4r")
plot(gg.abundance / gg.unique)
try(dev.off(), silent=TRUE)
```
# Assign taxonomy {.tabset}
Now that we have a cleaned table of sequences and their abundances across samples, we need to assign taxonomy to the sequences in order to identify taxa. The default approach is currently to use IDTAXA to assign heirarchial taxonomy, followed by a BLAST search for increased species level assignment. However there are a number of alternative classifiers you can use to do this, a few of which are represented in the tabs below.
## IDTAXA + BLAST
We will use the IDTAXA algorithm of Murali et al 2018 to assign taxonomy to the ASVs. IDTAXA requires a pre-trained classifier, which can be found in the reference folder, alternatively see the taxreturn r package if you wish to curate a reference database and train a new classifier.
To increase classification to species level, we will also incorporate a BLAST search. However as top hit assignment methods such as BLAST do not take the context of other sequences into account, to reduce the risk of over-classification we will only assign an ASV to species rank if the BLAST search agrees with IDTAXA at the Genus rank.
```{r IDTAXA BLAST}
seqtab_final <- readRDS("output/rds/seqtab_final.rds")
# NOTE: these ranks may differ for different training sets. Check your training set to avoid an error
ranks <- c("Root", "Kingdom", "Phylum","Class", "Order", "Family", "Genus","Species")
#Classify using IDTAXA
trainingSet <- readRDS("reference/idtaxa_bftrimmed.rds")
dna <- DNAStringSet(getSequences(seqtab_final)) # Create a DNAStringSet from the ASVs
ids <- IdTaxa(dna, trainingSet, processors=1, threshold = 60, verbose=TRUE)
saveRDS(ids, "output/rds/idtaxa.rds")
# Output plot of ids
pdf(paste0("output/logs/idtaxa.pdf"), width = 11, height = 8 , paper="a4r")
plot(ids)
try(dev.off(), silent=TRUE)
#Convert the output object of class "Taxa" to a matrix analogous to the output from assignTaxonomy
tax <- t(sapply(ids, function(x) {
taxa <- paste0(x$taxon,"_", x$confidence)
taxa[startsWith(taxa, "unclassified_")] <- NA
taxa
})) %>%
purrr::map(unlist) %>%
stri_list2matrix(byrow=TRUE, fill=NA) %>%
magrittr::set_colnames(ranks) %>%
as.data.frame() %>%
magrittr::set_rownames(getSequences(seqtab_final)) %T>%
write.csv("output/logs/idtaxa_results.csv") %>% #Write out logfile with confidence levels
mutate_all(str_replace,pattern="(?:.(?!_))+$", replacement="") %>%
magrittr::set_rownames(getSequences(seqtab_final))
# Top hit with BLAST
seqs <- insect::char2dna(colnames(seqtab_final))
names(seqs) <- colnames(seqtab_final)
blast_spp <- blast_assign_species(query=seqs,db="reference/insecta_hierarchial_bftrimmed.fa.gz", identity=97, coverage=95, evalue=1e06, max_target_seqs=5, max_hsp=5, ranks=ranks, delim=";") %>%
dplyr::rename(blast_genus = Genus, blast_spp = Species) %>%
dplyr::filter(!is.na(blast_spp))
#Join together
tax_blast <- tax %>%
as_tibble(rownames = "OTU") %>%
left_join(blast_spp , by="OTU") %>%
dplyr::mutate(Species = case_when(
is.na(Species) & Genus == blast_genus ~ blast_spp,
!is.na(Species) ~ Species
)) %>%
dplyr::select(OTU, ranks) %>%
column_to_rownames("OTU") %>%
seqateurs::na_to_unclassified() %>% #Propagate high order ranks to unassigned ASVs
as.matrix()
# Write taxonomy table to disk
saveRDS(tax_blast, "output/rds/tax.rds")
```
## IDTAXA + Exact Matching
As an alternative to using BLAST, we can use exact 100% matches only to assign additional sequences to the species rank. This is particularly useful for bacterial metabarcoding as 100% matches have been shown to be the only valid method of assigning species to short bacterial 16s sequences.
```{r IDTAXA Exact}
seqtab_final <- readRDS("output/rds/seqtab_final.rds")
# NOTE: these ranks may differ for different training sets. Check your training set to avoid an error
ranks <- c("Root", "Kingdom", "Phylum","Class", "Order", "Family", "Genus","Species")
#Classify using IDTAXA
trainingSet <- readRDS("reference/idtaxa_bftrimmed.rds")
dna <- DNAStringSet(getSequences(seqtab_final)) # Create a DNAStringSet from the ASVs
ids <- IdTaxa(dna, trainingSet, processors=1, threshold = 60, verbose=TRUE)
saveRDS(ids, "output/rds/idtaxa.rds")
# Output plot of ids
pdf(paste0("output/logs/idtaxa.pdf"), width = 11, height = 8 , paper="a4r")
plot(ids)
try(dev.off(), silent=TRUE)
#Convert the output object of class "Taxa" to a matrix analogous to the output from assignTaxonomy
tax <- t(sapply(ids, function(x) {
taxa <- paste0(x$taxon,"_", x$confidence)
taxa[startsWith(taxa, "unclassified_")] <- NA
taxa
})) %>%
purrr::map(unlist) %>%
stri_list2matrix(byrow=TRUE, fill=NA) %>%
magrittr::set_colnames(ranks) %>%
as.data.frame() %>%
magrittr::set_rownames(getSequences(seqtab_final)) %T>%
write.csv("output/logs/idtaxa_results.csv") %>% #Write out logfile with confidence levels
mutate_all(str_replace,pattern="(?:.(?!_))+$", replacement="") %>%
magrittr::set_rownames(getSequences(seqtab_final))
#Further assign to species rank using exact matching
exact <- assignSpecies(seqtab_final, "reference/insecta_binomial_bftrimmed.fa.gz", allowMultiple = TRUE, tryRC = TRUE, verbose = FALSE) %>%
as_tibble(rownames = "OTU") %>%
filter(!is.na(Species)) %>%
dplyr::mutate(binomial = paste0(Genus," ",Species)) %>%
dplyr::rename(exact_genus = Genus, exact_species = Species)
#Merge together
tax_exact <- tax %>%
as_tibble(rownames = "OTU") %>%
left_join(exact, by="OTU") %>%
dplyr::mutate(Species = case_when(
is.na(Species) & Genus == exact_genus ~ binomial,
!is.na(Species) ~ Species
)) %>%
dplyr::select(OTU, ranks) %>%
column_to_rownames("OTU") %>%
seqateurs::na_to_unclassified() %>% #Propagate high order ranks to unassigned ASVs
as.matrix()
# Write taxonomy table to disk
saveRDS(tax_exact, "output/rds/tax.rds")
```
## IDTAXA
Alternatively, we can use the IDTAXA classifier by itself with no supplementary assignment
```{r IDTAXA}
seqtab_final <- readRDS("output/rds/seqtab_final.rds")
# NOTE: these ranks may differ for different training sets. Check your training set to avoid an error
ranks <- c("Root","Kingdom", "Phylum","Class", "Order", "Family", "Genus","Species")
#Classify using IDTAXA
trainingSet <- readRDS("reference/idtaxa_bftrimmed.rds")
dna <- DNAStringSet(getSequences(seqtab_final)) # Create a DNAStringSet from the ASVs
ids <- IdTaxa(dna, trainingSet, processors=2, threshold = 60, verbose=TRUE)
saveRDS(ids, "output/rds/idtaxa.rds")
# Output plot of ids
pdf(paste0("output/logs/idtaxa.pdf"), width = 11, height = 8 , paper="a4r")
plot(ids)
try(dev.off(), silent=TRUE)
#Convert the output object of class "Taxa" to a matrix analogous to the output from assignTaxonomy
tax <- t(sapply(ids, function(x) {
taxa <- paste0(x$taxon,"_", x$confidence)
taxa[startsWith(taxa, "unclassified_")] <- NA
taxa
})) %>%
purrr::map(unlist) %>%
stri_list2matrix(byrow=TRUE, fill=NA) %>%
magrittr::set_colnames(ranks) %>%
as.data.frame() %>%
magrittr::set_rownames(getSequences(seqtab_final)) %T>%
write.csv("output/logs/idtaxa_results.csv") %>% #Write out logfile with confidence levels
mutate_all(str_replace,pattern="(?:.(?!_))+$", replacement="") %>%
magrittr::set_rownames(getSequences(seqtab_final)) %>%
seqateurs::na_to_unclassified() %>% #Propagate high order ranks to unassigned ASVs
as.matrix()
# Write taxonomy table to disk
saveRDS(tax, "output/rds/tax.rds")
```
## RDP + Exact Matching {-}
Alternatively, the RDP classifier can be used to assign heirarchial taxonomy to the ASVs using the convenient assigntaxonomy wrapper function within DADA2
```{r RDP classifier, class.source="bg-warning"}
seqtab_final <- readRDS("output/rds/seqtab_final.rds")
# Assign Kingdom:Genus taxonomy using RDP classifier
tax <- assignTaxonomy(seqtab_final, "reference/insecta_hierarchial_bftrimmed.fa.gz", multithread=FALSE, minBoot=60, outputBootstraps=FALSE)
colnames(tax) <- c("Root","Kingdom", "Phylum","Class", "Order", "Family", "Genus", "Species")
saveRDS(tax, "output/rds/rdp.rds")
##add species to taxtable using exact matching
tax_plus <- addSpecies(tax, "reference/insecta_binomial_bftrimmed.fa.gz", allowMultiple=TRUE)
tax_plus <- na_to_unclassified(tax_plus)
# Write taxonomy table to disk
saveRDS(tax_plus, "output/rds/tax.rds")
```
# Optional - Top hit identity distribution
This is an optional step to produce a Top Hit Identity Distribution (THID) plot. This displays the taxonomy assigned to each ASV compared to its genetic distance from the most similar sequence in the reference database. This provides a good overview of how well the taxonomic assignment algorithm has performed, as well as the representation of the target taxa within the reference database. Press the CODE button to the lower right to display the code for this optional step.
```{R top hit dist, class.source = 'fold-hide'}
seqtab_final <- readRDS("output/rds/seqtab_final.rds")
tax <- readRDS("output/rds/tax.rds")
seqs <- insect::char2dna(colnames(seqtab_final))
names(seqs) <- colnames(seqtab_final)
out <- blast_top_hit(query=seqs, db="reference/insecta_hierarchial_bftrimmed.fa.gz", identity=60, coverage=80)
joint <- out %>%
dplyr::select(OTU = qseqid, acc, blastspp = Species, pident, length, evalue, qcovs) %>%
left_join(tax %>%
seqateurs::unclassified_to_na(rownames=FALSE) %>%
mutate(lowest = seqateurs::lowest_classified(.)), by="OTU")
#Write out comparison between BLAST and Heiarchial assignment
write_csv(joint, "output/logs/tax_assignment_comparison.csv")
gg.tophit <- joint %>%
dplyr::select(pident, rank = lowest) %>%
mutate(rank = factor(rank, levels = c("Root","Kingdom","Phylum","Class","Order","Family","Genus","Species"))) %>%
ggplot(aes(x=pident, fill=rank))+
geom_histogram(colour="black", binwidth = 1, position = "stack") +
labs(title = "Top hit identity distribution",
x = "BLAST top hit % identity",
y = "OTUs") +
scale_x_continuous(breaks=seq(60,100,2)) +
scale_fill_brewer(name = "Taxonomic \nAssignment", palette = "Spectral")
gg.tophit
pdf(paste0("output/logs/top_hit_tax_assignment.pdf"), width = 11, height = 8 , paper="a4r")
gg.tophit
try(dev.off(), silent=TRUE)
```
# Make phylogenetic tree
In addition to taxonomic assignment, we will create a phylogenetic tree from the identified sequences to allow interpetation within a phylognetic context.
```{r phylogeny}
seqtab_final <- readRDS("output/rds/seqtab_final.rds")
seqs <- getSequences(seqtab_final)
names(seqs) <- seqs # This propagates to the tip labels of the tree
alignment <- AlignSeqs(DNAStringSet(seqs), anchor=NA)
library(phangorn)
phang.align <- phyDat(as(alignment, "matrix"), type="DNA")
dm <- dist.ml(phang.align)
#Fit NJ tree
treeNJ <- NJ(dm) # Note, tip order != sequence order
fit <- pml(treeNJ, data=phang.align)
#Fit ML tree
fitGTR <- update(fit, k=4, inv=0.2)
fitGTR <- optim.pml(fitGTR, model="GTR", optInv=TRUE, optGamma=TRUE,
rearrangement = "stochastic", control = pml.control(trace = 0))
# Write phytree to disk