-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexploreReads.txt
1563 lines (1043 loc) · 46.3 KB
/
exploreReads.txt
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
## let's take a look at Sulari and Arne's reads
### set up ssh key for this. ###
git remote set-url origin [email protected]:danchurch/fichtelgebirgeSoils.git
## might need to grab files quickly between computers. a template
laptopLoc="/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/fichtelgebirgeSoils"
nanoCompLoc="/media/vol1/daniel/sulariArne/illuminaReads/sulariPhyloseqObject.rda"
scp -r -i ~/.ssh/id_ed25519 [email protected]:$nanoCompLoc $laptopLoc
## or something like that
###########################################
## now, much of this analysis will likely have to be done in R,
## on a computer with sufficient memory.
## the goal would be to contain this analysis to R
## so we'll use dada2 in R
## for the moment, let's use the lab computer,
## let's look in our files for primers, etc:
conda activate
conda create -n readQC -c bioconda cutadapt
readDir="/media/vol1/daniel/sulariArne/illuminaReads/goodReads"
## let's do this old-school:
cd $readDir
gunzip -k *
cat *fq > allSulariArneReads.fq
mkdir /media/vol1/daniel/sulariArne/illuminaReads/fastqcOut
## set variables
file="/media/vol1/daniel/sulariArne/illuminaReads/goodReads/allSulariArneReads.fq"
outdir="/media/vol1/daniel/sulariArne/illuminaReads/fastqcOut"
fastqc -t 10 -o $outdir $file &
path2put=/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/readReport/
path2get="/media/vol1/daniel/sulariArne/illuminaReads/fastqcOut/"
scp -r -i ~/.ssh/id_ed25519 [email protected]:$path2get $path2put
## quality looks great.
## split by direction and check again
## on nanoComp
conda activate
cd /media/vol1/daniel/sulariArne/illuminaReads
readDir="/media/vol1/daniel/sulariArne/illuminaReads/goodReads"
cat $readDir/*good_1.fq > R1_SulariArneReads.fq &
cat $readDir/*good_2.fq > R2_SulariArneReads.fq
r1=/media/vol1/daniel/sulariArne/illuminaReads/R1_SulariArneReads.fq
r2=/media/vol1/daniel/sulariArne/illuminaReads/R2_SulariArneReads.fq
outdir="/media/vol1/daniel/sulariArne/illuminaReads/fastqcOut"
fastqc -t 10 -o $outdir $r1 &
fastqc -t 10 -o $outdir $r2 &
## local machine:
path2put=/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/fichtelgebirgeSoils
path2get="/media/vol1/daniel/sulariArne/illuminaReads/Envt_Matrix.csv"
scp -r -i ~/.ssh/id_ed25519 [email protected]:$path2get $path2put
firefox *html
## all looks pretty amazing. For each (R1 and R2) We have 15510344/195 = 79540 reads per sample.
## after pairing.
## pretty much what they reported.
## look for primers...the first ten or so basepairs are highly conserved in both
## are these remnants of the primers?
## back on nanoComp
head R1_SulariArneReads.fq
wc -l R1_SulariArneReads.fq
## here are the primers used as reported by the company.
GTGYCAGCMGCCGCGGTAA
len('GTGYCAGCMGCCGCGGTAA') ##19
GGACTACNVGGGTWTCTAAT
len('GGACTACNVGGGTWTCTAAT') ##20
## these look like the latest earth microbiome, parada primers
## 515 forward, parada, in R1?:
grep -c "^GTG.CAGC.GCCGCGGTAA" R1_SulariArneReads.fq ## 14903512 reads
grep -c GTG.CAGC.GCCGCGGTAA R1_SulariArneReads.fq ## again 14903512 reads, out of
grep -c "@A01720" R1_SulariArneReads.fq ## 15510344
wc -l R1_SulariArneReads.fq ## 15510344
## 806R, in R1 reads?:
grep -c "GGACTAC..GGGT.TCTAAT" R1_SulariArneReads.fq ## 0 reverse primers, that's good
## reverse complement:
grep -c "ATTAGA.ACCC.NGTAGTCC" R1_SulariArneReads.fq ## 0 reverse RC primers, that's good
## 515 forward, parada, in R2?:
grep -c "^GTG.CAGC.GCCGCGGTAA" R2_SulariArneReads.fq ## 0, good
## 806R, in R1 reads?:
grep -c "GGACTAC..GGGT.TCTAAT" R2_SulariArneReads.fq ## 15170340, out of 15510344
## reverse complement:
grep -c "ATTAGA.ACCC.NGTAGTCC" R2_SulariArneReads.fq ## 0, good.
## this looks like really good data.
## let's clip these primers, and get on to dada2
## make a directories of uncompressed, separated R1/R2
readDir="/media/vol1/daniel/sulariArne/illuminaReads/goodReads"
allReadsPrimersClippedDir="/media/vol1/daniel/sulariArne/illuminaReads/goodReads_primerClipped"
#mkdir $allReadsPrimersClippedDir
readsPrimersClippedDir="/media/vol1/daniel/sulariArne/illuminaReads/goodReads_primerClipped"
conda activate readQC
cd $readDir
cd $allReadsPrimersClippedDir
## something like this?
for iR1 in *good_1.fq; do
iR2=${iR1/_1\.fq/_2\.fq}
echo $iR1
outR1=${iR1/1\.fq/1_trimmed\.fq}
outR2=${iR2/2\.fq/2_trimmed\.fq}
cutadapt -g GTGYCAGCMGCCGCGGTAA -G GGACTACNVGGGTWTCTAAT -o $outR1 -p $outR2 $iR1 $iR2
done
## did that work?
cd /media/vol1/daniel/sulariArne/illuminaReads/uncompressedReads
head -n4 Bacteria_BM663-01M0087_good_1.fq
head -n4 Bacteria_BM663-01M0087_good_1_trimmed.fq
clear
tail -n4 Bacteria_BM663-01M0087_good_1.fq
tail -n4 Bacteria_BM663-01M0087_good_1_trimmed.fq
tail -n4 Bacteria_BM663-01M0087_good_2.fq
tail -n4 Bacteria_BM663-01M0087_good_2_trimmed.fq
grep "^GTG.CAGC.GCCGCGGTAA" Bacteria_BM663-01M0087_good_1.fq ## lots
grep "^GTG.CAGC.GCCGCGGTAA" Bacteria_BM663-01M0087_good_1_trimmed.fq ## nada
## looks pretty good, move them to their own directory:
#mv *trimmed* /media/vol1/daniel/sulariArne/illuminaReads/goodReads_primerClipped/
cd /media/vol1/daniel/sulariArne/illuminaReads/goodReads_primerClipped
######################
## with a specialized environment for dada2.
conda activate
## in R
install.packages("BiocManager")
library("BiocManager")
BiocManager::install("dada2")
BiocManager::install("phyloseq")
BiocManager::install("DESeq2")
library(DESeq2)
library("phyloseq")
## that takes forever.
## following these tutorials from the dada2 site:
http://benjjneb.github.io/dada2/bigdata_paired.html
http://benjjneb.github.io/dada2/bigdata.html
## but start with this:
http://benjjneb.github.io/dada2/tutorial.html
#############
## try to get Arne and Sulari to divide up their read directories, to reduce
## memory usage?
nanoComp
conda activate dada2
R
library(dada2)
library(phyloseq)
library(ggplot2)
library(scales)
library(grid)
packageVersion("dada2")
## will dada2 take our data as is?
## on lab comp
setwd("/media/vol1/daniel/sulariArne/illuminaReads/")
## on personal comp:
#setwd("/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/soilExtractions")
## for clipped:
#path <- "/media/vol1/daniel/sulariArne/illuminaReads/goodReads_primerClipped"
## sample names are here:
sampleNames <- read.csv('sampleName_clientId.txt',
sep='\t',
col.names= c('sampleName', 'clientId'))
## on my personal computer:
#sampleNames <- read.csv('/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/readReport/sampleName_clientId.txt',
# sep='\t',
# col.names= c('sampleName', 'clientId'))
getwd()
head(sampleNames)
## for raw reads:
path <- "/media/vol1/daniel/sulariArne/illuminaReads/uncompressedReads"
## on personal computer: ##
#path <- "/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/readsUncompressed"
list.files(path)
# make two sorted lists, for R1 and R2
fnFs <- sort(list.files(path, pattern="_1.fq", full.names = TRUE))
fnRs <- sort(list.files(path, pattern="_2.fq", full.names = TRUE))
plotQualityProfile(fnFs[1:2]) ## kicks error. is this because of the lab computer setup?
## yes, works fine on my local setup
## does the order of our sampleNames DF fit the order of our file name vectors?
head(sampleNames)
fnFs[1:6]
tail(sampleNames)
fnFs[190:195]
## looks good
## so this should be the vector of sample names:
sample.names <- sampleNames$clientId
filtFs <- file.path(path, "filtered", paste0(sample.names, "_F_filt.fastq.gz"))
filtRs <- file.path(path, "filtered", paste0(sample.names, "_R_filt.fastq.gz"))
names(filtFs) <- sample.names
names(filtRs) <- sample.names
#### can we subset to just Sulari's reads? ###
## use grep to get just samples that start with "S":
onlySulari <- grep("S", filtFs)
controls <- grep("C[1-2]", filtFs)
sulAndCon <- c(onlySulari, controls)
justSulariSamplesF <- filtFs[sulAndCon]
## repeat with reverse files
onlySulari <- grep("S", filtRs)
sulAndCon <- c(onlySulari, controls)
controls <- grep("C[1-2]", filtRs)
justSulariSamplesR <- filtRs[sulAndCon]
length(justSulariSamplesF)
head(justSulariSamplesF)
tail(justSulariSamplesF)
length(justSulariSamplesR)
head(justSulariSamplesR)
tail(justSulariSamplesR)
#################################################
out <- filterAndTrim(fnFs, filtFs, fnRs, filtRs, trimLeft=c(19,20),
maxN=0, maxEE=c(2,2), truncQ=2, rm.phix=TRUE,
compress=TRUE, multithread=TRUE) # On Windows set multithread=FALSE
## that uses pretty much all of my resources on my laptop
## run it on the lab computer.
## for me, I import them here:
out <- filterAndTrim(fnFs, filtFs, fnRs, filtRs, trimLeft=c(19,20),
head(out) ## gives you a report of the results.
## to
## now dada2 needs to model the errors from the sequencing run:
## now this may be to much for laptops:
errF <- learnErrors(filtFs, multithread=TRUE)
## interruptions, so save this to be recovered for tomorrow
#save(errF, file='errF.rda')
load('errF.rda')
errR <- learnErrors(filtRs, multithread=TRUE)
#save(errR, file='errR.rda')
load('errR.rda')
plotErrors(errF, nominalQ=TRUE)
## to run dada2 on ALL the reads (Arne, Sulari, Controls)
dadaFs <- dada(filtFs, err=errR, multithread=TRUE)
#save(dadaFs, file='dadaFs.rda')
dadaRs <- dada(filtRs, err=errR, multithread=TRUE)
## can we do this with just Sulari's reads (and controls)?
dadaFs <- dada(justSulariSamplesF, err=errF, multithread=TRUE)
#save(dadaFs, file="dadaFsSulariOnly.rda")
dadaRs <- dada(justSulariSamplesR, err=errR, multithread=TRUE)
#save(dadaRs, file="dadaRsSulariOnly.rda")
load("sulariData/dadaFsSulariOnly.rda")
## the object is here:
dadaFs[[1]]
dadaRs[[1]]
## for just sulari
mergers <- mergePairs(dadaFs, justSulariSamplesF, dadaRs, justSulariSamplesR, verbose=TRUE)
#save(mergers, file="sulariMergers.rda")
load("sulariMergers.rda")
## for all samples
#mergers <- mergePairs(dadaFs, filtFs, dadaRs, filtRs, verbose=TRUE)
# Inspect the merger data.frame from the first sample
head(mergers[[1]])
## so now we should have fully denoised, merged sequences
## this means we can construct ASVs, or zero-radius-OTUs (zOTUs)
## after merging, keep following the same tutorial, here:
## http://benjjneb.github.io/dada2/tutorial.html
seqtab <- makeSequenceTable(mergers)
?makeSequenceTable
dim(seqtab)
# Inspect distribution of sequence lengths
table(nchar(getSequences(seqtab))
## get rid of chimeras
seqtab.nochim <- removeBimeraDenovo(seqtab, method="consensus", multithread=TRUE, verbose=TRUE)
#save(seqtab.nochim, file ="sulariOnlyseqtab.nochim")
load("sulariOnlyseqtab.nochim")
dim(seqtab.nochim)
## how many were chimeras?
sum(seqtab.nochim)/sum(seqtab) ## 99%, good stuff
## let's get the latest tax training dataset:
wget https://zenodo.org/record/4587955/files/silva_nr99_v138.1_train_set.fa.gz
taxa <- assignTaxonomy(seqtab.nochim, "silva_nr99_v138.1_train_set.fa.gz", multithread=TRUE)
#save(taxa, file ="sulariData/sulariOnlyTaxa.rda")
load("sulariOnlyTaxa.rda")
head(taxa)
taxa.print <- taxa # Removing sequence rownames for display only
rownames(taxa.print) <- NULL
head(taxa.print)
## checking mock communities:
## first mock community
unqs.mock <- seqtab.nochim['S53',]
unqs.mock <- seqtab.nochim['C1.1',]
unqs.mock <- seqtab.nochim['C1.2',]
unqs.mock <- seqtab.nochim['C2.1',]
unqs.mock <- seqtab.nochim['C2.2',]
unqs.mock <- sort(unqs.mock[unqs.mock>0], decreasing=TRUE) # Drop ASVs absent in the Mock
cat("DADA2 inferred", length(unqs.mock), "sample sequences present in the Mock community.\n")
dim(seqtab.nochim)
seqtab.nochim['C1.1',2:10]
tail(seqtab.nochim)[,1:2]
## try these out on phyloseq!
library(phyloseq)
ps <- phyloseq(otu_table(seqtab.nochim, taxa_are_rows=FALSE),
tax_table(taxa))
########## step1 get data into phyloseq ###############
## on lab computer
#conda activate dada2
R
library(dada2)
library(phyloseq)
library(ggplot2)
library(scales)
library(grid)
library(vegan)
library(DESeq2)
library(patchwork) ## good for ggplot
library(BiocGenerics) ## might not need to load in newer versions of deseq2?
library(rsq)
packageVersion("DESeq2") ## I'm working with deseq2 version 1.34.0
## try making a phyloseq object out of just our
## otu table and our taxonomic object:
## on dan's lab computer
#setwd("/media/vol1/daniel/sulariArne/illuminaReads/")
## dan's lab comp
setwd("/home/daniel/Documents/projects/fichtelgebirge_project/sulariArneSoils/fichtelgebirgeSoils")
## we can move directly from the dada2 code block above
dna <- Biostrings::DNAStringSet(taxa_names(ps))
names(dna) <- taxa_names(ps)
ps <- merge_phyloseq(ps, dna)
taxa_names(ps) <- paste0("ASV", seq(ntaxa(ps)))
#save(ps, file="sulariData/sulariData/sulariPhyloseqObject.rda")
## or if we are coming back from a break we can start here:
load("sulariData/sulariPhyloseqObject.rda")
## sulari's environmental data should be here:
## if you need to update...
## get the latest:
download.file(
"https://raw.githubusercontent.com/danchurch/fichtelgebirgeSoils/main/sulariData/Envt_Matrix.csv",
destfile = "sulariData/Envt_Matrix.csv",
method="wget") ## remove this last argument if using windows
env_data = read.csv('sulariData/Envt_Matrix.csv', row.names=1)
## add this dataframe to our phyloseq object as sample_data
sample_data(ps) <- env_data
## and our transformed, min-cutoff, etc ps created below:
sample_data(logMin50ps) <- env_data
## save the R data object
#save(ps, file="sulariData/sulariPhyloseqObject.rda")
#save(logMin50ps, file= "sulariData/sularilogMin50ps.rda")
head(env_data)
##### side note, Sulari found a typo: ####
grep("w1", env_data) ## column 4...
grep("w1", env_data$season) ## row 25
## correct it:
env_data[25,4] <- "W1"
## save it:
write.csv(env_data, 'Envt_Matrix.csv')
## also correct it in the ps phyloseq object
sample_data(ps) <- env_data
## and resave
#save(ps, file="sulariData/sulariPhyloseqObject.rda")
load("sulariData/sulariPhyloseqObject.rda")
##### side note, Sulari found a typo^^^ ####
###### another side note this is how dan got lat/lon data from betty's spreadsheet ####
## we also have geographic data we can add to our
## environmental matrix
## some horrible data wrangling here follows:
## get our geographic data, a csv made from betty's google doc
## I have kept a slightly cleaned up version here:
download.file(
"https://raw.githubusercontent.com/danchurch/fichtelgebirgeSoils/main/carb4D_cleaned.csv",
destfile = "carb4D_cleaned.csv",
method="wget") ## for windows users, don't add this last "method" line, leave it out and use default
geoDat <- read.csv("carb4D_cleaned.csv")
## read in the environmental data we have that doesn't yet have lat/long:
env_data <- read.csv('Envt Matrix.csv')
## make functions to get latitude and longitude out of the geoDat df:
getLat <- function(samp){
bb <- substring(samp, 1, 5)
cc <- grep(bb, geoDat$plotID, value=TRUE)
lat <- as.numeric(geoDat[geoDat$plotID == cc,]["lat"])
return(lat)
}
getLon <- function(samp){
bb <- substring(samp, 1, 5)
cc <- grep(bb, geoDat$plotID, value=TRUE)
lon <- as.numeric(geoDat[geoDat$plotID == cc,]["lon"])
return(lon)
}
## make empty vectors, search for latitude values, fill vectors
lats <- vector()
for (i in env_data$Plot.ID){
lats <- c(lats,getLat( i))
}
## add the control NAs
lats <- c(lats, c(NA,NA,NA,NA))
env_data["Latitude"] <- lats
## repeat for longitude
lons <- vector()
for (i in env_data$Plot.ID){
lons <- c(lons,getLon( i))
}
## add the control NAs
lons <- c(lons, c(NA,NA,NA,NA))
env_data["Longitude"] <- lons
## update the environmental matrix csv file
write.csv(env_data, file='Envt_Matrix.csv', row.names=FALSE)
## use this now as our latest environmental data
## from now on, let's avoid spaces in file names
## and back to the tutorial and data exploration
############## step2 exploting data, especially controls ################
## let's start with this introductory tutorial,
http://joey711.github.io/phyloseq-demo/phyloseq-demo.html
## since we've already imported data to create our
## start with the section "Basic Interaction with phyloseq Data"
## some useful phyloseq commands:
ntaxa(ps)
nsamples(ps)
sample_names(ps)
sample_names(ps)[1:10]
taxa_names(ps)[1:10]
sample_variables(ps)
rank_names(ps)
sample_sums(ps)
(p = plot_richness(ps, x = "pH"))
(p = plot_richness(ps, x = "Land.type"))
p + geom_boxplot(data = p$data, aes(x = "Land.type", y = value, color = NULL), alpha = 0.1)
## we can plot abundances with their ggplot-based functions:
TopNOTUs = names(sort(taxa_sums(ps), TRUE)[1:10])
ps10 = prune_taxa(TopNOTUs, ps)
plot_bar(ps10, "Land.type", facet_grid = ~Phylum)
## or try:
plot_bar(ps10, "Land.type", facet_grid = ~Genus)
## etc, etc
## this actually looks very good. only the 1rst sample is lower than the rest, essentially
## I tend to use base-R plotter, I find it simpler to use:
summary(sample_sums(ps))
quantile(sample_sums(ps))
quantile(sample_sums(ps), probs=c(.50,.60,.70,.80,.90,1))
quantile(sample_sums(ps), probs=c(0.05,.1,.2,.3,.4,.50,.60,.70,.80,.90,0.95,1))
summary(sample_sums(ps), quantile.type=90)
png(file='sulariReadDepths.png')
barplot(sample_sums(ps), main="Read depth by sample")
dev.off()
barplot(sort(sample_sums(ps), decreasing=TRUE))
## so maybe not a lot of correction for mean depth/variance relationship
## especially if we drop singletons.
barplot(get_taxa(ps, "C1.1" ))
## that figure is hard to see/understand. customize a bit.
## We'll use the following customized barplotting function a lot:
rankAb <- function(phyObj, sampleName, ylimit=500, ntax=NULL, textatX=100, textatY=(ylimit-40)){
sampleNo0filter <- get_taxa(phyObj, sampleName) > 0
if(is.null(ntax)) ntax=sum(sampleNo0filter)
print(sum(sampleNo0filter)) ## let user know how many unique taxa are in sample
sampleNo0 <- get_taxa(phyObj, sampleName)[sampleNo0filter]
sampleNo0 <- sort(sampleNo0, decreasing=TRUE)
sampleNo0 <- sampleNo0[1:ntax]
taxaNames=tax_table(phyObj)[ names(sampleNo0), "Genus"]
nuASV <- paste("number of unique ASVs = ",sum(sampleNo0filter), sep="")
par(cex.axis = .75, mar=c(10,4,4,2))
barplot(sampleNo0,
ylim = c(0,ylimit),
main=sampleName,
cex.main=2,
las=2,
names.arg=taxaNames)
text(textatX, textatY, nuASV, cex = 2, )
}
## this function currently takes six arguments:
## phyObj=the phyloseq object of interest
## sampleName=obvious
## ylimit= maximum abundance you want to cut the graph off at, default 500
## ntax= number of taxa you want to look at
## textatX=if you need to adjust the message about number of ASVs
## textatY=if you need to adjust the message about number of ASVs
## this lets us look a little closer:
rankAb(ps,"C1.1")
rankAb(ps,"C1.1", 50000, textatX=100, textatY=10000)
rankAb(ps,"S1", 1000, 10, 5, 800)
## first control, cutoff graph at 100 observations, 10 most abundant species
rankAb(ps,"C1.1", 100,10, 5)
## E. coli has at least two ASVs!
## that is called "OTU-splitting", also in the mock community (C2 controls)
## also see that a lot of the members in our Mock community (C2 controls) ended up
## here in the single species (C1 controls).
## the reverse also happens, see below: E. coli is in our mock community??
## This is called tag-switching!!
## or taller:
rankAb(ps,"C1.1", 100,10, 5)
## look at the single species control side-by-side:
par(mfrow=c(2,1))
rankAb(ps,"C1.1", 10000, 12)
rankAb(ps,"C1.2", 10000, 12)
par(mfrow=c(1,1))
## looking at the mock communities side by side:
par(mfrow=c(2,1))
rankAb(ps,"C2.1", 10000,15, 50)
rankAb(ps,"C2.2", 10000,15, 50)
par(mfrow=c(1,1))
## consistency is good, indicates low sequencer error,
## but lots of "weeds" in there.
## Also E. coli! What is that doing in there??
## it leaked over from our single-species positive control (C1)
## = tag switching!!
## we can explore actual samples, too:
rankAb(ps, "S2", 10000, 15)
############# filtering out errors with abundance #############
## we see from our controls that there are a lot of low abundance
## "weeds", contaminants of some kind
rankAb(ps, "C1.1", 10000, 15)
## putting aside OTU-splitting, let's try tansforming our
## samples to reduce the big artificial differences in abundances
## and make samples a little more comparable.
## let's say that we don't trust any ASV that isn't
## observed at least 50 times in a sample
## set a cutoff
#minCutoff <- 20
#minCutoff <- 30
minCutoff <- 50
#minCutoff <- 150 ## etc
## make a copy of our otu_table from our original phyloseq object:
ot <- otu_table(ps)
## change any ASV's abundance to zero
## if it doesn't meet this cutoff:
ot[ot < minCutoff] <- 0
## insert this into a new phyloseq object
psMinCutoff <- ps
otu_table(psMinCutoff) <- ot
## how many reads do we lose with this?
sum(otu_table(ps)) ## 7944340 originally, before cutoff
sum(otu_table(psMinCutoff)) ## 6943873 after 20 mininum read cutoff
## 5144801 after 50 mininum read cutoff
## and check, does this change our controls much?
par(mfrow=c(2,1))
rankAb(ps,"C1.1", 50000, textatX=100, textatY=20000)
rankAb(psMinCutoff,"C1.1", 80000, textatX=10, textatY=30000)
par(mfrow=c(1,1))
## this C1 control should only have 1 ASV
## a minimum cutoff of 20 reads leaves 73 ASVs out 216
## a minimum cutoff of 30 reads leaves 51 ASVs out 216
## a minimum cutoff of 50 reads leaves 29 ASVs out 216
## and our mock community controls?
par(mfrow=c(2,1))
rankAb(ps,"C2.1", 10000, textatX=50, textatY=8000)
rankAb(psMinCutoff,"C2.1", 10000, textatX=10, textatY=8000)
par(mfrow=c(1,1))
## this C2 control should have 11 ASVs
## a minimum cutoff of 20 reads leaves 36 ASVs out 94
## a minimum cutoff of 30 reads leaves 26 ASVs out 94
## a minimum cutoff of 50 reads leaves 18 ASVs out 94
## check real samples too!
par(mfrow=c(2,1))
rankAb(ps,"S10", ylimit=1000, textatX=500, textatY=300)
rankAb(psMinCutoff,"S10", ylimit=1000, textatX=200, textatY=300)
par(mfrow=c(1,1))
## a minimum cutoff of 20 reads leaves 848 ASVs out of 1796
## a minimum cutoff of 30 reads leaves 569 ASVs out of 1796
## a minimum cutoff of 50 reads leaves 322 ASVs out of 1796
## pretty powerful stuff. We can't really know how many of these
## are "really there" and how many are contaminants of some kind.
## our mock community helps us a bit with this, but in ecological
## samples there are many "real" species that are present in
## much lower amounts that the ASVs in our mock controlr.
## the best we can do is try to find a minimum that removes
## most of the noise from our single species control with as
## little loss overall in reads and ASVs. It is a somewhat
## subjective decision, but record what cutoff you use, and why,
## for readers.
## For the moment, I will use a minimum cutoff of 50 reads,
## it retains all mock community members, and leaves some
## room for appearance of semi-rare species.
## so my phyloseq object going forward is:
minCutoff <- 50
ot <- otu_table(ps)
ot[ot < minCutoff] <- 0
psMinCutoff <- ps
otu_table(psMinCutoff) <- ot
## (code explained above at beginning of this section)
psMinCutoff
###### side note - mystery ASV in C2 controls #####
## side note - unexpected mystery ASV in our positive control
## interestingly, with Sulari's data we do not see an ASV with the
## taxonomy assigned as Enterobacter (which was in
## the mock community). We do see a Klebsiella species...
## maybe this is the Enterobacter?
## the NCBI accession for the intended Enterobacter is here:
https://www.ncbi.nlm.nih.gov/nuccore/EU721605.2/
## does our reference sequence for this Klebsiella bast to this?
## what is it called?
## look at the barplots:
par(mfrow = c(1,2))
rankAb(ps, "C2.1", 10000, 15)
rankAb(ps, "C2.2", 10000, 15)
par(mfrow = c(1,1))
## it's the 4th/5th most common taxa in these controls samples
## which asv is that?
names(sort(get_taxa(ps, "C2.1"), TRUE)[4]) ## ASV62
names(sort(get_taxa(ps, "C2.2"), TRUE)[5]) ## ASV62
## get the reference 16sV4 sequence for this asv:
as.character(refseq(ps)['ASV62'])
## we can blast this sequence quickly on NCBI:
https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE=MegaBlast&PROGRAM=blastn&PAGE_TYPE=BlastSearch&BLAST_SPEC=
## this blasts with 100% to a million different
## klebsiellas, enterobacter, and Leclercia species
## so this is very probably the Enterobacter that
## Nico included in our positive controls
############# step3 transformation of data #########
barplot(sort(sample_sums(ps), TRUE))
## our sample sizes for this run are actually pretty
## even, most of them fall between 60-70,000 reads,
## with a few exceptions. All are between 40,000 and
## 70,000, I think.
## the sample-mean-variance problem is therefore
## not much of an issue here. Especially since
## we are filtering a lot of the low-abundance
## observations out.
## so let's do a simple transformation, as in
## 1- normalization of ASV abundances by sample read total,
## 2 - log-transform of abundances to reduce the effect of
## high abundance reads.
## this would look like this, just using our raw, original phyloseq object:
## transform to normalize by abundances
aa <- transform_sample_counts(ps, function(x) x/sum(x))
## now log transform. Add 1 to avoid the log giving a non-zero
## value to zero abundances
otu_table(aa) <- otu_table(aa) + 1
logTransformedPS <- transform_sample_counts(aa, log)
## how does this affect our controls?
## use the custom rankAb plotting function from above
## if R-studio can't handle two plots at a time,
## ignore the "par" command and run one plot a time.
## since we log transformed, our y-values
## are now much smaller (<15?), so adjust the settings
## accordingly
## this hopefully dampens radical differences in abundances
## for the mock community samples
## check our mock community
par(mfrow=c(1,2))
rankAb(ps,"C2.1", 10000,ntax=NULL,30, 6000)
rankAb(logTransformedPS,"C2.1", 0.2,ntax=NULL,30, 0.1)
par(mfrow=c(1,1))
## single species:
par(mfrow=c(2,1))
rankAb(ps,"C1.1", 10000, ntax=NULL, 100, 2000)
rankAb(logTransformedPS,"C1.1", 1, ntax=NULL, 100,0.5 )
par(mfrow=c(1,1))
## we can combine these two steps
## (minimum cutoffs + transformation)
## we start with this as our phyloseq object
psMinCutoff ## created in step above, 50 read minimum cutoff
## transform to normalize by abundances then log to flatten abundance differences
aa <- transform_sample_counts(psMinCutoff, function(x) x/sum(x))
## now log transform. Add 1 to avoid the log giving a non-zero
## value to zero abundances
otu_table(aa) <- otu_table(aa) + 1
logMin50ps <- transform_sample_counts(aa, log)
## check out the differences.
## use the "pdf" and "dev.off" commands to save these to files for easier viewing
## single species
pdf("filteringStepsSingleSpComparison.pdf")
par(mfrow=c(3,1))
rankAb(ps,"C1.1", 10000, ntax=NULL, 150, 7000)
rankAb(psMinCutoff,"C1.1", 10000, ntax=NULL, 20, 7000)
rankAb(logMin50ps,"C1.1", 1, ntax=NULL, 25, 0.7)
dev.off()
## mock community
pdf("filteringStepsMockComComparison.pdf")
par(mfrow=c(3,1))
rankAb(ps,"C2.1", 10000, ntax=NULL, 50, 7000)
rankAb(psMinCutoff,"C2.1", 10000, ntax=NULL, 15, 7000)
rankAb(logMin50ps,"C2.1", 0.2, ntax=NULL, 14, 0.1)
dev.off()
## real sample
sample="S100"
filename=paste0("filteringStepsSample",sample,"Comparison.pdf")
pdf(filename)
par(mfrow=c(3,1))
rankAb(ps, sample, 1000, ntax=NULL, 1000, 500)
rankAb(psMinCutoff, sample, 1000, ntax=NULL, 200, 500)
rankAb(logMin50ps, sample, 0.03, ntax=NULL, 200, 0.015)
dev.off()
## save out the filtered, transformed phyloseq object
############# ordination ####################
## let's try an ordination:
## or just run it as is:
plot_ordination(ps, ordinate(ps, "MDS"), color = "Land.type") + geom_point(size = 5)
## changing symbols
plot_ordination(ps, ordinate(ps, "MDS"), color = "pH") + geom_point(aes(shape = Land.type), size=5)
## how does this compare to our phyloseq object that has