-
Notifications
You must be signed in to change notification settings - Fork 1
/
EvolutionaryComparisonPipelineLargeTaxa.R
2596 lines (2199 loc) · 117 KB
/
EvolutionaryComparisonPipelineLargeTaxa.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# There is a copy of the GNU General Public License
# along with this program in the repository where it is located.
# Or view it directly here at http://www.gnu.org/licenses/
###################
# Authors and Contributions:
# This program was authored primarily by Matthew Orton.
# Contributions by Jacqueline May for lines 347-378,
# editing, formatting and testing of this program.
# Contributions by David Lee for lines 1822-1843,
# editing and formatting of this program.
# Contributions by Winfield Ly for editing and formatting of this program.
# Collaboration of Sarah Adamowicz (University of Guelph)
# in designing the analyses for this program as well as editing, formatting
# and testing of this program.
###################
# Program Purpose (Class-Level Analyses):
# This program will allow for the generation of latitudinally separated
# sister pairings and associated outgroupings from nearly any taxa
# (provided they have a suitable reference sequence
# and are not too large) and geographical region found on the BOLD API in one
# streamlined R pipeline! In this iteration of the pipeline, data is translated
# directly from a BOLD tsv file of the user's choosing to a dataframe in R.
# The generated sister pairs and outgroups can also be written to a csv or tsv,
# and the file will appear in the current working directory of R. Additionally,
# binomial and Wilcoxon tests can be performed on the signed relative branch
# lengths of the generated pairings, and a plot of the resultant relative
# outgroup distances can be generated for each class. A world map visualizing
# the latitudinally separated pairings for the taxon being run can also be
# generated using using the R visualization tool plotly.
# Larger taxa including various phyla can be run and will get broken down into
# classes, and sister pairs are sought within classes by default.
# ***This version of the program is intended for the larger taxa over 10000
# BIN's in size.***
###################
# Guidelines and Tips on Using this Program:
# The versioning of R and R Studio is important and can influence the results
# of this program. At this time we can only guarantee full function of this
# program using R Studio versions 0.99.903 or 1.0.44 and R versions 3.3.1
# or 3.2.4.
# It is highly recommended that you use the IDE R Studio to run this program
# as this will provide a much more user friendly interface than just using R.
# This program is limited to using the BOLD API for download of taxonomic and
# sequence data. The taxa being tested with this program must use BIN
# identifiers as a means of identification; for instance, plants on the BOLD API
# cannot be run using this program since they do not use BIN identifiers.
# At this time, it is best not to run Arthropoda, Insecta, or Chordata
# in their entirety since these are all very large and computationally demanding
# and should be broken down into smaller sub-taxa. As well be aware that the
# larger insect orders including Diptera, Hymenoptera and Lepidoptera are large
# enough that they require an additional code component that divides the dataset
# into four separate geographical regions: North America, South America,
# Australia and Eurasia/Africa. This code component will be located in
# section 5 of the program.
# It is highly recommended that you save your workspaces frequently with large
# taxa in case of unexpected crashes within R Studio.
# Larger taxa consume a great deal of working memory and R is very memory
# intensive, so be mindful of the amount of available working memory you have
# available on your PC/Mac. As a general rule, every 1000 BIN's processed using
# this program requires roughly 1.5 Gb of working memory.
# It's probably a good idea to ensure RStudio is the only memory intensive
# application running when you run this program with a larger taxon. It is also
# important to note that some taxa are so large that running R Studio locally
# isnt really possible due to computational demands. However there is a great
# online version of R Studio using an EC2 instance on Amazon Web
# Services (cloud computing instance). There is a guide here that will show
# how to use this service:
# http://strimas.com/r/rstudio-cloud-1/
# Entries on BOLD which do not at least have class-level classification
# will be filtered out since the program cannot properly categorize these.
# You do not have to worry about entries missing certain pieces of data,
# for example latitude coordinates, sequence data etc.
# The script will filter these records out automatically.
# There are two options for parsing the tsv.
# You can either download the tsv directly from the BOLD API,
# or you can use a tsv you have previously downloaded. You can also save your
# workspace once a TSV is downloaded so you don't have to download it again.
# When testing a taxon for the first time, you will have to ensure that you have
# a suitable reference sequence for it and ensure that it is inserted into the
# dfRefSeq dataframe in Section 5 of the code. Ensure that you keep the entire
# sequence in one line; breaking it up on to separate lines will add a new line
# character.
# The reference sequence is a high-quality sequence from a given taxon, which is
# used as the basis for the first alignment step. As well, the reference
# sequence is used to trim all sequences to the same length for analysis. To
# insert a sequence to the dfRefSeq dataframe, simply add another taxon and
# sequence in quotation marks in the refseq dataframe commented in the
# reference sequence section.
# Some tips for using the BOLD API since this is what is used to grab
# the relevant data needed from BOLD:
# To see details on how to use the BOLD API,
# go to http://www.boldsystems.org/index.php/resources/api?type=webservices
# We can add additional restrictions to the url, for example
# &instituiton=Biodiversity Institute of Ontario|York University or
# &marker=COI-5P if you want to specifiy an institution.
# geo=all in the url means global but geo can be geo=Canada, for example.
# We can also use | modifier in the url. For example, &geo=Canada|Alaska
# would give data for both Canada and Alaska,
# or taxon=Aves|Reptilia would yield data for both Aves and Reptilia.
#################
# Important Dataframes:
# dfPVal gives the p-values for both the binomial test and Wilcoxon tests for
# all classes (that have pairings) and each class separately.
# dfPairingResultsSummary shows a more user-friendly summation of the
# pairing results.
# dfRelativeBranchLength shows the relative distances to the outgroup for each
# pairing including pseudoreplicates.
# dfPairingResultsL1L2 is a more detailed finalized dataframe that contains all
# of the finalized pairings and outgroupings and all relevant details for them.
# dfPairingResultsL1 and dfPairingResultsL2 represent dataframes for each
# lineage of each pairing, respectively.
# dfInitial is the dataframe first produced by the import from BOLD and is
# filtered by latitude, bin_uri, N content, gap content, and sequence length.
# dfOutGroupL1 and L2 contain the associated outgroupings only
# (for each lineage), but each one does have a column indicating the pairing
# with which it is associated.
# dfCentroid contains centroid sequences for all BINs with more than one member.
# dfNonCentroid contains all BINs that only have one member and thus do not need
# centroid sequences.
# dfAllSeq is simply dfNonCentroid and dfCentroid combined together in one
# dataframe.
# dfGeneticDistanceStack is all genetic distance matrices concatenated into one
# long column of values. It is used to grab bin_uri's and distances for each
# pairing and assist in determining outgroup bin_uri's and distances.
# dfRefSeq shows various taxa with a suitable reference sequence that has been
# found for them.
# dfPseudoRep shows each separate ingroup pairing number of each set of
# pseudoreplicates along with its respective relative outgroup distance.
# dfPseudoRepAverage shows the averaged relative branch lengths for each set of
# pseudoreplicates in dfPseudoRep.
##################
# Important Variables:
# alignment2 will show a truncated alignment of each class before divergent
# sequences are removed. (For example, typing alignment2[1] will show the first
# alignment performed.) Note that the console will not show the full alignment,
# to view the full alignment you must convert and export to FASTA format.
# To export to FASTA format and view the full alignment, please see the commands
# in section 6 of the code.
# alignmentFinal will show a truncated final alignment of each class after
# divergent sequences are removed. (For example, typing alignmentFinal[1] will
# show the first alignment performed.) Note that the console will not show the
# full alignment, to view the full alignment you must convert and export to
# FASTA format. To export to FASTA format and view the full alignment, please
# see the commands in section 7 of the code.
# alignmentFinalTrim will show a truncated final alignment of each class that is
# also trimmed by the reference sequence. (For example, typing
# alignmentFinalTrim[1] will show the first trimmed alignment performed.)
# Note that the console will not show the full alignment, to view the full
# alignment you must convert to FASTA format. To export to FASTA format and view
# the full alignment, please see the commands in section 8 of the code.
# binomialTestOutGroup shows the results of the binomial test.
# wilcoxonTestOutgroup shows the results of the Wilcoxon test.
# mapLayout is a variable that will allow for customization of the world map
# for map plotting using the visualization tool Plotly.
#################
# Packages Required:
# Note that once you have installed the packages (first time running program),
# you only have to run the libraries again each time you open up R Studio or
# restart R Studio.
# Therefore, remove the "#" symbol in front of the lines for installing the
# packages the first time running the script.
# We need the foreach package for several functions that require iteration
# over dataframe rows.
# install.packages("foreach")
library(foreach)
# For genetic distance determination using the TN93 model, the ape package is
# required.
# install.packages("ape")
library(ape)
# The readr package will speed up parsing of the tsv file using the
# read_tsv function.
# install.packages("readr")
library(readr)
# For sequence alignments we need the biostrings (DNAStringSet function)
# and muscle libraries, as follows:
# source("https://bioconductor.org/biocLite.R")
# biocLite("Biostrings")
# biocLite("muscle")
library(Biostrings)
library(muscle)
# For the calculation of overlapping latitude regions we need the
# Desctools package.
# The Desctools package allows us to use the Overlap function which can
# calculate overlap regions between BINs based on the maximum and minimum
# latitudinal ranges of each BIN.
# install.packages("DescTools")
library(DescTools)
# Adding the data tables package for data table merging of outgroup BIN data
# with pairing results BIN data in the pairing result section.
# install.packages("data.table")
library(data.table)
# For plotting of relative outgroup distances between lineages we will also need
# ggplot2.
# install.packages ("ggplot2")
require(ggplot2)
# dplyr is required if this is not already installed.
# install.packages("dplyr")
library(dplyr)
# As a pre-requisite package to plotly we need the colorspace package.
# install.packages("colorspace")
library(colorspace)
# Prerequisite for the plotly package.
# install.packages("jsonlite")
library(jsonlite)
# plotly package used for map plotting functionality.
# install.packages("plotly")
library(plotly)
# Excel writer for output of results to an excel file
# install.packages("xlsx")
library(xlsx)
#################
# R Commands:
# Section 1: TSV Parsing
# In this section the intial TSV of the desired taxon is parsed from the BOLD
# database API.
# First we download the TSV and convert it into a dataframe. The URL below is
# what is modified by the user and will determine the taxon, geographic region,
# etc. Example: taxon=Aves$geo=all, see above in Guidelines and Tips for more
# information on how to use the BOLD API.
# The read_tsv function has been modified to select only certain columns to save
# on downloading time:
dfInitial <- read_tsv("http://www.boldsystems.org/index.php/API_Public/combined?taxon=&geo=all&format=tsv")[,
c('recordID', 'bin_uri','phylum_taxID','phylum_name',
'class_taxID','class_name','order_taxID',
'order_name','family_taxID','family_name',
'subfamily_taxID','subfamily_name','genus_taxID',
'genus_name','species_taxID','species_name',
'lat','lon','nucleotides','markercode')]
# If you want to run pre downloaded BOLD TSV's to avoid downloading of the same
# tsv multiple times, this will let you choose a path to that TSV and parse.
# Uncomment and run these commands:
# tsvParseDoc <- file.choose()
# dfInitial <- read_tsv(tsvParseDoc)[,
# c('recordID', 'bin_uri','phylum_taxID','phylum_name',
# 'class_taxID','class_name','order_taxID',
# 'order_name','family_taxID','family_name',
# 'subfamily_taxID','subfamily_name','genus_taxID',
# 'genus_name','species_taxID','species_name',
# 'lat','lon','nucleotides','markercode')]
# ***Keep in mind you can also save your R workspace to avoid redownloading
# BOLD TSV's.***
###################
# Section 2: Dataframe Filtering and Reorganization
# In this section, the dataframe is filtered according to latitude,
# sequence quality, and sequence length.
# The initial dataframe is also reorganized.
# Renaming record id column.
colnames(dfInitial)[1] <- "record_id"
# Removing sequences with marker codes other than COI-5P.
containCOI <- grep( "COI-5P", dfInitial$markercode)
dfInitial<-dfInitial[containCOI,]
# Removing sequences with no latitude values. We are filtering according to lat
# since we only really need lat for the analysis.
containLat <- grep( "[0-9]", dfInitial$lat)
dfInitial<-dfInitial[containLat,]
# Next, we have to convert the lat column to num instead of chr type. This will
# become important later on for median latitude determination.
latNum <- with(dfInitial, as.numeric(as.character(lat)))
dfInitial$latNum <- latNum
# We will do lon as well for map plotting using plotly.
lonNum <- with(dfInitial, as.numeric(as.character(lon)))
dfInitial$lonNum <- lonNum
# We next identify records missing a BIN assignment and eliminate rows with
# missing bin_uri's since the presence of a BIN designation is an indicator of
# sequence length and quality. As well, we use BINs later in the analysis.
# This is achieved by using grep by colon, since every record with a BIN
# identifier will have this.
containBin <- grep( "[:]", dfInitial$bin_uri)
dfInitial <- dfInitial[containBin,]
# We next get rid of any records that don't have sequence data.
# Sometimes there are records that bear a BIN but for which the sequence was
# subsequently deleted. This could occur if a record had a sequence and the
# record holder later deleted the sequence, e.g. due to suspected contamination.
containNucleotides <- grep( "[ACGT]", dfInitial$nucleotides)
dfInitial <- dfInitial[containNucleotides,]
# Next, we filter out high gap content and N content to ensure high sequence
# quality.
# First, we need to convert nucleotides to chr type.
dfInitial$nucleotides <- with(dfInitial, (as.character(nucleotides)))
# Cut off starting Ns and gaps (large portions of Ns and gaps occur at the start
# of a sequence).
startNGap <- sapply(regmatches(dfInitial$nucleotides, gregexpr("^[-N]",
dfInitial$nucleotides)), length)
startNGap <- foreach(i=1:nrow(dfInitial)) %do%
if (startNGap[[i]] > 0) {
split <- strsplit(dfInitial$nucleotides[i], "^[-N]+")
dfInitial$nucleotides[i] <- split[[1]][2]
}
# Cut off ending Ns and gaps (large portions of Ns and gaps occur at the end of
# a sequence).
endNGap <- sapply(regmatches(dfInitial$nucleotides, gregexpr("[-N]$",
dfInitial$nucleotides)), length)
endNGap <- foreach(i=1:nrow(dfInitial)) %do%
if (endNGap[[i]] > 0) {
split <- strsplit(dfInitial$nucleotides[i], "[-N]+$")
dfInitial$nucleotides[i] <- split[[1]][1]
}
# This will give the number of positions where an *internal* N or gap is found
# for each sequence.
internalNGap <- sapply(regmatches(dfInitial$nucleotides, gregexpr("[-N]",
dfInitial$nucleotides)), length)
# We then loop through each sequence to see if the number of Ns or gaps is
# greater than 1% (0.01) of the total sequence length.
internalNGap <- foreach(i=1:nrow(dfInitial)) %do%
which((internalNGap[[i]] / nchar(dfInitial$nucleotides[i]) > 0.01 ))
nGapCheck <- sapply( internalNGap , function (x) length( x ) )
nGapCheck <- which(nGapCheck > 0)
# Subset out these higher gap and N content sequences.
dfInitial <- dfInitial[-nGapCheck, ]
# Filter out sequences less than 640 bp and greater than 1000 bp since these
# sequence length extremes can interfere with the alignment,
# and this also helps to standardize sequence length against the reference
# sequences, for consistency in subsequent analyses.
sequenceLengths <- nchar(gsub("-", "", dfInitial$nucleotides))
sequenceLengthCheck <- which(sequenceLengths > 1000 | sequenceLengths < 640)
dfInitial <- dfInitial[-sequenceLengthCheck,]
# Modifying BIN column slightly to remove "BIN:"
dfInitial$bin_uri <- substr(dfInitial$bin_uri, 6 , 13)
# Dataframe Reorganization
dfInitial <- (dfInitial[,c("record_id","bin_uri","phylum_taxID","phylum_name",
"class_taxID","class_name","order_taxID","order_name"
,"family_taxID","family_name","subfamily_taxID",
"subfamily_name","genus_taxID","genus_name",
"species_taxID","species_name","nucleotides",
"latNum","lonNum")])
###################
# Section 3: BIN Stats and Median Latitude/Longitude Determination per BIN
# In this section, the median latitude is determined for each BIN as well as
# other important pieces of information including number of record ids within
# each BIN and the latitudinal min and max of each BIN.
# First we can make a smaller dataframe with the columns we want for each BIN:
# bin_uri, latnum, lonnum, record_id, and nucleotides.
dfBinList <-
(dfInitial[,c("record_id","bin_uri","latNum","lonNum","nucleotides")])
# We convert latitudes to absolute values before median latitude values are
# calculated on dfBinList.
dfBinList$latNumAbs <- abs(dfBinList$latNum)
# Lon remains untouched as it is not needed for the analysis.
# Create groupings by BIN with each grouping representing a different bin_uri.
# Each element of this list represents a BIN with subelements representing the
# various columns of the initial dataframe created, and the information is
# grouped by BIN.
binList <- lapply(unique(dfBinList$bin_uri), function(x)
dfBinList[dfBinList$bin_uri == x,])
# Now determine the median latitude for each BIN based on absolute values.
medianLatAbs <- sapply( binList , function(x) median( x$latNumAbs ) )
# Calculating median lat based upon the original latitude values,
# for mapping purposes only.
medianLatMap <- sapply( binList , function(x) median( x$latNum ) )
# We also need a median longitude for map plotting.
medianLon <- sapply( binList , function(x) median( x$lonNum ) )
# We can also take a few other important pieces of data regarding each BIN using
# sapply, including number of record_ids within each BIN and the latitudinal min
# and max of each BIN.
latMin <- sapply( binList , function(x) min( x$latNum ) )
latMax <- sapply( binList , function(x) max( x$latNum ) )
binSize <- sapply( binList , function (x) length( x$record_id ) )
# Dataframe of our median lat values. This will be used in our final dataframe.
dfLatLon <- data.frame(medianLatAbs)
# Adding bin_uri, latMin, latMax, binSize and medianLatMap to dataframe.
# medianLatMap is the median latitude without conversion to an absolute value
# and is used purely for mapping purposes.
dfLatLon$bin_uri <- c(unique(dfInitial$bin_uri))
dfLatLon$medianLon <- c(medianLon)
dfLatLon$latMin <- c(latMin)
# Convert to absolute value for latMin and latMax.
dfLatLon$latMin <- abs(dfLatLon$latMin)
dfLatLon$latMax <- c(latMax)
dfLatLon$latMax <- abs(dfLatLon$latMax)
dfLatLon$binSize <- c(binSize)
dfLatLon$medianLatMap <- c(medianLatMap)
# Merging LatLon to BinList for the sequence alignment step.
dfBinList <- merge(dfBinList, dfLatLon, by.x = "bin_uri", by.y = "bin_uri")
# Also reordering dfLatLon by bin_uri for a step later on.
dfLatLon <- dfLatLon[order(dfLatLon$bin_uri),]
###################
# Section 4: Selecting a Centroid Sequence Per BIN
# A single Barcode Index Number (BIN) can contain many record ids and sequences.
# In order to simplify the analyses, we select one sequence per BIN.
# To do this we are determining the centroid sequence for each BIN.
# Centroid Sequence: BIN sequence with minimum average pairwise distance to all
# other sequences in a given BIN.
# First we have to subset dfBinList to find BINs with more than one member since
# these BINs will need centroid sequences.
largeBin <- which(dfBinList$binSize > 1)
# If there is at least one BIN with more than one member, then a dataframe
# dfCentroid will be created with those BINs.
if (length(largeBin) > 0) {
dfCentroid <- dfBinList[largeBin,]
# Also subset dfLatLon down to number of BINs in dfInitial
dfLatLon <- subset(dfLatLon, dfLatLon$bin_uri %in% dfCentroid$bin_uri)
# Also need to find the number of unique BINs in dfCentroid.
binNumberCentroid <- unique(dfCentroid$bin_uri)
binNumberCentroid <- length(binNumberCentroid)
# We also have to create another separate dataframe with BINs that only have
# one member called dfNonCentroid.
dfNonCentroid <- dfBinList[-largeBin, ]
# We then take the dfCentroid sequences and break it down into a list with
# each element being a unique BIN.
largeBinList <- lapply(unique(dfCentroid$bin_uri),
function(x) dfCentroid[dfCentroid$bin_uri == x,])
# Extract record id from each BIN.
largeBinRecordId <- sapply( largeBinList , function(x) ( x$record_id ) )
# Convert all of the sequences in the largeBinList to dnaStringSet format for
# the alignment step.
dnaStringSet1 <-
sapply( largeBinList, function(x) DNAStringSet(x$nucleotides) )
# name DNAStringSet with the record ids.
for (i in seq(from = 1, to = binNumberCentroid, by = 1)) {
names(dnaStringSet1[[i]]) <- largeBinRecordId[[i]]
}
# Multiple sequence alignment using the muscle package.
# Refer here for details on package:
# https://www.bioconductor.org/packages/release/bioc/html/muscle.html
# Run a multiple sequence alignment on each element of the dnaStringSet1 list
# Using diags = TRUE with Muscle command to speed up alignment of each BIN.
# ***For larger taxa, it is highly recommended to use a maxiter
# setting of 2 to reduce alignment times.***
alignment1 <- foreach(i=1:binNumberCentroid) %do%
muscle::muscle(dnaStringSet1[[i]], maxiters = 2, diags = TRUE, gapopen = -3000)
# We can then convert each alignment to DNAbin format.
dnaBINCentroid <-
foreach(i=1:binNumberCentroid) %do% as.DNAbin(alignment1[[i]])
# Then, we perform genetic distance determination with the TN93 model on each
# DNAbin list.
geneticDistanceCentroid <- foreach(i=1:binNumberCentroid) %do%
dist.dna(dnaBINCentroid[[i]], model = "TN93", as.matrix = TRUE,
pairwise.deletion = TRUE)
# The centroid sequence can be determined from the distance matrix alone.
# It is the sequence in a bin with minimum average pairwise distance to all
# other sequences in its BIN.
centroidSeq <- foreach(i=1:binNumberCentroid) %do%
which.min(rowSums(geneticDistanceCentroid[[i]]))
centroidSeq <- unlist(centroidSeq)
centroidSeq <- names(centroidSeq)
centroidSeq <- as.numeric(centroidSeq)
# Subset dfCentroid by the record ids on this list.
dfCentroid <- subset(dfCentroid, record_id %in% centroidSeq)
# Append our noncentroid to our centroid sequences. We will make a new
# dataframe for this - dfAllSeq.
# Now we have all of the sequences we need for the next alignment of all
# sequences, with one sequence representing each BIN.
dfAllSeq <- rbind(dfCentroid, dfNonCentroid)
# We can then merge this with dfInitial to get all of the relevant data we
# need, merging to dfInitial to gain all the relevant taxanomic data.
dfAllSeq <- merge(dfAllSeq, dfInitial, by.x = "record_id", by.y = "record_id")
# Renaming and reorganizing the dataframe.
dfAllSeq <-
(dfAllSeq[,c("bin_uri.x","binSize","record_id","phylum_taxID","phylum_name",
"class_taxID","class_name","order_taxID","order_name",
"family_taxID","family_name","subfamily_taxID",
"subfamily_name","genus_taxID","genus_name","species_taxID",
"species_name","nucleotides.x","medianLatAbs","medianLatMap",
"latMin","latMax","medianLon")])
colnames(dfAllSeq)[1] <- "bin_uri"
colnames(dfAllSeq)[18] <- "nucleotides"
# Adding an index column to reference later with Pairing Results dataframe.
dfAllSeq$ind <- row.names(dfAllSeq)
# Deleting any possible duplicate entries.
dfAllSeq <- (by(dfAllSeq, dfAllSeq["bin_uri"], head, n = 1))
dfAllSeq <- Reduce(rbind, dfAllSeq)
} else {
# Else if there are no BINs with more than one member then we would simply
# merge latlon with initial to get dfAllSeq and thus all of the sequences we
# want.
dfAllSeq <- merge(dfLatLon, dfInitial, by.x = "bin_uri", by.y = "bin_uri")
dfAllSeq <-
(dfAllSeq[,c("bin_uri.x","binSize","record_id","phylum_taxID","phylum_name",
"class_taxID","class_name","order_taxID","order_name",
"family_taxID","family_name","subfamily_taxID",
"subfamily_name","genus_taxID","genus_name","species_taxID",
"species_name","nucleotides.x","medianLatAbs","medianLatMap",
"latMin","latMax","medianLon")])
dfAllSeq$ind <- row.names(dfAllSeq)
}
# To simplify the number of dataframes, can remove dfLatLon and dfBinList since
# these are redundant.
rm(dfBinList)
rm(dfLatLon)
gc()
###################
# Section 5: Creation of Reference Sequence Dataframe
# In this section we establish reference sequences that will be used in the
# final alignment for appropriate trimming of the alignment to a standard
# sequence length of 620 bp.
# Currently, the script is finetuned for reference sequences of 658 bp of
# the barcode region of the cytochrome c oxidase subunit I (COI) gene. Minor
# modifications to the alignment settings or trimming amount would be needed to
# use sequences of different lengths or different genes.
# We selected reference sequences that fell between the primers for COI
# by Folmer et al. (1994):
# Folmer O, M, Black WH, Lutz R, Vrijenhoek R (1994) DNA primers for
# amplification of mitochondrial cytochrome C oxidase subunit I from metazoan
# invertebrates. Molecular Marine Biology and Biotechnology 3: 294-299.
# In DNA barcoding studies, many taxonomic groups are amplified by these primers
# or by variants of these primers that bind at the same position. For most taxa,
# the reference sequences were exactly 658 bp in length. For certain taxa
# (e.g. Bivalvia), the length differed from 658 bp due to amino acid indels, but
# the same start and end point, as verified using an amino acid alignment,
# was used.
# Manual input of reference sequences into dfRefSeq dataframe
dfRefSeq <- data.frame(taxa = c("",""),
nucleotides = c("",
""))
colnames(dfRefSeq)[2] <- "nucleotides"
dfRefSeq$nucleotides <- as.character(dfRefSeq$nucleotides)
# Symmetrical trimming of the references to a standard 620 bp from 658 bp.
# A different trimming length could be used, depending upon the distribution of
# sequence lengths in a particular taxon.
dfRefSeq$nucleotides <-
substr(dfRefSeq$nucleotides, 20, nchar(dfRefSeq$nucleotides) - 19)
# Check of sequence length.
dfRefSeq$seqLength <- nchar(dfRefSeq$nucleotides)
# Subset dfAllSeq by entries in the reference sequence dataframe.
dfAllSeq <- subset(dfAllSeq, dfAllSeq$class_name %in% dfRefSeq$taxa)
# Breakdown of a taxon by geographical region, please uncomment one set of these
# commands (ex: North American Region) to breakdown by a specific geographical
# region. Breaking down by region will require 4 runthroughs after section 5 to
# complete a taxon.
# ***For the large insect orders including Hymenoptera, Diptera and Lepidoptera,
# running by region will most likely be required due to their large size.***
# North American Region
# northAmericaFilter <- which(dfAllSeq$medianLatMap > 7 &
# dfAllSeq$medianLon > (-170) & dfAllSeq$medianLon < (-15) &
# dfAllSeq$medianLatMap < 90)
# dfAllSeq <- dfAllSeq[northAmericaFilter, ]
# South American Region
# southAmericaFilter <- which(dfAllSeq$medianLatMap < 7 &
# dfAllSeq$medianLon > (-135) & dfAllSeq$medianLon < (-30) &
# dfAllSeq$medianLatMap > (-90))
# dfAllSeq <- dfAllSeq[southAmericaFilter, ]
# Australasian Region
# australasianFilter1 <- which(dfAllSeq$medianLatMap > (-90) &
# dfAllSeq$medianLon < (-135) & dfAllSeq$medianLon > (-180) &
# dfAllSeq$medianLatMap < 0)
# australasianFilter2 <- which(dfAllSeq$medianLatMap > (-90) &
# dfAllSeq$medianLon < (180) & dfAllSeq$medianLon > (90) &
# dfAllSeq$medianLatMap < 0)
# australasianFilter3 <- append(australasianFilter1, australasianFilter2)
# dfAllSeq <- dfAllSeq[australasianFilter3, ]
# Eurasia/African Region
# northAmericaFilter <- which(dfAllSeq$medianLatMap > 7 &
# dfAllSeq$medianLon > (-170) & dfAllSeq$medianLon < (-15) &
# dfAllSeq$medianLatMap < 90)
# southAmericaFilter <- which(dfAllSeq$medianLatMap < 7 &
# dfAllSeq$medianLon > (-135) & dfAllSeq$medianLon < (-30) &
# dfAllSeq$medianLatMap > (-90))
# australasianFilter1 <- which(dfAllSeq$medianLatMap > (-90) &
# dfAllSeq$medianLon < (-135) & dfAllSeq$medianLon > (-180) &
# dfAllSeq$medianLatMap<0)
# australasianFilter2 <- which(dfAllSeq$medianLatMap > (-90) &
# dfAllSeq$medianLon < (180) & dfAllSeq$medianLon > (90) &
# dfAllSeq$medianLatMap < 0 )
# australasianFilter3 <- append(australasianFilter1, australasianFilter2)
# eurasiaAfricaFilter <- append(australasianFilter3, northAmericaFilter)
# eurasiaAfricaFilter2 <- append(southAmericaFilter, eurasiaAfricaFilter)
# dfAllSeq <- dfAllSeq[-eurasiaAfricaFilter2, ]
# Break dfAllSeq down into the various classes.
taxaListComplete <- lapply(unique(dfAllSeq$class_taxID),
function(x) dfAllSeq[dfAllSeq$class_taxID == x,])
# Revise dfRefSeq dataframe to reflect this.
classList <- foreach(i=1:nrow(dfRefSeq)) %do%
unique(taxaListComplete[[i]]$class_name)
classList <- unlist(classList)
# This command will ensure the reference sequence dataframe is in the same order
# as the dfAllSeq dataframe.
dfRefSeq <- dfRefSeq[match(classList, dfRefSeq$taxa), ]
###################
# Section 6: Preliminary Alignment with Muscle and Pairwise Distance Matrix with
# the TN93 Model to Identify and Remove Divergent Sequences
# In this section we want to eliminate sequences that are too divergent in
# pairwise distance by doing an initial alignment and distance matrix.
# Highly divergent sequences can cause major gaps in the alignment and
# inaccurate pairwise distances between sequences.
# As well, the analysis further below compares latitudinally separated BINs that
# are relatively closely related.
# Using the Muscle alignment algorithm and the TN93 model.
# This ensures the final alignment will only be using sequences that are closely
# related to some others in pairwise distance.
# Extraction of Sequences from taxaListComplete for the alignment.
classSequences <- foreach(i=1:nrow(dfRefSeq)) %do%
taxaListComplete[[i]]$nucleotides
# Extraction of BINs from taxalist for the alignment.
classBin <- foreach(i=1:nrow(dfRefSeq)) %do% taxaListComplete[[i]]$bin_uri
# Conversion to DNAStringSet format.
dnaStringSet2 <-
foreach(i=1:nrow(dfRefSeq)) %do% DNAStringSet(classSequences[[i]])
# Naming the DNAStringSet with the appropriate bin_uri's.
for (i in seq(from = 1, to = nrow(dfRefSeq), by = 1)) {
names(dnaStringSet2[[i]]) <- classBin[[i]]
}
# Multiple sequence alignment using muscle package on the dnaStringSet2 list for
# each class.
# Refer here for details on package:
# https://www.bioconductor.org/packages/release/bioc/html/muscle.html
# This could take several minutes to hours depending on the taxa.
# Using default settings of package, the muscle command can detect DNA is being
# used and align accordingly.
# The settings can be modified, if needed, depending upon the size of the
# data set to be aligned and the patterns of sequence divergence in given data
# set.
# ***For larger taxa, it is highly recommended to use a maxiter
# setting of 2 to reduce alignment times.***
alignment2 <- foreach(i=1:length(classBin)) %do%
muscle(dnaStringSet2[[i]], maxiters = 2, diags = TRUE, gapopen = -3000)
# To check each preliminary alignment (each class) and output the preliminary
# alignments to FASTA format, uncomment and run these three commands:
# classFileNames <- foreach(i=1:nrow(dfRefSeq)) %do%
# paste("alignmentPrelim",dfRefSeq$taxa[i],".fas",sep="")
# alignmentPrelimFasta <- foreach(i=1:nrow(dfRefSeq)) %do%
# DNAStringSet(alignment2[[i]])
# foreach(i=1:nrow(dfRefSeq)) %do%
# writeXStringSet(alignmentPrelimFasta[[i]],
# file=classFileNames[[i]], format = "fasta", width = 1500)
# ***FASTA files will show up in working directory of R and be named according
# to the appropriate class being aligned.
# For instance the class Polychaeta would show up as the file
# alignmentPrelimPolychaeta.fas.***
# Conversion to DNAbin format before using pairwise distance matrix.
dnaBin <- foreach(i=1:length(taxaListComplete)) %do% as.DNAbin(alignment2[[i]])
# Details on each model can be found here:
# https://cran.rstudio.com/web/packages/ape/index.html
# We are using the TN93 model for our data, but the model selection can be
# altered.
matrixGeneticDistance <- foreach(i=1:length(taxaListComplete)) %do%
dist.dna(dnaBin[[i]], model = "TN93",
as.matrix = TRUE, pairwise.deletion = TRUE)
# Conversion to dataframe format.
geneticDistanceMatrixList <- foreach(i=1:length(taxaListComplete)) %do%
as.data.frame(matrixGeneticDistance[i])
# Putting it into a stack (each column concatenated into one long column of
# indexes and values)so it can be easily subsetted.
geneticDistanceStackList <- foreach(i=1:length(taxaListComplete)) %do%
stack(geneticDistanceMatrixList[[i]])
# Identification and removal of divergent sequences, a divergent sequence being
# one that is greater than 0.15 in pairwise distance to all other sequences.
# Finding all sequences between 0.15 and 0 distance.
# This command will remove divergent sequences which do not have pairwise
# distances between 0.15 and 0.
divergentSequencesRemove <- foreach(i=1:length(taxaListComplete)) %do%
which(geneticDistanceMatrixList[[i]] <= 0.15 &
geneticDistanceMatrixList[[i]] > 0)
# Subsetting the distance stack by BINs meeting this criteria.
divergentSequencesRemove <- foreach(i=1:length(taxaListComplete)) %do%
geneticDistanceStackList[[i]][c(divergentSequencesRemove[[i]]), ]
# Grabbing all BINs from this stack that meet this criteria and converting to
# character type.
divergentSequencesRemove <- foreach(i=1:length(taxaListComplete)) %do%
as.character(unique(divergentSequencesRemove[[i]]$ind))
###################
# Section 7: Finalized Alignment with Addition of Reference Sequence
# In this section we can perform the final alignment after divergent sequences
# have been removed and the addition of a reference sequence.
# Subset taxalist by BINs meeting 0.15 criteria so no divergent sequences are
# present.
taxaListComplete <- foreach(i=1:length(taxaListComplete)) %do%
subset(taxaListComplete[[i]], taxaListComplete[[i]]$bin_uri %in%
divergentSequencesRemove[[i]])
# Extract sequences and bin_uri from each class.
classBin <- foreach(i=1:nrow(dfRefSeq)) %do% taxaListComplete[[i]]$bin_uri
classSequences <-
foreach(i=1:nrow(dfRefSeq)) %do% taxaListComplete[[i]]$nucleotides
classSequencesNames <- classBin
# Take our reference sequences.
alignmentRef <- as.character(dfRefSeq$nucleotides)
dfRefSeq$reference <- "reference"
# Name our reference as reference for each class so it can be identified as such
# in the alignment.
alignmentRefNames <- dfRefSeq$reference
# Merge our reference sequences with each of our class sequences.
alignmentSequencesPlusRef <- foreach(i=1:nrow(dfRefSeq)) %do%
append(classSequences[[i]], alignmentRef[[i]])
# Merge the names together.
alignmentNames <- foreach(i=1:nrow(dfRefSeq)) %do%
append(classSequencesNames[[i]], alignmentRefNames[[i]])
# Converting all sequences in dfAllSeq plus reference to DNAStringSet format,
# the format required for the alignment.
dnaStringSet3 <- foreach(i=1:nrow(dfRefSeq)) %do%
DNAStringSet(alignmentSequencesPlusRef[[i]])
# Name the DNAStringSet List with the appropriate BIN uri's.
for (i in seq(from=1, to=nrow(dfRefSeq), by = 1)){
names(dnaStringSet3[[i]]) <- alignmentNames[[i]]
}
# Multiple sequence alignment using muscle package on each element of the
# dnaStringSet2 list for each class.
# Refer here for details on package:
# https://www.bioconductor.org/packages/release/bioc/html/muscle.html
# This could take several minutes to hours depending on the taxa.
# Using default parameters, muscle will detect DNA is being used and will
# align accordingly.
# ***For larger taxa, it is highly recommended to use a maxiter
# setting of 2 to reduce alignment times.***
alignmentFinal <- foreach(i=1:length(classBin)) %do%
muscle(dnaStringSet3[[i]], maxiters = 2, diags = TRUE, gapopen = -3000)
# To check each final alignment (each class) and output the final alignments to
# FASTA format, uncomment and run these three commands:
# classFileNames2 <- foreach(i=1:nrow(dfRefSeq)) %do%
# paste("alignmentFinal", dfRefSeq$taxa[i], ".fas", sep="")
# alignmentFinalFasta <- foreach(i=1:nrow(dfRefSeq)) %do%
# DNAStringSet(alignmentFinal[[i]])
# foreach(i=1:nrow(dfRefSeq)) %do%
# writeXStringSet(alignmentFinalFasta[[i]], file=classFileNames2[[i]],
# format="fasta", width=1500)
# ***FASTA files will show up in working directory of R and be named according
# to the appropriate class being aligned. For instance the class Polychaeta
# would show up as the file alignmentFinalPolychaeta.fas.***
# Removal of unecessary large variables to minimize workspace size and
# free up working memory
rm(geneticDistanceStackList)
rm(geneticDistanceMatrixList)
rm(matrixGeneticDistance)
rm(geneticDistanceCentroid)
rm(dfInitial)
rm(endNGap)
rm(startNGap)
rm(internalNGap)
rm(binList)
gc()
#***Save workspace before proceeding further***
###################
# Section 8: Sequence Trimming of Finalized Alignment According to the Reference
# Sequence
# In this section, the final alignment generated is now trimmed according to the
# position of the reference in the alignment. This step ensures that a
# consistent genetic region is used for the subsequent distance calculations.
# For trimming of the sequences we have to determine where in the alignment the
# reference sequence is and determine its start and stop positions relative to
# the other sequences. We can then use these positions to trim the rest of the
# sequences in the alignment.
refSeqPos <- foreach(i=1:nrow(dfRefSeq)) %do%
which(alignmentFinal[[i]]@unmasked@ranges@NAMES == "reference")
refSeqPos <- foreach(i=1:nrow(dfRefSeq)) %do%
alignmentFinal[[i]]@unmasked[refSeqPos[[i]]]
# Finding start position by searching for the first nucleotide position of the
# reference sequence.
refSeqPosStart <- foreach(i=1:nrow(dfRefSeq)) %do%
regexpr("[ACTG]", refSeqPos[[i]])
refSeqPosStart <- as.numeric(refSeqPosStart)
# Finding last nucleotide position of the reference sequence.
refSeqPosEnd <- foreach(i=1:nrow(dfRefSeq)) %do%
(nchar(dfRefSeq$nucleotides[i]) + refSeqPosStart[i])
refSeqPosEnd <- as.numeric(refSeqPosEnd)
# Then we can substr the alignment by these positions to effectively trim the
# alignment.
alignmentFinalTrim <- foreach(i=1:nrow(dfRefSeq)) %do%
substr(alignmentFinal[[i]], refSeqPosStart[i] + 1, refSeqPosEnd[i])
# To check each final trimmed alignment (each class) and output the final
# trimmed alignments to FASTA format, uncomment and run these three commands:
# classFileNames3 <- foreach(i=1:nrow(dfRefSeq)) %do%
# paste("alignmentFinalTrim", dfRefSeq$taxa[i], ".fas", sep="")
# alignmentFinalTrimFasta <- foreach(i=1:nrow(dfRefSeq)) %do%
# DNAStringSet(alignmentFinalTrim[[i]])
# foreach(i=1:nrow(dfRefSeq)) %do%
# writeXStringSet(alignmentFinalTrimFasta[[i]], file=classFileNames3[[i]],
# format="fasta", width=658)
# ***FASTA files will show up in working directory of R and be named according
# to the appropriate class being aligned. For instance the class Polychaeta
# would show up as the file alignmentFinalTrimPolychaeta.fas.***
# Again, convert to dnaStringSet format.
dnaStringSet4 <- foreach(i=1:nrow(dfRefSeq)) %do%
DNAStringSet(alignmentFinalTrim[[i]])
# Establish where the reference sequence is in each alignment for removal of
# the reference from further analysis.
refSeqRemove <- foreach(i=1:nrow(dfRefSeq)) %do%
which(dnaStringSet4[[i]]@ranges@NAMES == "reference")
# We also have to check dnaStringSet4 for alignments that only contain a
# reference sequence and remove these.
alignmentCheck <- foreach(i=1:nrow(dfRefSeq)) %do%
which(length(dnaStringSet4[[i]]) == 1)
alignmentCheck <- which(alignmentCheck > 0)
# Subset dnaStringSet4, taxalistcomplete, alignmentFinalTrim and refSeqRemove by
# the alignment check.
if (length(alignmentCheck > 0)) {
dnaStringSet4 <- dnaStringSet4[-alignmentCheck]
taxaListComplete <- taxaListComplete[-alignmentCheck]
alignmentFinalTrim <- alignmentFinalTrim[-alignmentCheck]
refSeqRemove <- refSeqRemove[-alignmentCheck]
}
# Removal of references from both dnaStringSet4 and alignmentFinalTrim.
dnaStringSet4 <- foreach(i=1:length(taxaListComplete)) %do%
subset(dnaStringSet4[[i]][-refSeqRemove[[i]]])
alignmentFinalTrim <- foreach(i=1:length(taxaListComplete)) %do%
alignmentFinalTrim[[i]][-refSeqRemove[[i]]]
###################
# Section 9: Pairwise Distance Determination with the TN93 Model of Finalized
# Alignment
# In this section we do the final pairwise distance determination step using the
# TN93 model, before initial pairings can be generated.
# Conversion to DNAbin format before using genetic distance matrix.
dnaBin2 <- foreach(i=1:length(taxaListComplete)) %do%
as.DNAbin(dnaStringSet4[[i]])
# Once again using the TN93 model for pairwise distance computation, this time
# from the 3rd alignment after divergent sequences have been removed and after
# trimming according to the reference sequences.
matrixGeneticDistance2 <- foreach(i=1:length(taxaListComplete)) %do%
dist.dna(dnaBin2[[i]], model = "TN93", as.matrix = TRUE,
pairwise.deletion = TRUE)
# Convert to dataframe format.
geneticDistanceMatrixList2 <- foreach(i=1:length(taxaListComplete)) %do%
as.data.frame(matrixGeneticDistance2[i])
# Putting it into a stack (each column concatenated into one long column of
# indexes and values) so it can be easily subsetted.
geneticDistanceStackList2 <- foreach(i=1:length(taxaListComplete)) %do%
stack(geneticDistanceMatrixList2[[i]])
###################
# Section 10: Finding Appropriate Pairings According to Genetic Distance Criteria
# and Latitude Criteria
# In this section, we establish preliminary pairings of BINs showing up to a
# maximum of 0.15 genetic divergence and 20 degrees latitude difference
# and divide preliminary pairings into distinct lineages.
# These values can easily be edited to add more or less stringency to the
# matches. Will produce lists with indexes (BINs, row and column names) of each
# match according to the maximum genetic distance criterion of 0.15.
pairingResultCandidates <- foreach(i=1:length(taxaListComplete)) %do%
which(geneticDistanceMatrixList2[[i]] <= 0.15)
# Generate a matrix of latitude differences between bins.