-
Notifications
You must be signed in to change notification settings - Fork 0
/
03_Mp_PopulationGenomics_V3.Rmd
1697 lines (1379 loc) · 56.9 KB
/
03_Mp_PopulationGenomics_V3.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: "03_Mp_PopulationGenomicsAnalysis"
author: "Viviana Ortiz"
date: "10/19/2021"
output: html_document
editor_options:
chunk_output_type: console
---
```{r eval = TRUE, echo = FALSE, results = 'hide'}
rm(list=ls(all=TRUE)) #Removes all variables in the global environment
Sys.time() # prints out the time and date you ran the code
options(scipen = 999) # stops anything from being in scientific notation
```
#Install packges and load libraries
```{r}
ipak <- function( pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[,"Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
packages <- c("poppr", "vcfR", "ape", "mmod", "pegas", "ggplot2", "adegenet", "seqinr",
"magrittr", "plink", "reshape2", "agricolae", "plotly", "reshape2", "cowplot")
ipak(packages)
```
#Creating a genlight object using the filtered vcf
```{r}
vcf95filt <- "051920_vcfs/051920_mp39_95_SNP_DPquant595_DP4_0miss_MQ60_MAF002.vcf.gz"
vcf <- read.vcfR(vcf95filt,
convertNA = TRUE, verbose = TRUE)
vcf #95 samples, 86 CHROMs, 77,465 variants
#Genligth object only supports biallelic SNPs, 484 loci with more than two alleles will be omitted from the genlight object
gl.mp <- vcfR2genlight(vcf[is.polymorphic(vcf, na.omit = T)])
gl.mp #95 genotypes, 76,981 binary SNPs, size: 8.1 Mb
#Setting the ploidy
ploidy(gl.mp) <- as.integer(1)
```
#Including metadata to assign populations
```{r}
#Setting the populations
folder <- "isolates_database/"
data <- read.csv(paste0(folder, "2021_95mp_vcforder_climKG2018_1km.csv"), na.strings = ("NA")) #metadata
data$isolate <- as.factor(data$isolate)
data$isolate_vcf <- as.factor(data$isolate_vcf)
data$Location <- as.factor(data$Location)
data$Country <- as.factor(data$Country)
data$State_Department <- as.factor(data$State_Department)
data$Region <- as.factor(data$Region)
data$region_noaa<- as.factor(data$region_noaa)
data$region_IPCC<- as.factor(data$region_IPCC)
data$Host <- as.factor(data$Host)
data$Municipality <- as.factor(data$Municipality)
data$field <-as.factor(data$field)
#Add strata to a genlight object
#strata: a data frame containing different levels of population definition. (For methods, see addStrata and setPop)
strata(gl.mp) <- data.frame(data)
gl.mp
strata(gl.mp)
head(strata(gl.mp))
tail(strata(gl.mp))
colnames(strata(gl.mp))
nameStrata(gl.mp) <- ~vcf_order/Isolate/Isolate_vcf/label_raxml_ng/location_full/Longitude/Latitude/Region/Region_noaa/Region_IPCCC/Country/Location/State_Department/Host/municipality_resolution/Municipality/Field/Clade/Subclade/Genetic_Cluster/source/comments/ClimZ_code/ClimZ/description/RGB
head(strata(gl.mp))
```
#Setting the strata
```{r}
#####Here is how to set the population using strata, after defining the strata, you use set<- for setting populations
#Next, we analyze the data according to Country, Clade, and/or Genetic CLuster:
#Clade/subclade
setPop(gl.mp) <- ~Clade/Subclade
gl.mp
#Subclade
setPop(gl.mp) <- ~Subclade
gl.mp
#Country
setPop(gl.mp) <- ~Country
gl.mp
#Country/State
setPop(gl.mp) <- ~Country/State_Department
gl.mp
#Country/State/Municipality
setPop(gl.mp) <- ~Country/State_Department/Municipality
gl.mp
#Genetic_Cluster
setPop(gl.mp) <- ~Genetic_Cluster
gl.mp
pop.clade <- as.factor(data$clade)
pop.subclade <- as.factor(data$subclade)
pop.country <- as.factor(data$Country)
pop.cluster <- as.factor(data$Genetic_Cluster)
```
# 1.Principal components analysis
```{r}
#Colors
library(adegenet)
library(scales)
library(RColorBrewer)
#PCA
#Set population to Genetic_Cluster
setPop(gl.mp) <- ~Genetic_Cluster
gl.mp
mp.pca <- glPca(gl.mp, nf = 4) #nf = NULL if want to select the number of axes to be retained
barplot(100*mp.pca$eig/sum(mp.pca$eig), col = heat.colors(50), main="PCA Eigenvalues")#looks like 2 or 3 explain most of the variance
title(ylab="Percent of variance\nexplained", line = 2)
title(xlab="Eigenvalues", line = 1)
#To see variance explained
var.expl <- 100*mp.pca$eig/sum(mp.pca$eig)
var.expl
mp.pca.scores <- as.data.frame(mp.pca$scores)
mp.pca.scores$pop <- pop(gl.mp)
#see order to assign colors
levels(mp.pca.scores$pop)
#[1] "US2" "US1A" "COLPR2" "US1B" "COLPR1"
#colors
subclade.col5 <- c("#F06C45CC", "#FDA440CC", "#1F78B4CC","#569EA4", "#6A3D9ACC")
show_col(subclade.col5)
#ordered colors
subclade.col5 <- c("#1F78B4CC","#569EA4", "#6A3D9ACC", "#F06C45CC", "#FDA440CC")
show_col(subclade.col5)
p <- ggplot(mp.pca.scores, aes(x=PC1, y=PC2, colour=pop, fill=pop))
#p <- ggplot(mp.pca.scores, aes(x=PC1, y=PC3, colour=pop))
#p <- ggplot(mp.pca.scores, aes(x=PC2, y=PC3, colour=pop))
p <- p + geom_point(shape=21, colour="black", size=4) + theme_classic()
p
p <- p + scale_colour_manual(values = subclade.col5, aesthetics = c("fill", "colour"), na.value = "grey90",
limits = c("US1A", "US1B", "US2", "COLPR1","COLPR2"),
name="Genetic Cluster")
p
p <- p + stat_ellipse(level = 0.95, size = 0.6)
p
p <- p + labs(x= "PC1 (50.6%)", y = "PC2 (15.5%)")#vcf 77k
p
p <- p + geom_hline(yintercept = 0, size=0.1)
p <- p + geom_vline(xintercept = 0, size=0.1)
p <- p + theme(panel.border = element_rect(fill = NA))
p
p <- p + theme(legend.box.background = element_rect(), legend.box.margin = margin())
p
ggsave(plot = p, "./202111_figures/112121_pca_4.png", dpi = 600, units = "in", height = 4, width = 5)
#or points with alpha and no border
p <- ggplot(mp.pca.scores, aes(x=PC1, y=PC2, colour=pop))
#p <- ggplot(mp.pca.scores, aes(x=PC1, y=PC3, colour=pop))
#p <- ggplot(mp.pca.scores, aes(x=PC2, y=PC3, colour=pop))
p <- p + geom_point(size=4, alpha = 0.6) + theme_classic()
p
p <- p + scale_colour_manual(values = subclade.col5, aesthetics = "colour", na.value = "grey90",
limits = c("US1A", "US1B", "US2", "COLPR1","COLPR2"),
name="Genetic Cluster",)
p
p <- p + stat_ellipse(level = 0.95, size = 0.6)
p
p <- p + labs(x= "PC1 (50.6%)", y = "PC2 (15.5%)")#vcf 77k
p
p <- p + geom_hline(yintercept = 0, size=0.1)
p <- p + geom_vline(xintercept = 0, size=0.1)
p
ggsave(plot = p, "./202111_figures/112121_pca_3.png", dpi = 600, units = "in", height = 4, width = 5)
```
# 1.1 DAPC adegenet using find clusters grouping (K-means)
```{r}
#Set population to Genetic_Cluster
setPop(gl.mp) <- ~Genetic_Cluster
gl.mp
grp_mp <- find.clusters(gl.mp, max.n.clust = 10)
#20 PCs, 5 clusters
dapc1 <- dapc(gl.mp, grp_mp$grp)
#15 PCs retained, 100 das retained
dapc1
scatter(dapc1)
scatter(dapc1, scree.da=FALSE, leg=F)
scatter(dapc1, scree.da=FALSE, bg="white", pch=17-21, cstar=0, solid=0.4, cex=3,clab=0, leg=TRUE, txt.leg=paste("Cluster",1:7))
compoplot(dapc1, posi="bottomright", txt.leg=paste("Cluster", 1:4), lab="", ncol=1, xlab="individuals", col=funky(10))
```
#K-means clustering from pop genomics in R Grunwald
```{r}
library(adegenet)
maxK <- 7
myMat <- matrix(nrow=7, ncol=maxK)
colnames(myMat) <- 1:ncol(myMat)
for(i in 1:nrow(myMat)){
grp <- find.clusters(gl.mp, n.pca = 40, choose.n.clust = FALSE, max.n.clust = maxK)
myMat[i,] <- grp$Kstat
}
#Visualizing K-mean clustering
library(ggplot2)
library(reshape2)
my_df <- melt(myMat)
colnames(my_df)[1:3] <- c("Group", "K", "BIC")
my_df$K <- as.factor(my_df$K)
head(my_df)
#plot BIC
p1 <- ggplot(my_df, aes(x = K, y = BIC))
p1 <- p1 + geom_boxplot()
p1 <- p1 + theme_bw()
p1 <- p1 + xlab("Number of groups (K)")
p1
#DAPC
my_k <- 4:7
my_k <- 5
#my_k <- 7
grp_l <- vector(mode = "list", length = length(my_k))
dapc_l <- vector(mode = "list", length = length(my_k))
for(i in 1:length(dapc_l)){
set.seed(9)
grp_l[[i]] <- find.clusters(gl.mp, n.pca = 40, n.clust = my_k[i])
dapc_l[[i]] <- dapc(gl.mp, pop = grp_l[[i]]$grp, n.pca = 40, n.da = my_k[i])
# dapc_l[[i]] <- dapc(gl.mp, pop = grp_l[[i]]$grp, n.pca = 3, n.da = 2)
}
#DAPC scatterplot
my_df <- as.data.frame(dapc_l[[ length(dapc_l) ]]$ind.coord)
my_df$Group <- dapc_l[[ length(dapc_l) ]]$grp
head(my_df)
my_pal <- RColorBrewer::brewer.pal(n=8, name = "Dark2")
p2 <- ggplot(my_df, aes(x = LD1, y = LD2, color = Group, fill = Group))
p2 <- p2 + geom_point(size = 4, shape = 21)
p2 <- p2 + theme_bw()
p2 <- p2 + scale_color_manual(values=c(my_pal))
p2 <- p2 + scale_fill_manual(values=c(paste(my_pal, "66", sep = "")))
p2
#DAPC barplot
#barplots of the posterior probabilities of group assignment for each sample. Here we’ll use “facets” to separate the different values of K
#Long format dataframe
tmp <- as.data.frame(dapc_l[[1]]$posterior)
tmp$K <- my_k[1]
tmp$Isolate <- rownames(tmp)
tmp <- melt(tmp, id = c("Isolate", "K"))
names(tmp)[3:4] <- c("Group", "Posterior")
tmp$Population <- pop(gl.mp)
my_df <- tmp
for(i in 2:length(dapc_l)){
tmp <- as.data.frame(dapc_l[[i]]$posterior)
tmp$K <- my_k[i]
tmp$Isolate <- rownames(tmp)
tmp <- melt(tmp, id = c("Isolate", "K"))
names(tmp)[3:4] <- c("Group", "Posterior")
tmp$Population <- pop(gl.mp)
my_df <- rbind(my_df, tmp)
}
#PLot de DAPC barplot (compoplot)
grp.labs <- paste("K =", my_k)
names(grp.labs) <- my_k
p3 <- ggplot(my_df, aes(x = Isolate, y = Posterior, fill = Group))
p3 <- p3 + geom_bar(stat = "identity")
p3 <- p3 + facet_grid(K ~ Population, scales = "free_x", space = "free",
labeller = labeller(K = grp.labs))
p3 <- p3 + theme_bw()
p3 <- p3 + ylab("Posterior membership probability")
p3 <- p3 + theme(legend.position='none')
#p3 <- p3 + scale_color_brewer(palette="Dark2")
p3 <- p3 + scale_fill_manual(values = subclade.col5, na.value = "grey90",
limits = c("1", "3", "5", "2","4"),
name="Genetic Cluster")
p3 <- p3 + theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 8))
p3
ggsave(plot = p3, "./202111_figures/112121033121_kmeans5_dapc_compoplot_xsmall.png", dpi = 600, units = "in", height = 4, width = 10)
```
# 2.Genetic diversity and differentiation
Raw data, clone correction has not been applied yet here
```{r}
#Genetic diversity individual
library(poppr)
mpdiv <- diversity_stats(gl.mp)
mpdiv
#Genetic differentiation at population level
#1.Using Country
gen.diff.country <- as.data.frame(genetic_diff(vcf, pop.country))
head(gen.diff.country)
# Mean value of each metric
colMeans(gen.diff.country[,c(3:ncol(gen.diff.country))], na.rm = T)
#2.Using Clade
gen.diff.clade <- as.data.frame(genetic_diff(vcf, pop.clade))
head(gen.diff.clade)
# Mean value of each metric
colMeans(gen.diff.clade[,c(3:ncol(gen.diff.clade))], na.rm = T)
#3.Using genetic cluster
gen.diff.cluster <- as.data.frame(genetic_diff(vcf, pop.cluster))
head(gen.diff.cluster)
# Mean value of each metric
colMeans(gen.diff.cluster[,c(3:ncol(gen.diff.cluster))], na.rm = T)
```
# 2.1 Genetic differentiation at different population levels using genind object
Create genind object for clone-corrected analysis
```{r}
#Calculating genetic differentiation using "poppr" function which takes a genind object
#Convert vcf to genind
gi.mp <- vcfR2genind(vcf[is.polymorphic(vcf, na.omit = T)])
gi.mp
gi.mp.bial <-
#Setting the ploidy
ploidy(gi.mp) <- as.integer(1)
#Seting the strata for genind object to the same as for genlight object
strata(gi.mp) <- strata(gl.mp)
strata(gi.mp)
#Setting the population
setPop(gi.mp) <- ~Genetic_Cluster
gi.mp
gi.mp@pop
```
```{r}
#Clone corrected genind
gi.mp.cc <- clonecorrect(gi.mp, strata = ~Genetic_Cluster, combine = T) #combine T: the strata will be combined to create a new population for the clone-corrected genind or genclone object
#After clone correction using genetic cluster
#77 individuals; 77,465 loci; 155,395 alleles; size: 92.8 Mb
gi.mp.cchier <- clonecorrect(gi.mp, strata = ~Clade/Genetic_Cluster, combine = T) #combine T: the strata will be combined to create a new population for the clone-corrected genind or genclone object
gi.mp.cchier
gi.mp.cchier@pop
#79 individuals; 77,465 loci; 155,395 alleles; size: 94 Mb
#Remove isolates with NA in strata (IN129-4 and Mph40) which were not assigned to any genetic cluster
gi.mp.cc.nona <- gi.mp.cc[!is.na(strata(gi.mp.cc)$Genetic_Cluster) , ]
gi.mp.cc.nona
gi.mp.cc.nona@pop
####Country
##Median pairwise distance by Country
#Using clone corrected genind
gi.mp.cchier
setPop(gi.mp.cchier) <- ~Country
gi.mp.cchier@pop
gi.uscou <- popsub(gi.mp.cchier , sublist = "US")
gi.col <- popsub(gi.mp.cchier , sublist = "COL")
gi.pr <- popsub(gi.mp.cchier , sublist = "PR")
#Median pairwise genetic distance within countries
#US
usdistcou <- bitwise.dist(gi.uscou)
#usdist
median(usdistcou)
#COL
coldist <- bitwise.dist(gi.col)
#coldist
median(coldist)
#PR
prdist <- bitwise.dist(gi.pr)
#prdist
median(prdist)
#Expected heterozygosity (Hexp) with Hs function (adegenet)
#Hs for each Country
Hs.country <- Hs(gi.mp.cchier)
Hs.country
# US COL PR
#0.1035387 0.2633720 0.1631632
#Test difference in expected heterozygosity (Gene diversity)
#Pairwise US-Colombia
us_co_Ht <- Hs.test(gi.mp.cchier[pop="US"], gi.mp.cchier[pop="COL"], n.sim=499)
us_co_Ht
plot(us_co_Ht)
#Pairwise US-PR
us_pr_Ht <- Hs.test(gi.mp.cchier[pop="US"], gi.mp.cchier[pop="PR"], n.sim=499)
us_pr_Ht
plot(us_pr_Ht)
#Pairwise CO-PR
co_pr_Ht <- Hs.test(gi.mp.cchier[pop="COL"], gi.mp.cchier[pop="PR"], n.sim=499)
co_pr_Ht
plot(co_pr_Ht)
##Hexp and other statsitics with poppr
h.uscou <- locus_table(gi.uscou)
h.uscou
####Clades
##Median pairwise distance by Clades
#Using NOT clone corrected genind
# gi.mp
# #Subset genind to Clades
# popNames(gi.mp)
# setPop(gi.mp) <- ~Clade #Setting the population
# gi.mp
# gi.mp@pop
# gi.us <- popsub(gi.mp, sublist = "US")
# gi.colpr <- popsub(gi.mp, sublist = "COLPR")
#Using clone corrected genind
gi.mp.cchier
setPop(gi.mp.cchier) <- ~Clade
gi.mp.cchier@pop
gi.us <- popsub(gi.mp.cchier , sublist = "US")
gi.colpr <- popsub(gi.mp.cchier , sublist = "COLPR")
#Median pairwise genetic distance within clades
#US
usdist <- bitwise.dist(gi.us)
#usdist
median(usdist)
mean(usdist)
#COLPR
colprdist <- bitwise.dist(gi.colpr)
#colprdist
median(colprdist)
#Expected heterozygosity Hs (adegenet)
#Hs for each clade
Hs(gi.mp.cchier) #clone-corrected at 79 MLGs
# US COLPR
#0.06839165 0.23628203
Hs(gc.mp)# clone-corrected at 34MLL
# US COLPR
#0.05734503 0.23628203
#Test difference in expected heterozygosity (Gene diversity)
#Pairwise
us_colprHt <- Hs.test(gi.mp.cchier[pop="US"], gi.mp.cchier[pop="COLPR"], n.sim=499)
us_colprHt
plot(us_colprHt)
###Genetic Clusters
#Subset genind to Genetic Cluster
# gi.mp
# setPop(gi.mp) <- ~Genetic_Cluster
# popNames(gi.mp)
# gi.us1a <- popsub(gi.mp, sublist = "US1A")
# gi.us1b <- popsub(gi.mp, sublist = "US1B")
# gi.us2 <- popsub(gi.mp, sublist = "US2")
# gi.colpr1 <- popsub(gi.mp, sublist = "COLPR1")
# gi.colpr2 <- popsub(gi.mp, sublist = "COLPR2")
#Using clone corrected genind
gi.mp.cchier #Using clone corrected genind
setPop(gi.mp.cchier) <- ~Genetic_Cluster
popNames(gi.mp.cchier)
gi.us1a <- popsub(gi.mp.cchier, sublist = "US1A")
gi.us1b <- popsub(gi.mp.cchier, sublist = "US1B")
gi.us2 <- popsub(gi.mp.cchier, sublist = "US2")
gi.colpr1 <- popsub(gi.mp.cchier, sublist = "COLPR1")
gi.colpr2 <- popsub(gi.mp.cchier, sublist = "COLPR2")
#Median pairwise genetic distance within genetic clusters
#US1A
us1adist <- bitwise.dist(gi.us1a)
#us1adist
median(us1adist)
#US1B
us1bdist <- bitwise.dist(gi.us1b)
#us1bdist
median(us1bdist)
#US2
us2dist <- bitwise.dist(gi.us2)
#us2dist
median(us2dist)
#COLPR1
colpr1dist <- bitwise.dist(gi.colpr1)
#colpr1dist
median(colpr1dist)
#COLPR2
colpr2dist <- bitwise.dist(gi.colpr2)
#colpr2dist
median(colpr2dist)
#Expected heterozygosity Hs (adegenet)
#Hs for each cluster
Hs(gi.mp.cchier)
#Test difference in expected heterozygosity (Gene diversity)
#Pairwise
us1a_1bHt <- Hs.test(gi.mp.cchier[pop="US1A"], gi.mp.cchier[pop="US1B"], n.sim=499)
us1a_1bHt
plot(us1a_1bHt)
#Global GST using clone-corrected genind
#Clades
diff.usclade <- diff_stats(gi.us) # this function calculates overall Nei's Gst, Hedrick's Gst and of the dataset
diff.colprclade <- diff_stats(gi.colpr)
```
# 3.Pairwise genetic differentiation
```{r}
#Pairwise genetic difference
#Clades US and COLPR
gen.dif.clade.pair <- pairwise_genetic_diff(vcf, pop.clade, method = "nei")
dim(gen.dif.clade.pair)
head(gen.dif.clade.pair)
colMeans(gen.dif.clade.pair[c(4:ncol(gen.dif.clade.pair))], na.rm = T)
#Gst_COLPR_US Gprimest_COLPR_US
# 0.3246086 0.4137490
#Genetic Clusters all
gen.dif.gc.pair <- pairwise_genetic_diff(vcf, pop.cluster, method = "nei")
dim(gen.dif.gc.pair)
head(gen.dif.gc.pair)
colMeans(gen.dif.gc.pair[c(4:ncol(gen.dif.gc.pair))], na.rm = T)
us.gen.dif.subcl.pair <- pairwise_genetic_diff(us.vcf, pop.ussubclade2, method = "nei")
dim(gen.dif.subcl.pair)
head(gen.dif.subcl.pair)
colMeans(gen.dif.subcl.pair[c(4:45)], na.rm = T)
hist(gen.dif.subcl.pair[5], xlab = expression(italic("G'"["ST"])), col='skyblue', breaks = seq(0, 1, by = 0.01))
#problem with NaN, it looks it may be a memory issue
```
# 3.1 Pairwise genetic differentiation using mmod package and genind object
https://www.molecularecologist.com/2011/03/02/should-i-use-fst-gst-or-d-2/
Clone corrected
```{r}
#Pairwise genetic differentiation using mmod package and genind object
library(mmod)
#vignette("mmod-demo", package="mmod")
#Clades
gi.mp.cchier
setPop(gi.mp.cchier) <- ~Clade
popNames(gi.mp.cchier)
pair.diff.clades <- pairwise_Gst_Nei(gi.mp.cchier, linearized = FALSE) # Calculates pairwise Gst. If linearized = TRUE, it calculates 1/(1- Gst)
# US
#COLPR 0.4453554
Gst_Hedrick(gi.mp.cc.co)
pairgstHed.co <- pairwise_Gst_Hedrick(gi.mp.cc.co, linearized = FALSE)# Calculates pairwise Gst. If linearized = TRUE, it calculates 1/(1- Gst')
#Genetic clusters
##79 MLGs
setPop(gi.mp.cchier) <- ~Genetic_Cluster
popNames(gi.mp.cchier)
pair.diff.gc <- pairwise_Gst_Nei(gi.mp.cchier, linearized = FALSE) # Calculates pairwise Gst. If linearized = TRUE, it calculates 1/(1- Gst)
# US2 US1A COLPR2 US1B
#US1A 0.9918494
#COLPR2 0.6948396 0.6833509
#US1B 0.6385817 0.5431124 0.5865585
#COLPR1 0.8114427 0.8038622 0.5033223 0.6925585
#Test significance in GST
bs <- chao_bootstrap(gi.mp.cchier, nreps = 100)
summarise_bootstrap(bs, Gst_Nei) # for Nei's Gst
##34 MLGs, pretty much same results as with 79 MLGs
setPop(gc.mp) <- ~Genetic_Cluster
popNames(gc.mp)
pair.diff.gcmll <- pairwise_Gst_Nei(gc.mp, linearized = FALSE) # Calculates pairwise Gst. If linearized = TRUE, it calculates 1/(1- Gst)
# US2 US1A COLPR2 US1B
#US1A 0.9919670
#COLPR2 0.6948396 0.6840234
#US1B 0.6385817 0.5440726 0.5865585
#COLPR1 0.8114427 0.8043152 0.5033223 0.6925585
```
# 4. Multilocus genotype analysis using snpclone object
https://grunwaldlab.github.io/poppr/articles/mlg.html
This will make sure that you can have mutlilocus genotype definitions travel with your data. From here, you can:
Define multilocus lineages with mlg.filter()
Calculate sliding windows of the standardized index of association with win.ia()
Randomly sample loci for the standardized index of association with samp.ia()
Construct minimum spanning networks with poppr.msn()
Create boostrapped dendrograms with aboot()
# 4.1 Defining multilocus lineages with mlg.filter() and a distance threshold
```{r}
#1.Converting genind to genclone
setPop(gi.mp) <- ~Clade #Set population
gc.mp <- as.genclone(gi.mp) #genclone
gc.mp #79 original multilocus genotypes
gc.mp@mlg
gc.mp@pop
```
```{r}
# or Converting genlight to snpclone: best for many loci and the difference is using only biallellic loci
#snpclone
#This snpclone will have the strata and population I set to the genlight object
sc.mp <- as.snpclone(gl.mp) #snpclone
sc.mp #75 original multilocus genotypes
sc.mp@pop
```
## 4.1.1 Explore MLGs and define a threshold for MLLs
This is exploratory, don't need to run this chunck every time
#Genclone
```{r}
#2. Explore orginal MLGs
#Plot thresholds
#thresh <- filter_stats(gc.mp, distance = bitwise.dist, plot = TRUE)
#p <- last_plot(); p + facet_wrap(~population, ncol = 1, scales = "free_y")
#p
#mll() to display and switch between different multilocus genotypes/lineages
head(mll(gc.mp, "original"), 20) # Showing the definitions for the first 20 samples
#snpclone
head(mll(sc.mp, "original"), 20)
#Naïve (“original”)
#This is the default way poppr calculates multilocus genotypes
mll(gc.mp) <- "original"
gc.mp #79 original multilocus genotypes
head(mll(gc.mp, "original"), 20) # Showing the definitions for the first 20 samples
mll(gc.mp, "original") # all samples mlgs
#Default MLG: all alleles must match to make a unique multilocus genotype
#Default MLG
mlg_gc <- mlg.table(gc.mp, strata = ~Clade/Genetic_Cluster)
ggsave("mlg_clade_gc_hier.pdf")
# See which individuals belong to each MLG
mlgid <- mlg.id(gc.mp)
mlgid["59"] # "M_15_12_R1" "W_MISO2_4_10_R1"
# Let's say we want to visualize the multilocus genotype distribution for each cluster
us1atab <- mlg.table(gc.mp, sublist = c("US1A"), plot=TRUE)
ncol(us1atab) #MLGs in us1a, the columns of the table from mlg.table are equal to the number of MLGs
us1btab <- mlg.table(gc.mp, sublist = c("US1B"), plot=TRUE)
ncol(us1btab)
us2tab <- mlg.table(gc.mp, sublist = c("US2"), plot=TRUE)
ncol(us2tab)
colpr1tab <- mlg.table(gc.mp, sublist = c("COLPR1"), plot=TRUE)
ncol(colpr1tab)
colpr2tab <- mlg.table(gc.mp, sublist = c("COLPR2"), plot=TRUE)
ncol(colpr2tab)
# Show which genotypes exist accross populations in the entire dataset.
crossmlg <- mlg.crosspop(gc.mp, quiet = FALSE)
#No multilocus genotypes were detected across populations
#Country
#Default MLG
#Set again to the original (default)
mll(gc.mp) <- "original"
mll(gc.mp) # original
gc.mp
mlg_co <- mlg.table(gc.mp, strata = ~Country)
# See which individuals belong to each MLG
mlgid <- mlg.id(gc.mp)
mlgid
ustab <- mlg.table(gc.mp, strata = ~Country, sublist = c("US"), plot=TRUE)
ncol(ustab) #MLGs in us 54, the columns of the table from mlg.table are equal to the number of MLGs
coltab <- mlg.table(gc.mp, strata = ~Country, sublist = c("COL"), plot=TRUE)
ncol(coltab) #MLGs in colombia 20
prtab <- mlg.table(gc.mp, strata = ~Country, sublist = c("PR"), plot=TRUE)
ncol(prtab) #MLGs in puerto rico 5
#3.Apply a treshold for defining MLLs
#Filtered (“contracted”)
#We can utilize genetic distance, which will allow us to collapse multilocus genotypes that are under a specific distance threshold.
#Calculate raw genetic distance with bitwise.dist(), this distance is in %, see ?bitwise.dist()
#Fraction of different alleles in percentage (this is actually proportion 0 to 1):
gc.dist <- bitwise.dist(gc.mp)
gc.dist
hist(gc.dist, breaks = 100000)
median(gc.dist)
#Number of allelic differences. percent = FALSE will return the distance represented as integers from 1 to n where n is the number of loci
gc.dist.nl <- bitwise.dist(gc.mp, percent = F)
gc.dist.nl
hist(gc.dist.nl, breaks = 10000)
median(gc.dist.nl)
max(gc.dist.nl)
#Threshold based on distance calculated with bitwise.dist (dissimilarity distance)
#The most familiar name might be the Hamming distance, or the number of differences between two strings.
#Should the distance be represented from 0 to 1? Default set to TRUE. FALSE will return the distance represented as integers from 1 to n where n is the number of loci. This option has no effect if euclidean = TRUE
#If the user supplies a genind or genclone object, prevosti.dist() will be used for calculation.
#So here it is Prevosti's distance
#Set again to the original (default)
mll(gc.mp) <- "original"
mll(gc.mp) # original
gc.mp
#Choosing an algorithm and a threshold to represent the minimum genetic distance at which two individuals would be considered from different clonal lineages.
gc.mp.filtered <- filter_stats(gc.mp, distance = bitwise.dist, plot = TRUE)
gc.mp.filtered
# One method described in the literature of choosing a threshold is to look for an initial, small peak in the histogram of pairwise genetic distances and set the threshold to be between that peak and the larger peak `(Arnaud-Haond et al. 2007, @bailleul2016rclone). This initial peak likely represents clones differentiated by a small set of random mutations.
#
#Closer look, to identify the initial peak that likely represents clones differentiated by a small set of random mutations
hist(gc.dist, breaks = 10000, xlim= c(0, 0.1))
hist(gc.dist, breaks = 100000, xlim= c(0, 0.01))
hist(gc.dist, breaks = 1000000, xlim= c(0, 0.004))
hist(gc.dist, breaks = 1000000, xlim= c(0, 0.001))
#Looks like the very first peak is below 0.0001
#Threshold based on 0.0001 8 SNPs out of total 77465 (8/77465)
mlg.filter(gc.mp, distance = gc.dist, algorithm = "a") <- 0.0001 #0.0001032724 8 snps, 0.01% differences, to account for sequencing error
gc.mp #A threshold of 0.0001 gives 34 contracted multilocus genotypes
mlgid <- mlg.id(gc.mp)
mll(gc.mp) <- "contracted"
```
#Same but using snpclone
```{r}
#2. Explore orginal MLGs
#Plot thresholds
#thresh <- filter_stats(gc.mp, distance = bitwise.dist, plot = TRUE)
#p <- last_plot(); p + facet_wrap(~population, ncol = 1, scales = "free_y")
#p
#mll() to display and switch between different multilocus genotypes/lineages
#snpclone
head(mll(sc.mp, "original"), 20)
#Naïve (“original”)
#This is the default way poppr calculates multilocus genotypes
mll(sc.mp) <- "original"
sc.mp #79 original multilocus genotypes
head(mll(sc.mp, "original"), 20) # Showing the definitions for the first 20 samples
mll(sc.mp, "original") # all samples mlgs
#Default MLG: all alleles must match to make a unique multilocus genotype
#Default MLG
mlg_gc <- mlg.table(sc.mp, strata = ~Clade/Genetic_Cluster)
ggsave("mlg_clade_sc_hier.pdf")
# See which individuals belong to each MLG
mlgid <- mlg.id(sc.mp)
mlgid["59"] # "M_15_12_R1" "W_MISO2_4_10_R1"
# Let's say we want to visualize the multilocus genotype distribution for each cluster
us1atab <- mlg.table(sc.mp, sublist = c("US1A"), plot=TRUE)
ncol(us1atab) #MLGs in us1a, the columns of the table from mlg.table are equal to the number of MLGs
us1btab <- mlg.table(sc.mp, sublist = c("US1B"), plot=TRUE)
ncol(us1btab)
us2tab <- mlg.table(sc.mp, sublist = c("US2"), plot=TRUE)
ncol(us2tab)
colpr1tab <- mlg.table(sc.mp, sublist = c("COLPR1"), plot=TRUE)
ncol(colpr1tab)
colpr2tab <- mlg.table(sc.mp, sublist = c("COLPR2"), plot=TRUE)
ncol(colpr2tab)
# Show which genotypes exist accross populations in the entire dataset.
crossmlg <- mlg.crosspop(sc.mp, quiet = FALSE)
#No multilocus genotypes were detected across populations
#Country
#Default MLG
#Set again to the original (default)
mll(sc.mp) <- "original"
mll(sc.mp) # original
sc.mp
mlg_co <- mlg.table(sc.mp, strata = ~Country)
# See which individuals belong to each MLG
mlgid <- mlg.id(sc.mp)
mlgid
ustab <- mlg.table(sc.mp, strata = ~Country, sublist = c("US"), plot=TRUE)
ncol(ustab) #MLGs in us 54, the columns of the table from mlg.table are equal to the number of MLGs
coltab <- mlg.table(sc.mp, strata = ~Country, sublist = c("COL"), plot=TRUE)
ncol(coltab) #MLGs in colombia 20
prtab <- mlg.table(sc.mp, strata = ~Country, sublist = c("PR"), plot=TRUE)
ncol(prtab) #MLGs in puerto rico 5
#3.Apply a treshold for defining MLLs
#Filtered (“contracted”)
#We can utilize genetic distance, which will allow us to collapse multilocus genotypes that are under a specific distance threshold.
#Calculate raw genetic distance with bitwise.dist(), this distance is in %, see ?bitwise.dist()
#Fraction of different alleles in percentage (this is actually proportion 0 to 1):
gc.dist <- bitwise.dist(sc.mp)
gc.dist
hist(gc.dist, breaks = 100000)
median(gc.dist)
#Number of allelic differences. percent = FALSE will return the distance represented as integers from 1 to n where n is the number of loci
gc.dist.nl <- bitwise.dist(sc.mp, percent = F)
gc.dist.nl
hist(gc.dist.nl, breaks = 10000)
median(gc.dist.nl)
max(gc.dist.nl)
#Threshold based on distance calculated with bitwise.dist (dissimilarity distance)
#The most familiar name might be the Hamming distance, or the number of differences between two strings.
#Should the distance be represented from 0 to 1? Default set to TRUE. FALSE will return the distance represented as integers from 1 to n where n is the number of loci. This option has no effect if euclidean = TRUE
#If the user supplies a genind or genclone object, prevosti.dist() will be used for calculation.
#So here it is Prevosti's distance
#Set again to the original (default)
mll(sc.mp) <- "original"
mll(sc.mp) # original
sc.mp
#Choosing an algorithm and a threshold to represent the minimum genetic distance at which two individuals would be considered from different clonal lineages.
sc.mp.filtered <- filter_stats(sc.mp, distance = bitwise.dist, plot = TRUE)
sc.mp.filtered
# One method described in the literature of choosing a threshold is to look for an initial, small peak in the histogram of pairwise genetic distances and set the threshold to be between that peak and the larger peak `(Arnaud-Haond et al. 2007, @bailleul2016rclone). This initial peak likely represents clones differentiated by a small set of random mutations.
#
#Closer look, to identify the initial peak that likely represents clones differentiated by a small set of random mutations
hist(gc.dist, breaks = 10000, xlim= c(0, 0.1))
hist(gc.dist, breaks = 100000, xlim= c(0, 0.01))
hist(gc.dist, breaks = 1000000, xlim= c(0, 0.004))
hist(gc.dist, breaks = 1000000, xlim= c(0, 0.001))
#Looks like the very first peak is below 0.0001
#Threshold based on 0.0001 8 SNPs out of total 77465 (8/77465)
mlg.filter(sc.mp, distance = gc.dist, algorithm = "a") <- 0.0001 #0.0001032724 8 snps, 0.01% differences, to account for sequencing error
sc.mp #A threshold of 0.0001 gives 34 contracted multilocus genotypes
mlgid <- mlg.id(sc.mp)
mll(sc.mp) <- "contracted"
```
## 4.1.2 Defined multilocus lineages for M. phaseolina with the following criteria:
```{r}
#[t] threshold 0.0001
#[d] distance Bitwise distance (Hamming distance, as in bitwise.dist {poppr} function for genclone is Prevosti's)
#If the user supplies a genind or genclone object, prevosti.dist() will be used for calculation
#[a] algorithm average neighbor
gc.dist <- bitwise.dist(gc.mp)
mlg.filter(gc.mp, distance = gc.dist, algorithm = "a") <- 0.0001 #0.0001032724 8 snps, 0.01% differences, to account for sequencing error
gc.mp #A threshold of 0.0001 gives 34 contracted multilocus genotypes
mlgid <- mlg.id(gc.mp)
mll(gc.mp) <- "contracted"
mll(gc.mp, "contracted")
# Show which genotypes exist accross populations in the entire dataset.
crossmlg <- mlg.crosspop(gc.mp, quiet = FALSE)
#No multilocus genotypes were detected across populations
```
# 4.2 Diversity analysis using multilocus lineages as defined above
```{r}
###Distribution of MLGs
#Contracted MLG: as defined above
#strata: Clade
mlgc_cl <- mlg.table(gc.mp, strata = ~Clade)
mlgc_cl
#strata: Genetic_Cluster
mlgc_gc <- mlg.table(gc.mp, strata = ~Genetic_Cluster)
mlgc_gc
#strata: Country
mlgc_co <- mlg.table(gc.mp, strata = ~Country)
mlgc_co
#Identify shared MLGs among countries
crossmlg <- mlg.crosspop(gc.mp, strata = ~Country, quiet = FALSE)
#MLG.7: (2 inds) COL PR
#MLG.17: (2 inds) US PR
#MLG.59: (20 inds) 19 US 1 COL
#Show isolates in each of the shared MLG
# See which individuals belong to each MLG
mlgid <- mlg.id(gc.mp)
mlgid
mlgid["7"] # "Mph_5_R1" "UPR_Mph_JD1_R1"
mlgid["17"] #"TN501_R1" "UPR_Mph_ISA3_R1"
mlgid["59"]#"Mph_49_R1" with 19 US1A isolates
#strata: Country/State_Department
mlgc_st <- mlg.table(gc.mp, strata = ~State_Department)
mlgc_st
### Basic statistics
#Genetic diveristy statistics without correcting for uneven sample size
#strata: Clade
mp.mlgstat.cl <- diversity_stats(mlgc_cl)
mp.mlgstat.cl
#strata: Genetic_Cluster
mp.mlgstat.gc <- diversity_stats(mlgc_gc)
mp.mlgstat.gc
#strata: Country
mp.mlgstat.co <- diversity_stats(mlgc_co)
mp.mlgstat.co
#strata: Country/State_Department
mp.mlgstat.st <- diversity_stats(mlgc_st)
mp.mlgstat.st
###Confidence Intervals
diversity_ci(mlgc_st, n = 100L, raw = FALSE)
diversity_ci(mlgc_gc, n = 100L, raw = FALSE)
diversity_ci(mlgc_cl, n = 100L, raw = FALSE)
### Clonal fraction MLG/N
myCF <- function(x){
x <- drop(as.matrix(x))
if (length(dim(x)) > 1){ # if it's a matrix
res <- rowSums(x > 0)/rowSums(x)
} else { # if it's a vector
res <- sum(x > 0)/sum(x)
}
return(res)
}
# The previous version of poppr contained a definition of Hexp, which
# was calculated as (N/(N - 1))*lambda. It basically looks like an unbiased
# Simpson's index. This statistic was originally included in poppr because it
# was originally included in the program multilocus. It was finally figured
# to be an unbiased Simpson's diversity metric (Lande, 1996; Good, 1953).
uSimp <- function(x){
lambda <- vegan::diversity(x, "simpson")
x <- drop(as.matrix(x))
if (length(dim(x)) > 1){
N <- rowSums(x)
} else {
N <- sum(x)