-
Notifications
You must be signed in to change notification settings - Fork 1
/
TinHan_et_al2019_SuppMat.Rmd
2501 lines (1955 loc) · 80.6 KB
/
TinHan_et_al2019_SuppMat.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: "Nursery origin of a euryhaline predator: Inferences from natural tags: Baseline testing for stock identification using genetic and microchemistry data"
subtitle: "Extended Methods & Results"
author: "TC TinHan, SJ O'Leary, DS Portnoy, JR Rooker, C. Gelpy, RJD Wells"
date: "`r Sys.Date()`"
output: tint::tintHtml
bibliography: Bull.bib
link-citations: yes
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
# load libraries and functions ====
library(tint)
library(knitr)
# invalidate cache when the package version changes
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE,
cache.extra = packageVersion("tint"),
tidy = FALSE,
echo = FALSE
)
options(htmltools.dir.version = FALSE)
library(parallel)
library(doMC)
library(doParallel)
library(doSNOW)
library(radiator)
library(randomForestSRC)
library(assigner)
library(assignPOP)
library(related)
source("scr/libraries.R")
source("scr/ggplot.R")
source("scr/xtrafunctions.R")
source("scr/genind.R")
# set levels & colors for nurseries ====
# including SA
col_nurseries <- c("darkorange", "yellow",
"darkblue",
"forestgreen", "limegreen")
nurseries <- c("SL", "GAL",
"MAT",
"SA", "ARA/CC")
# main nurseries
col_nurseries1 <- c("darkorange", "yellow",
"darkblue",
"limegreen")
nurseries1 <- c("SL", "GAL",
"MAT",
"ARA/CC")
# all nurseries
nurseries2 <- c("SL", "GAL",
"MAT",
"SA", "ARA/CC",
"ULM", "LMM")
col_nurseries2 <- c("darkorange", "yellow",
"darkblue",
"forestgreen", "limegreen", "darkgreen",
"maroon4", "purple3")
# set levels + colors for regions ====
col_regions <- c("darkorange", "darkblue", "darkgreen")
regions <- c("North", "Central", "South")
col_regions1 <- c("darkorange", "darkblue", "darkgreen", "maroon4")
regions1 <- c("North", "Central", "South", "other")
# set how numbers are printed
options(scipen=999)
# functions ====
# update function ====
accuracy.MC.SOL <- function(dir=NULL){
fileName_vec <- list.files(path = dir, pattern = "Out_*")
fileName_vec <- sort(fileName_vec)
noFiles <- length(fileName_vec)
result01 <- read.table(paste0(dir, fileName_vec[1]), header = T)
pops <- names(result01)[4:length(names(result01))]
noPops <- length(pops)
Var1 <- NULL
Var2 <- NULL
train.inds <- NULL
train.loci <- NULL
iters <- NULL
assign.rate.all <- NULL
assign.rate.each <- as.data.frame(matrix(nrow = 0, ncol = noPops),
stringsAsFactors = F)
for (i in 1:noFiles) {
oneFileName <- unlist(strsplit(fileName_vec[i], split = "_"))
train.inds[i] <- oneFileName[2]
train.loci[i] <- oneFileName[3]
iters[i] <- unlist(strsplit(oneFileName[4], split = ".txt"))
df <- read.table(paste0(dir, fileName_vec[i]), header = T) %>%
mutate(origin.pop = ordered(origin.pop, levels = pops),
pred.pop = ordered(pred.pop, levels = pops))
# levels(df$origin.pop) <- pops
# levels(df$pred.pop) <- pops
ctable <- table(df$origin.pop, df$pred.pop)
ftable <- as.data.frame(ctable)
totalSample <- sum(ftable$Freq)
AllcorrectNo <- sum(subset(ftable, Var1 == Var2)$Freq)
assign.rate.all[i] <- AllcorrectNo/totalSample
popCorrectRate_vec <- NULL
for (p in pops) {
pop_size <- sum(subset(ftable, Var1 == p)$Freq)
if (pop_size == 0) {
popCorrectRate = 0
}
else {
popCorrectNo <- subset(subset(ftable, Var1 ==
Var2), Var1 == p)$Freq
popCorrectRate <- popCorrectNo/pop_size
}
popCorrectRate_vec <- c(popCorrectRate_vec, popCorrectRate)
}
assign.rate.each[i, ] <- popCorrectRate_vec
}
assign_rate_df <- cbind(train.inds, train.loci, iters, assign.rate.all,
assign.rate.each)
names(assign_rate_df)[5:ncol(assign_rate_df)] <- paste0("assign.rate.",
pops)
write.table(assign_rate_df, file = paste0(dir, "Rate_of_",
nrow(assign_rate_df), "_tests_", noPops, "_pops.txt"),
quote = F, row.names = F)
cat("\n Correct assignment rates were estimated!!")
cat(paste0("\n A total of ", nrow(assign_rate_df), " assignment tests for ",
noPops, " pops."))
cat(paste0("\n Results were also saved in a 'Rate_of_",
nrow(assign_rate_df), "_tests_", noPops, "_pops.txt' file in the directory."))
return(assign_rate_df)
}
```
# Genotyping
DNA was extracted from dermal tissue using Mag-Bind Blood and Tissue kits.
For assembly of a reduced representation reference, double digest restriction site associated DNA (ddRAD) using EcoRI and SphI following was performed to create a single library consisting of 24 individuals from all sampled estuaries which was sequenced on a single lane of an Illumina MiSeq DNA sequencer (paired end, 300bp reads). Using longer reads produced from Miseq data for reference assembly increases efficiency during read mapping and SNP calling downstream. Raw reads were demultiplexed using process_radtags [@Catchen2013] and reference contiguous sequence alignments (contigs) reconstructed using the overlapping read assembly option in the dDocent pipeline [@Puritz2014]. Reference assembly was run for a range of combinations of threshold values for K1 (minimum within individual coverage per read), K2 (number of individuals a read must occur in) and c (minimum percent similarity to cluster reads) and a test data set (subset of Hiseq data set described below) mapped to each reference to identify the optimum reference by maximizing the number of reads mapped, minimize the number of reads for which readpairs are mapped to two different contigs. Final parameters selected were K1 = 5, K2 = 6, and c = 0.8. Detailed steps can be found in the `01 Reference_Construction.html`-notebook.
For genotyping, two ddRAD libraries were constructed and sequenced on two separate lanes of an Illumina HiSeq 4000. Raw sequences were demultiplexed using `process_radtags` [@Catchen2013]. Quality trimming, read mapping to the reduced representation reference, and SNP calling were performed using the `dDocent` pipeline [@Puritz2014]. Raw SNPs were filtered using `VCFtools` [@Danecek2011] and custom scripts following O’Leary et al. [-@OLeary2018], setting thresholds for a minimum sequence and genotype quality of 20, a minimum genotype call rate per locus by estuary of 90%, a minor allele count of three, a minimum genotype depth of five, a mean minimum depth of 15, and a mean maximum depth of 180. Individuals with > 10% missing data were removed. SNPs were further filtered based on allele balance, quality/depth ratio, mapping quality ratio of reference/alternate alleles, properly paired status, strand representation, and variance in depth. Finally, SNPs on the same contig were collapsed into haplotypes using `rad_haplotyper` [@Willis2017] producing a final data set consisting of SNP-containing loci (hereafter ‘loci’) for data analysis. In addition, `rad_haplotyper` flags loci exhibiting patterns of indicative of paralogs or genotyping error due to low coverage which were removed from the final data set. Detailed filtering steps and sequentially applied thresholds are found in `02 Genotyping.html`. After haplotyping loci with a global major allele frequency > 95% were removed.
```{r cache=TRUE}
# import genotypes
df <- read_delim("data/POPGEN/CLE.filtered.genotypes", delim = "\t") %>%
select(-pop) %>%
column_to_rownames("LIB_ID")
gen <- df2genind(df, sep = ":")
# remove laguna madre individuals
removeInd <- c("CLE_2A-B09_Cleu_Lag001", "CLE_2A-B10_Cleu_Lag002")
gen <- gen.ind.rem.Ind(gen, removeInd)
# load sample info as strata
SampleInfo <- read_delim("data/POPGEN/SampleInfo.txt", delim = "\t")
Inds <- as.data.frame(indNames(gen)) %>%
rename(LIB_ID = `indNames(gen)`) %>%
separate(LIB_ID, into = c("SP", "LIB", "Cleu", "Sample"),
sep = "_", remove = FALSE, extra = "merge") %>%
unite(SAMPLE_ID, 4:5, sep = "_", remove = TRUE)
strata <- left_join(Inds, SampleInfo) %>%
distinct() %>%
mutate(POP = ifelse(POP %in% c("ARA", "CC"), "ARA/CC", POP)) %>%
mutate(REGION = case_when(POP %in% c("SL", "GAL") ~ "North",
POP == "MAT" ~ "Central",
POP %in% c("SA", "ARA/CC") ~ "South",
POP %in% c("ULM", "LMM") ~ "other"),
REGION2 = ifelse(POP %in% c("SL", "GAL", "MAT"), "North",
ifelse(POP %in% c("SA", "ARA/CC"), "South", "other"))) %>%
mutate(POP = ordered(POP, levels = nurseries2),
REGION = ordered(REGION, levels = regions1),
REGION2 = ordered(REGION2, levels = c("North", "South", "other")),
OVERALL = "overall")
write_delim(strata, "scratch/genotyped.indv")
strata(gen) <- strata
# define groups using strata information
setPop(gen) <- ~POP
```
`r nInd(gen)` individuals were genotypes for `r nLoc(gen)` loci (`r sum([email protected])` alleles).
# Sample sizes for YOY and Juvniles (genetic data)
A total of `r nrow(strata)` **YOY and juveniles** were genotyped to assess genetic heterogeneity and population differentiation.
To test for genetic heterogeneity and population structure, YOY and Juveniles were grouped by natal estuaries and regions informed by vertebral chemistry analysis defined as **South** (Corpus Christi Bay, San Antonio Bay, Aransas Bay), **Central** (Matagorda Bay), and **North** (Galveston Bay, Sabine Lake). Regional groupings were based on similarities in hydrological characteristics (e.g. temperature, salinity, sources of freshwater input), expected to produce distinctive signatures in vertebral chemistry. Exploratory analysis of genetic data indicated that the Matagorda Bay might be more appropriately grouped with the North region, therefore a second set of grouping of individuals into **South** and **North** regions was tested.
```{r}
# sample size by pop
knitr::kable(
strata %>%
count(POP),
caption = "Table 1a: Sample size per estuary (east to west - SL: Sabine Lake, GAL: Galveston Bay, MAT: Matagorda Bay, SA: San Antonio Bay, ARA/CC: Aransas & Corpus Christi Bay)."
)
# sample size by region
knitr::kable(
strata %>%
count(REGION),
caption = "Table 1b: Sample size per region (North: SL, GAL; Central: MAT; South: SA, ARA/CC)."
)
# sample size by region
knitr::kable(
strata %>%
count(REGION2),
caption = "Table 1c: Sample size per region (North: SL, GAL, MAT; South: SA, ARA/CC)."
)
```
# Assessment of genetic heterogeneity and population differentiation
`r margin_note("Confidence intervals may provide more reliable biological trends in the data than p-values which require a null hypothesis, e.g. Fst = 0, to permute p-values and can be more helpful with small sample sizes.")`
To test for genetic heterogeneity across estuaries, global FST [@Weir1984] was calculated and a 95% confidence interval (CI) determined using 1,000 iterations (loci sampled with replacement) and permuted p-values calculated using 1,000 iterations using functions implemented in `hierfstat` [@Goudet2005] and `assigner` [@Gosselin2016]. Similarly, pairwise FST 95%-CI, and permuted p-values were calculated to test for pairwise significant differences among estuaries and regions. Finally, the distribution of FST per locus was assessed to identify most informative loci.
## Calculate global allele frequencies.
Allele frequencies across all sampled individuals were calculated to compare allele frequency spectra for major allele and minor alleles. In general, loci variable in < 5% of individuals are not considered informative at a population level.
```{r fig.cap="Figure 1: Distribution of major and minor allele frequencies per locus across all individuals.", fig.height=3, fig.width=8, cache=TRUE}
# setPop(gen) <- ~OVERALL
#
# dat <- hierfstat:::.genind2hierfstat(gen)
# stats <- basic.stats(dat)
#
# f <- stats$pop.freq
#
# freq <- list()
#
# for(l in names(f)){
#
# freq[[l]] <- as.data.frame(f[[l]]) %>%
# filter(Var2 == 1) %>%
# rename(ALLELE = x,
# FRQ = Freq) %>%
# select(ALLELE, FRQ)
#
# }
#
# freq <- ldply(freq, data.frame) %>%
# rename(LOCUS = `.id`)
#
# write_delim(freq, "results/global_allelefreq.frq", delim = "\t")
freq <- read_delim("results/global_allelefreq.frq", delim = "\t")
major <- freq %>%
filter(!FRQ == Inf) %>%
group_by(LOCUS) %>%
arrange(desc(FRQ)) %>%
top_n(1, FRQ)
# write_delim(major, "results/major.frq", delim = "\t")
p1 <- ggplot(major, aes(x = FRQ)) +
geom_histogram(binwidth = 0.025, color = "black", fill = "darkorange") +
geom_vline(xintercept = 0.95, color = "darkred", linetype = "dashed") +
scale_x_continuous(limits = c(0, 1)) +
labs(x = "major allele freq", y = "number of loci") +
theme_standard
minor <- freq %>%
filter(!FRQ == Inf) %>%
group_by(LOCUS) %>%
arrange(FRQ) %>%
top_n(-1, FRQ)
# write_delim(minor, "results/minor.frq", delim = "\t")
p2 <- ggplot(minor, aes(x = FRQ)) +
geom_histogram(binwidth = 0.025, color = "black", fill = "darkorange") +
scale_y_continuous(limits = c(0, 1500)) +
scale_x_continuous(limits = c(0, 1)) +
labs(x = "minor allele freq", y = "number of loci") +
theme_standard
multiplot(p1, p2, cols = 2)
```
Loci fixed in > 95% of individuals were removed from the data set for Fst analysis and baseline assessment.
```{r}
temp <- major %>%
filter(FRQ >= .95)
removeloc <- temp$LOCUS
gen <- genind.rem.loci(gen, removeloc)
write_delim(as.data.frame(indNames(gen)), "scratch/Fst_analysis.ind", delim = "\t")
```
`r nLoc(gen)` loci (`r sum([email protected])` alleles) were retained for further analysis.
## Global Fst
```{r}
# # format genetic data for estuary comparison
# setPop(gen) <- ~POP
#
# pop <- popNames(gen)
#
# tidy <- tidy_genomic_data(data = gen, filename = NULL)
#
# # calculate fst
# fst.ci.est <- fst_WC84(data = tidy,
# holdout.samples = NULL,
# pop.levels = pop,
# pairwise = TRUE,
# ci = TRUE,
# iteration.ci = 1000,
# quantiles.ci = c(0.025, 0.975),
# digits = 9,
# parallel.core = 1,
# verbose = TRUE)
#
# write_delim(fst.ci.est$fst.overall, "results/estuaries.global.fst", delim = "\t")
kable(
read_delim("results/estuaries.global.fst", delim = "\t"),
caption = "Table 2: Global Fst and bootstrapped 95%-confidence intervals (1,000 iterations, sampled with replacement) calculated according to Weir & Cockerham 1984 for individuals grouped by natal estuary."
)
```
Individuals were permuted across estuaries to determine significance of global Fst.
```{r}
#
# # set up to run in parallel ====
# library(parallel)
# library(foreach)
# library(doMC)
#
# # set number of cores to run in parallel
# registerDoMC(55)
#
# # format genetic data for estuary comparison
# setPop(gen) <- ~POP
#
# pop <- popNames(gen)
#
# dat <- genind2hierfstat(gen)
# dat_rand <- dat
#
# # number of permutations
# nperm <- 1000
#
# # create vector with locus names
# loc <- locNames(gen)
#
# # calculate F-statistics for genotypes permuted betw pop ====
# start_time <- Sys.time()
#
# fst.glob.sim <- foreach(1:nperm) %dopar% {
#
# dat_rand$pop <- sample(dat_rand$pop, replace = FALSE)
#
# wc(dat_rand)
#
# }
#
# end_time <- Sys.time()
#
# end_time - start_time # Time difference of 1.344 hours (45 cores)
#
# # calculate F-statistics for empirical data ====
# fst.glob.obs <- wc(dat)
#
# fst.glob.obs
#
# # parse permuted Fst (all loci) ====
# sim_fst <- list()
#
# for(i in 1:nperm){
#
# sim_fst[[i]] <- as.data.frame(fst.glob.sim[[i]]$FST) %>%
# rename(SIM_FST = `fst.glob.sim[[i]]$FST`)
#
# }
#
# # calculate p-value ====
# sim_fst <- ldply(sim_fst, data.frame)
#
# obs_fst <- fst.glob.obs$FST
#
# larger <- filter(sim_fst, SIM_FST > obs_fst)
# larger <- nrow(larger)
#
# pval <- larger/nperm
#
# # write to file ====
# STAT <- c("OBS_FST", "PVAL", "NPERM")
# VALUE <- c(obs_fst, pval, nperm)
#
# results <- data.frame(STAT, VALUE)
#
# write_delim(results, "results/estuary_sign.globalfst", delim = "\t")
p <- read_delim("results/estuary_sign.globalfst", delim = "\t") %>%
filter(STAT == "PVAL")
```
**Significant genetic heterogeneity was detected among estuaries along the Texas coast (p = `r p$VALUE`).**
## Pairwise Fst: Estuary comparisons
```{r}
# write_delim(fst.ci.est$pairwise.fst, "results/estuaries.pairwise.fst", delim = "\t")
kable(
read_delim("results/estuaries.pairwise.fst", delim = "\t") %>%
arrange(desc(CI_LOW)) %>%
select(-N_MARKERS),
caption = "Table 3a: Pairwise Fst and bootstrapped 95%-CI (1000 iterations, sampled with replacement) calculated according Weir & Cockerham (1984)."
)
# col <- colnames(fst.ci.est$pairwise.fst.full.matrix)
#
# row <- rownames(fst.ci.est$pairwise.fst.full.matrix)
#
# fst_matrix <- matrix(as.numeric(unlist(fst.ci.est$pairwise.fst.full.matrix)),nrow=nrow(fst.ci.est$pairwise.fst.full.matrix))
#
# colnames(fst_matrix) <- col
# rownames(fst_matrix) <- row
#
# temp <- as.data.frame(fst_matrix) %>%
# rownames_to_column("ESTUARY")
#
# write_delim(temp, "results/estuaries.matrix.fst", delim = "\t")
kable(
read_delim("results/estuaries.matrix.fst", delim = "\t"),
caption = "Table 3b: Pairwise Fst among all pairs of estuaries"
)
```
Individuals were permuted among estuaries to calculate pairwise Fst (Weir & Cockerham 1984) and determine significance.
```{r}
# # set groups to compare ====
# setPop(gen) <- ~POP
#
# # number of groups being compared
# n <- length(popNames(gen))
#
# # compute Fst matrix ====
# dat <- genind2hierfstat(gen)
# mat.obs <- pairwise.WCfst(dat)
#
# temp <- as.data.frame(mat.obs) %>%
# rownames_to_column("GRP1") %>%
# gather(key = "GRP2", value = "obsFst", 2:(n+1)) %>%
# filter(GRP1 != GRP2)
#
# write_delim(temp, "results/estuaryWC84.fst", delim = "\t")
# # calculate pairwise Fst for individuals permuted between groups ====
#
# # create list with NPERM matrices of permuted Fst values
# NBPERM <- 1000
#
# # permute individuals between groups for each pairwise comparison
# mat.perm <- mclapply(1:NBPERM, function(i) pairwise.WCfst(mutate(dat, pop = sample(pop, replace = FALSE))), mc.cores = 20)
#
# # create data frame with permuted values
# fst_perm <- list()
#
# for(i in 1:length(mat.perm)){
#
# fst <- as.data.frame(mat.perm[[i]]) %>%
# rownames_to_column("GRP1") %>%
# gather(key = "GRP2", value = "ppFST", 2:(n+1)) %>%
# filter(GRP1 != GRP2)
#
# fst_perm[[i]] <- fst
#
# }
#
# fst_perm <- ldply(fst_perm, data.frame)
#
# write_delim(fst_perm, "results/estuaryWC84.fstperm", delim = "\t")
# # get p-values for each pairwise comparison ====
#
# # use randtest to determine p-value (i.e. is observed value different from permuted values)
# # p.globs.p<-sum(gglobs.p>=gglobs.p[nperm+1])/(nperm+1) p-val is sum(times observed value is > permuted value / total permutations)
#
# ppfst_pval <- list()
#
# for(i in 1:(nrow(mat.obs)-1)){
#
# for(j in 2:nrow(mat.obs)){
#
# ppfst_pval[[paste(rownames(mat.obs)[i], rownames(mat.obs)[j], sep = "-")]] <- as.randtest(na.omit(sapply(1:NBPERM, function(k) mat.perm[[k]][i,j])), mat.obs[i,j], alter = "greater")
#
# }
#
# }
#
# # create data frame with p-values
# COMP <- names(ppfst_pval)
#
# PVAL <- rep(NA, length(ppfst_pval))
#
# for (i in 1:length(PVAL)) {
#
# PVAL[i] <- ppfst_pval[[i]]$pvalue
#
# }
#
# pval <- data.frame(COMP, PVAL)
#
# write_delim(pval, "results/estuaryWC84.fstpval", delim = "\t")
# RESULTS ====
fst_obs <- read_delim("results/estuaryWC84.fst", delim = "\t") %>%
unite(COMP, 1:2, sep = "-", remove = FALSE)
# fst_perm <- read_delim("results/estuaryWC84.fstperm", delim = "\t") %>%
# unite(COMP, 1:2, sep = "-", remove = FALSE)
fst_pval <- read_delim("results/estuaryWC84.fstpval", delim = "\t") %>%
separate(COMP, into = c("GRP1", "GRP2"), sep = "-", remove = FALSE)
fst_sign <- left_join(fst_obs, fst_pval) %>%
filter(!is.na(PVAL)) %>%
distinct(obsFst, .keep_all = TRUE)
# pairwise Fst table
kable(
as.data.frame(fst_sign) %>%
arrange((PVAL)) %>%
select(-COMP),
caption = "Table 3c: Pairwise Fst and permuted p-values (individuals shuffled across estuaries, 1,000 permutations)"
)
```
Locus-specific Fst (individuals grouped by estuary).
```{r fig.cap="Figure 2: Distribution of locus-specific Fst-values", fig.height=4, fig.width=5}
# fst_loc <- fst.ci.est$fst.markers
#
# write_delim(fst_loc, "results/estuaries.fst.perloc", delim = "\t")
fst_loc <- read_delim("results/estuaries.fst.perloc", delim = "\t")
ggplot(fst_loc, aes(x = FST)) +
geom_histogram(binwidth = 0.005, color = "black", fill = "darkorange") +
scale_y_sqrt() +
theme_standard
kable(
count(fst_loc, FST > 0),
caption = "Table 4a: Number of loci with Fst > 0."
)
kable(
count(fst_loc, FST > 0.01),
caption = "Table 4b: Number of loci with Fst > 0.01"
)
```
## Pairwise Fst: Regional comparison (North, Central, South)
```{r}
# # prepare genetic data
# setPop(gen) <- ~REGION
#
# pop <- popNames(gen)
#
# tidy <- tidy_genomic_data(data = gen, filename = NULL)
#
# # calculate fst
# fst.ci.reg <- fst_WC84(data = tidy,
# holdout.samples = NULL,
# pop.levels = pop,
# pairwise = TRUE,
# ci = TRUE,
# iteration.ci = 1000,
# quantiles.ci = c(0.025, 0.975),
# digits = 9,
# parallel.core = 30,
# verbose = TRUE)
#
# write_delim(fst.ci.reg$pairwise.fst, "results/region.pairwiseCI.fst", delim = "\t")
# print CIs
kable(
read_delim("results/region.pairwiseCI.fst", delim = "\t") %>%
arrange(desc(CI_LOW)) %>%
select(-N_MARKERS),
caption = "Table 5a: Pairwise Fst and bootstrapped 95% confidence intervals (1000 iterations, sampled with replacement) among regions calculated according to Weir & Cockerham 1984."
)
# col <- colnames(fst.ci.reg$pairwise.fst.full.matrix)
#
# row <- rownames(fst.ci.reg$pairwise.fst.full.matrix)
#
# fst_matrix <- matrix(as.numeric(unlist(fst.ci.reg$pairwise.fst.full.matrix)),nrow=nrow(fst.ci.reg$pairwise.fst.full.matrix))
#
# colnames(fst_matrix) <- col
# rownames(fst_matrix) <- row
#
# temp <- as.data.frame(fst_matrix) %>%
# rownames_to_column("REGION")
#
# write_delim(temp, "results/region.pairwise.fst", delim = "\t")
# pairwise matrix
kable(
read_delim("results/region.pairwise.fst", delim = "\t"),
caption = "Table 5b: Pairwise Fst among all pairs of regions."
)
```
Individuals were permuted among regions to determine significance of pairwise Fst.
```{r}
# # set groups to compare ====
# setPop(gen) <- ~REGION
#
# # number of groups being compared
# n <- length(popNames(gen))
#
# # compute Fst matrix ====
# dat <- genind2hierfstat(gen)
# mat.obs <- pairwise.WCfst(dat)
#
# temp <- as.data.frame(mat.obs) %>%
# rownames_to_column("GRP1") %>%
# gather(key = "GRP2", value = "obsFst", 2:(n+1)) %>%
# filter(GRP1 != GRP2)
#
# write_delim(temp, "results/regionWC84.fst", delim = "\t")
#
# # calculate pairwise Fst for individuals permuted between groups ====
#
# # create list with NPERM matrices of permuted Fst values
# NBPERM <- 1000
#
# # permute individuals between groups for each pairwise comparison
# mat.perm <- mclapply(1:NBPERM, function(i) pairwise.WCfst(mutate(dat, pop = sample(pop, replace = FALSE))), mc.cores = 45)
#
# # create data frame with permuted values
# fst_perm <- list()
#
# for(i in 1:length(mat.perm)){
#
# fst <- as.data.frame(mat.perm[[i]]) %>%
# rownames_to_column("GRP1") %>%
# gather(key = "GRP2", value = "ppFST", 2:(n+1)) %>%
# filter(GRP1 != GRP2)
#
# fst_perm[[i]] <- fst
#
# }
#
# fst_perm <- ldply(fst_perm, data.frame)
#
# write_delim(fst_perm, "results/regionWC84.fstperm", delim = "\t")
#
# # get p-values for each pairwise comparison ====
#
# # use randtest to determine p-value (i.e. is observed value different from permuted values)
# # p.globs.p<-sum(gglobs.p>=gglobs.p[nperm+1])/(nperm+1) p-val is sum(times observed value is > permuted value / total permutations)
#
# ppfst_pval <- list()
#
# for(i in 1:(nrow(mat.obs)-1)){
#
# for(j in 2:nrow(mat.obs)){
#
# ppfst_pval[[paste(rownames(mat.obs)[i], rownames(mat.obs)[j], sep = "-")]] <- as.randtest(na.omit(sapply(1:NBPERM, function(k) mat.perm[[k]][i,j])), mat.obs[i,j], alter = "greater")
#
# }
#
# }
#
# # create data frame with p-values
# COMP <- names(ppfst_pval)
#
# PVAL <- rep(NA, length(ppfst_pval))
#
# for (i in 1:length(PVAL)) {
#
# PVAL[i] <- ppfst_pval[[i]]$pvalue
#
# }
#
# pval <- data.frame(COMP, PVAL)
#
# write_delim(pval, "results/regionWC84.fstpval", delim = "\t")
fst_obs <- read_delim("results/regionWC84.fst", delim = "\t") %>%
unite(COMP, 1:2, sep = "-", remove = FALSE)
fst_perm <- read_delim("results/regionWC84.fstperm", delim = "\t") %>%
unite(COMP, 1:2, sep = "-", remove = FALSE)
fst_pval <- read_delim("results/regionWC84.fstpval", delim = "\t") %>%
separate(COMP, into = c("GRP1", "GRP2"), sep = "-", remove = FALSE)
fst_sign <- left_join(fst_obs, fst_pval) %>%
filter(!is.na(PVAL)) %>%
distinct(obsFst, .keep_all = TRUE)
kable(
as.data.frame(fst_sign) %>%
arrange(PVAL) %>%
select(-COMP),
caption = "Table 5c: Significance of pairwise Fst between regions assessed by permuting individuals across regions (1,000 permutations)"
)
```
Assess locus-specific Fst-values.
```{r fig.cap="Figure 3: Distribution of locus-specific Fst-values for individuals grouped by geographic region", fig.height=4, fig.width=5}
# fst_loc <- fst.ci.reg$fst.markers
#
# write_delim(fst_loc, "results/region.fst.perloc", delim = "\t")
fst_loc <- read_delim("results/region.fst.perloc", delim = "\t")
ggplot(fst_loc, aes(x = FST)) +
geom_histogram(binwidth = 0.005, color = "black", fill = "darkorange") +
scale_y_sqrt() +
theme_standard
kable(
count(fst_loc, FST > 0),
caption = "Table 6a: Number of loci with Fst > 0"
)
kable(
count(fst_loc, FST > 0.01),
caption = "Table 6b: Number of loci with Fst > 0.01"
)
```
## Pairwise Fst: Regional comparison (North, South)
```{r}
# # prepare genetic data
# setPop(gen) <- ~REGION2
#
# pop <- popNames(gen)
#
# tidy <- tidy_genomic_data(data = gen, filename = NULL)
#
# # calculate fst
# fst.ci.reg <- fst_WC84(data = tidy,
# holdout.samples = NULL,
# pop.levels = pop,
# pairwise = TRUE,
# ci = TRUE,
# iteration.ci = 1000,
# quantiles.ci = c(0.025, 0.975),
# digits = 9,
# parallel.core = 55,
# verbose = TRUE)
#
# write_delim(fst.ci.reg$pairwise.fst, "results/region2.pairwise.fstCI", delim = "\t")
kable(
read_delim("results/region2.pairwise.fstCI", delim = "\t") %>%
select(-N_MARKERS),
caption = "Table 7a: Pairwise Fst and bootstrapped 95% confidence intervals between regions calculated according to Weir & Cockerham 1984."
)
```
Individuals permuted between regions to calculate pairwise Fst and determine significance.
```{r}
# # set groups to compare ====
# setPop(gen) <- ~REGION2
#
# # number of groups being compared
# n <- length(popNames(gen))
#
# # compute Fst matrix ====
# dat <- genind2hierfstat(gen)
# mat.obs <- pairwise.WCfst(dat)
#
# temp <- as.data.frame(mat.obs) %>%
# rownames_to_column("GRP1") %>%
# gather(key = "GRP2", value = "obsFst", 2:(n+1)) %>%
# filter(GRP1 != GRP2)
#
# write_delim(temp, "results/region2WC84.fst", delim = "\t")
#
# # calculate pairwise Fst for individuals permuted between groups ====
#
# # create list with NPERM matrices of permuted Fst values
# NBPERM <- 1000
#
# # permute individuals between groups for each pairwise comparison
# mat.perm <- mclapply(1:NBPERM, function(i) pairwise.WCfst(mutate(dat, pop = sample(pop, replace = FALSE))), mc.cores = 45)
#
# # create data frame with permuted values
# fst_perm <- list()
#
# for(i in 1:length(mat.perm)){
#
# fst <- as.data.frame(mat.perm[[i]]) %>%
# rownames_to_column("GRP1") %>%
# gather(key = "GRP2", value = "ppFST", 2:(n+1)) %>%
# filter(GRP1 != GRP2)
#
# fst_perm[[i]] <- fst
#
# }
#
# fst_perm <- ldply(fst_perm, data.frame)
#
# write_delim(fst_perm, "results/region2WC84.fstperm", delim = "\t")
#
# # get p-values for each pairwise comparison ====
#
# # use randtest to determine p-value (i.e. is observed value different from permuted values)
# # p.globs.p<-sum(gglobs.p>=gglobs.p[nperm+1])/(nperm+1) p-val is sum(times observed value is > permuted value / total permutations)
#
# ppfst_pval <- list()
#
# for(i in 1:(nrow(mat.obs)-1)){
#
# for(j in 2:nrow(mat.obs)){
#
# ppfst_pval[[paste(rownames(mat.obs)[i], rownames(mat.obs)[j], sep = "-")]] <- as.randtest(na.omit(sapply(1:NBPERM, function(k) mat.perm[[k]][i,j])), mat.obs[i,j], alter = "greater")
#
# }
#
# }
#
# # create data frame with p-values
# COMP <- names(ppfst_pval)
#
# PVAL <- rep(NA, length(ppfst_pval))
#
# for (i in 1:length(PVAL)) {
#
# PVAL[i] <- ppfst_pval[[i]]$pvalue
#
# }
#
# pval <- data.frame(COMP, PVAL)
#
# write_delim(pval, "results/region2WC84.fstpval", delim = "\t")
fst_obs <- read_delim("results/region2WC84.fst", delim = "\t") %>%
unite(COMP, 1:2, sep = "-", remove = FALSE)
fst_perm <- read_delim("results/region2WC84.fstperm", delim = "\t") %>%
unite(COMP, 1:2, sep = "-", remove = FALSE)
fst_pval <- read_delim("results/region2WC84.fstpval", delim = "\t") %>%
separate(COMP, into = c("GRP1", "GRP2"), sep = "-", remove = FALSE)
fst_sign <- left_join(fst_obs, fst_pval) %>%
filter(!is.na(PVAL)) %>%
distinct(obsFst, .keep_all = TRUE)
kable(
as.data.frame(fst_sign) %>%
arrange(PVAL),
caption = "Table 7b: Significance of pairwise Fst between North/South estuaries (1,000 permutations)."
)
```
Assess locus-specific Fst-values.
```{r gig.cap="Figure 4: Distribution of locus-specific Fst values for individuals grouped by region.", fig.height=4, fig.width=5}
# fst_loc <- fst.ci.reg$fst.markers
#
# write_delim(fst_loc, "results/region2.fst.perloc", delim = "\t")
fst_loc <- read_delim("results/region2.fst.perloc", delim = "\t")
ggplot(fst_loc, aes(x = FST)) +
geom_histogram(binwidth = 0.005, color = "black", fill = "darkorange") +
scale_y_sqrt() +
theme_standard
kable(
count(fst_loc, FST > 0),
caption = "Table 8a: Number of loci with Fst > 0"
)
kable(
count(fst_loc, FST > 0.01),
caption = "Table 8b: Number of loci with Fst > 0"
)
```
# Identify YOY (Age 0 individuals)
Aging data from vertebrae was used to identify YOY caught in each estuary (Age 0).
```{r}
df <- read_delim("data/POPGEN/BullShark_MetaData.txt", delim = "\t") %>%
select(SAMPLE_ID, AGE)
AGE0 <- strata %>%
left_join(df) %>%
filter(AGE == 0)
write_delim(AGE0, "results/AGE0_genotyped.indv", delim = "\t")
knitr::kable(
AGE0 %>%
count(POP),
caption = "Table 9a: Sample size per estuary (east to west - SL: Sabine Lake, GAL: Galveston Bay, MAT: Matagorda Bay, SA: San Antonio Bay, ARA/CC: Aransas & Corpus Christi Bay."
)
knitr::kable(
AGE0 %>%
count(REGION),
caption = "Table 9b: Sample size per region (North: SL, GAL; Central: MAT; South: SA, ARA/CC)."
)