/
fst_WC84.R
1866 lines (1682 loc) · 63.7 KB
/
fst_WC84.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
# Compute Weir and Cockerham (1984) Fst
#' @name fst_WC84
#' @title A fast implementation of Weir and Cockerham (1984) Fst/Theta
#' (overall and paiwise estimates)
#' @description The function calculates Weir and Cockerham (1984)
#' Fst for diploid genomes. Both overall and pairwise Fst can be estimated with
#' confidence intervals based on bootstrap of markers (resampling with replacement).
#' The function gives identical results \emph{at the 9th decimal} when tested
#' against \code{genet.dist} in \code{hierfstat}. Using the
#' argument \code{snprelate = TRUE} will compute the Fst with
#' \href{https://github.com/zhengxwen/SNPRelate}{SNPRelate}. This implementation
#' gives slightly upward bias values but provided the fastest computations I know,
#' but it doesn't compute confidence intervals, for now.
#' For an R implementation, \code{\link{fst_WC84}} is very fast.
#' The computations takes advantage of \pkg{dplyr}, \pkg{tidyr}, \pkg{purrr},
#' \pkg{parallel} and \pkg{SNPRelate}.
#' The impact of unbalanced design on estimates can be tested by using the
#' subsample argument (see advance mode section).
#'
#' \emph{Special concerns for genome-wide estimate and filtering bias}
#'
#' During computation, the function first starts by keeping only the polymorphic
#' markers in common between the populations. Keep this in mind when filtering
#' your markers to use this function characteristic strategically to get
#' better genome-wide estimate. This is even more important when your project
#' involves more than 2 populations that evolved more by neutral processes
#' (e.g. genetic drift) than by natural selection (see the vignette for more details).
#' @note \strong{Negative Fst} are technical artifact of the computation
#' (see Roesti el al. 2012) and are automatically replaced with zero inside
#' this function.
#'
#' \strong{Why no p-values ?}
#'
#' There is no null hypothesis testing with \emph{P}-values.
#' Confidence intervals provided with the \emph{F}-statistics
#' enables more reliable conclusions about the biological trends in the data.
#' @param data A tidy data frame object in the global environment or
#' a tidy data frame in wide or long format in the working directory.
#' \emph{How to get a tidy data frame ?}
#' Look into \pkg{radiator} \code{\link{tidy_genomic_data}}.
#' You can also use this function to filter your dataset using
#' whitelist of markers, blacklist of individuals and genotypes.
#' @param snprelate (optional, logical) Use \href{https://github.com/zhengxwen/SNPRelate}{SNPRelate}
#' to compute the Fst.
#' It's the fastest computation I've seen so far!
#'
#' However, testing with different RADseq datasets as shown several upward bias
#' with \code{SNPRelate::snpgdsFst} (last version tested was v.1.16.0).
#' I compared the results with assigner, hierfstat and strataG
#' (results available upon request).
#' The SNPRelate author as not given me good reason to belive the issue is fully
#' resolved, consequently, the option is no longer available, until further notice.
#' Default: \code{snprelate = FALSE}
#' @param pop.levels (optional, string) This refers to the levels in a factor. In this
#' case, the id of the pop.
#' Use this argument to have the pop ordered your way instead of the default
#' alphabetical or numerical order. e.g. \code{pop.levels = c("QUE", "ONT", "ALB")}
#' instead of the default \code{pop.levels = c("ALB", "ONT", "QUE")}.
#' Default: \code{pop.levels = NULL}.
#' @param strata (optional, data frame) A tab delimited file with 2 columns with header:
#' \code{INDIVIDUALS} and \code{STRATA}.
#' If a \code{strata} file is specified, the strata file will have
#' precedence over any grouping found data file (\code{data}).
#' The \code{STRATA} column can be any hierarchical grouping.
#' Default: \code{strata = NULL}.
#' @param pairwise (optional, logical) With \code{pairwise = TRUE}, the
#' pairwise WC84 Fst is calculated between populations.
#' Default: \code{pairwise = FALSE}.
#' @param ci (optional, logical) Compute bootstrapped confidence intervals.
#' Default: \code{ci = FALSE}.
#' @param iteration.ci (optional, integer) The number of iterations for
#' the boostraps (resampling with replacement of markers).
#' Default: \code{iteration.ci = 100}.
#' @param quantiles.ci (optional, double)
#' The quantiles for the bootstrapped confidence intervals.
#' Default: \code{quantiles.ci = c(0.025,0.975)}.
#' @param heatmap.fst (logical) Generate a heatmap with the Fst values in
#' lower matrix and CI in the upper matrix.
#' The heatmap can also be generated separately after the Fst
#' analysis using the separate function: \code{\link{heatmap_fst}}.
#' Default: \code{heatmap.fst = FALSE}.
#' @param digits (optional, integer) The number of decimal places to be used in
#' results.
#' Default: \code{digits = 9}.
#' @param parallel.core (optional, integer) The number of core for parallel computation
#' of pairwise Fst.
#' Default: \code{parallel.core = parallel::detectCores() - 1}.
#' @param verbose (optional, logical) \code{verbose = TRUE} to be chatty
#' during execution.
#' Default: \code{verbose = FALSE}.
#' @param filename (optional, character) Give filename prefix, this will trigger
#' saving results in a directory.
#' Default: \code{filename = NULL}.
#' @param ... other parameters passed to the function.
#' @section Advance mode:
#'
#' \emph{dots-dots-dots ...} allows to pass several arguments for fine-tuning the function:
#' \enumerate{
#'
#' \item \code{filter.monomorphic} (logical, optional) By default monomorphic
#' markers present in the dataset are removed (and it should stay that way...).
#' Default: \code{filter.monomorphic = TRUE}.
#'
#' \item \code{holdout.samples} (optional, data frame) Samples that don't participate in the Fst
#' computation (supplementary). Data frame with one column \code{INDIVIDUALS}.
#' This argument is used inside assignment analysis.
#' Default: \code{holdout.samples = NULL}.
#'
#' \item \code{subsample} (Integer or character)
#' With \code{subsample = 36}, 36 individuals in each populations are chosen
#' randomly to represent the dataset. With \code{subsample = "min"}, the
#' minimum number of individual/population found in the data is used automatically.
#' Default is no subsampling, \code{subsample = NULL}.
#' \item \code{iteration.subsample} (Integer) The number of iterations to repeat
#' subsampling.
#' With \code{subsample = 20} and \code{iteration.subsample = 10},
#' 20 individuals/populations will be randomly chosen 10 times.
#' Default: \code{iteration.subsample = 1}.
#'
#'
#' \item \code{calibrate.alleles} (logical)
#' Un-calibrated alleles can bias estimate and by default the function expect that
#' the REF/ALT alleles are calibrated. Using \code{calibrate.alleles = TRUE},
#' can take a bit more time.
#' Default: \code{calibrate.alleles = FALSE}.
#' }
#' @return The function returns a list with several objects.
#' When sumsample is selected the objects end with \code{.subsample}.
#' \itemize{
#' \item \code{$subsampling.individuals}: the combinations of individuals and subsamples,
#' \item \code{$sigma.loc}: the variance components per locus, with
#' (\code{lsiga}: among populations,
#' \code{lsigb}: among individuals within populations,
#' \code{lsigw}: within individuals)
#' \item \code{$fst.markers}: the fst by markers,
#' \item \code{$fst.ranked}: the fst ranked,
#' \item \code{$fst.overall}: the mean fst overall markers and the number of markers
#' \item \code{$fis.markers}: the fis by markers,
#' \item \code{$fis.overall}: the mean fis overall markers and the number of markers,
#' \item \code{$fst.plot}: the histogram of the overall Fst per markers,
#' \item \code{$pairwise.fst}: the pairwise fst in long/tidy data frame and the number of markers ,
#' \item \code{$pairwise.fst.upper.matrix}: the pairwise fst in a upper triangle matrix,
#' \item \code{$pairwise.fst.full.matrix}: the pairwise fst matrix (duplicated upper and lower triangle),
#' \item \code{$pairwise.fst.ci.matrix}: matrix with pairwise fst in the upper triangle
#' and the confidence intervals in the lower triangle.
#' \item when subsample is selected \code{$pairwise.fst.subsample.mean} is a summary
#' of all pairwise comparisons subsample. The mean is calculated accross summary
#' statistics.
#' }
#' @export
#' @rdname fst_WC84
#' @examples
#' \dontrun{
#' wombat.fst.pairwise <- fst_WC84(
#' data = "wombat.filtered.tidy.tsv",
#' pop.levels = c("ATL", "MLE", "BIS", "PMO", "SOL", "TAS", "ECU"),
#' pairwise = TRUE,
#' ci = TRUE,
#' iteration.ci = 10000,
#' quantiles.ci = c(0.025,0.975),
#' parallel.core = 8,
#' verbose = TRUE,
#' filename = "wombat",
#' heatmap.fst = TRUE
#' )
#'
#' # To get the overall Fst estimate:
#' wombat.fst.pairwise$fst.overall
#'
#' # To get the Fst plot:
#' wombat.fst.pairwise$fst.plot
#'
#' #To get the pairwise Fst values with confidence intervals in a data frame:
#' df <- wombat.fst.pairwise$pairwise.fst
#' }
#' @references Excoffier L, Smouse PE, Quattro JM.
#' Analysis of molecular variance inferred from metric distances among
#' DNA haplotypes: application to human mitochondrial DNA restriction data.
#' Genetics. 1992;131: 479-491.
#' @references Meirmans PG, Van Tienderen PH (2004) genotype and genodive:
#' two programs for the analysis of genetic diversity of asexual organisms.
#' Molecular Ecology Notes, 4, 792-794.
#' @references Michalakis Y, Excoffier L.
#' A generic estimation of population
#' subdivision using distances between alleles with special reference for
#' microsatellite loci.
#' Genetics. 1996;142: 1061-1064.
#' @references Weir BS, Cockerham CC (1984) Estimating F-Statistics for the
#' Analysis of Population Structure.
#' Evolution, 38, 1358-1370.
#' @references Roesti M, Salzburger W, Berner D. (2012)
#' Uninformative polymorphisms bias genome scans for signatures of selection.
#' BMC Evol Biol., 12:94. doi:10.1111/j.1365-294X.2012.05509.x
#' @references Zheng X, Levine D, Shen J, Gogarten SM, Laurie C, Weir BS.
#' A high-performance computing toolset for relatedness and principal component
#' analysis of SNP data. Bioinformatics. 2012;28: 3326-3328.
#' doi:10.1093/bioinformatics/bts606
#' @seealso
#' From \href{http://www.bentleydrummer.nl/software/software/GenoDive.html}{GenoDive} manual:
#' \emph{'In general, rather than to test differentiation between all pairs of
#' populations,
#' it is advisable to perform an overall test of population differentiation,
#' possibly using a hierarchical population structure, (see AMOVA)'}.
#' To compute an AMOVA, use \href{http://www.bentleydrummer.nl/software/software/GenoDive.html}{GenoDive}
#' or \code{Phi_st_Meirmans} in \code{mmod}.
#'
#' \href{https://github.com/jgx65/hierfstat/}{hierfstat}
#'
#' For Fisher's exact test and p-values per markers
#' see \code{mmod} \code{diff_test}.
#'
#' \strong{Vignette for this function:} \href{https://www.dropbox.com/s/tiq4yenzmgzc2f5/fst_confidence_intervals.html?dl=0}{how to do the pairwise and overall Fst with confidence intervals and build the phylogenetic tree}
#' @author Thierry Gosselin \email{thierrygosselin@@icloud.com}
# Fst function: Weir & Cockerham 1984
fst_WC84 <- function(
data,
snprelate = FALSE,
strata = NULL,
pop.levels = NULL,
pairwise = FALSE,
ci = FALSE,
iteration.ci = 100,
quantiles.ci = c(0.025,0.975),
heatmap.fst = FALSE,
digits = 9,
filename = NULL,
parallel.core = parallel::detectCores() - 2,
verbose = FALSE,
...
) {
## test
# data
# snprelate = FALSE
# pop.levels = NULL
# strata = NULL
# holdout.samples = NULL
# pairwise = FALSE
# ci = FALSE
# iteration.ci = 100
# quantiles.ci = c(0.025, 0.975)
# subsample = NULL
# iteration.subsample = 1
# digits = 9
# parallel.core = parallel::detectCores() - 1
# verbose = TRUE
# filename = "coral_fst"
# heatmap.fst = FALSE
# filter.monomorphic=TRUE
# calibrate.alleles = FALSE
# Cleanup---------------------------------------------------------------------
assigner_function_header(f.name = "fst_WC84", verbose = verbose)
file.date <- format(Sys.time(), "%Y%m%d@%H%M")
if (verbose) message("Execution date/time: ", file.date)
old.dir <- getwd()
opt.change <- getOption("width")
options(width = 70)
timing <- assigner_tic()
res <- list()
#back to the original directory and options
on.exit(setwd(old.dir), add = TRUE)
on.exit(options(width = opt.change), add = TRUE)
on.exit(assigner_toc(timing), add = TRUE)
on.exit(assigner_function_header(f.name = "fst_WC84", start = FALSE, verbose = verbose), add = TRUE)
# Function call and dotslist -------------------------------------------------
rad.dots <- assigner::assigner_dots(
func.name = as.list(sys.call())[[1]],
fd = rlang::fn_fmls_names(),
args.list = as.list(environment()),
dotslist = rlang::dots_list(..., .homonyms = "error", .check_assign = TRUE),
keepers = c("filter.monomorphic", "holdout.samples", "subsample",
"iteration.subsample", "blacklist.id",
"calibrate.alleles"),
verbose = FALSE
)
dots.filename <- stringi::stri_join("assigner_fst_WC84_args_", file.date, ".tsv")
# currently not saved
# Checking for missing and/or default arguments ------------------------------
if (missing(data)) rlang::abort("data is missing")
if (!ci && heatmap.fst) {
heatmap.fst <- FALSE
if (verbose) message("\nconfidence intervals not selected, heatmap.fst: FALSE\n")
}
if (!filter.monomorphic) {
message("filter.monomorphic = FALSE... not a good idea, but lets do it...")
}
# filename & folder ----------------------------------------------------------
path.folder <- NULL
if (!is.null(filename)) {
filename <- stringi::stri_join(filename, "_fst_WC84")
path.folder <- radiator::generate_folder(
f = filename,
file.date = file.date,
verbose = verbose)
}
if (snprelate) {
# Check that snprelate is installed
if (!"SNPRelate" %in% utils::installed.packages()[,"Package"]) {
rlang::abort('Please install SNPRelate for this option:\n
install.packages("BiocManager")
BiocManager::install("SNPRelate")')
}
rlang::abort("Until the bias observed with SNPRelate is resolved, the option is unavailable.")
}
# Import data ---------------------------------------------------------------
if (verbose) message("Importing data")
data %<>% radiator::tidy_wide(data = ., import.metadata = TRUE)
if (!rlang::has_name(data, "GT") || calibrate.alleles) {
data %<>%
radiator::calibrate_alleles(
data = .,
parallel.core = parallel.core
) %$%
input
}
# Strata----------------------------------------------------------------------
strata <- radiator::read_strata(
strata = strata,
pop.id = TRUE,
blacklist.id = blacklist.id,
pop.levels = NULL,
verbose = verbose) %$%
strata
# population levels and strata------------------------------------------------
if (!is.null(strata)) {
data <- radiator::join_strata(
data = data, strata = strata, pop.id = TRUE, verbose = FALSE)
}
if (!rlang::has_name(data, "POP_ID") && rlang::has_name(data, "STRATA")) {
data %<>% dplyr::rename(POP_ID = STRATA)
}
pop.levels.bk <- pop.levels
if (is.null(pop.levels)) pop.levels.bk <- unique(data$POP_ID)
data %<>%
dplyr::mutate(POP_ID = factor(x = POP_ID, levels = pop.levels.bk)) %>%
dplyr::arrange(POP_ID)
# strip the data -------------------------------------------------------------
strata.bk <- markers.meta.bk <- genotypes.meta.bk <- NULL
env.arg <- rlang::current_env()
data %<>%
radiator::strip_rad(
x = .,
m = c("VARIANT_ID", "MARKERS", "CHROM", "LOCUS", "POS", "COL", "REF", "ALT"),
env.arg = env.arg,
keep.strata = TRUE,
verbose = FALSE
) %>%
dplyr::select(tidyselect::any_of(c("M_SEQ", "STRATA_SEQ", "ID_SEQ", "GT"))) %>%
dplyr::rename(MARKERS = M_SEQ, STRATA = STRATA_SEQ, INDIVIDUALS = ID_SEQ)
pop.levels <- unique(data$STRATA)
# subsampling data------------------------------------------------------------
# create the subsampling list
if (!is.null(subsample) && !is.numeric(subsample)) {
heatmap.fst <- FALSE
if (subsample == "min") {
subsample <- strata.bk %>%
dplyr::group_by(STRATA_SEQ) %>%
dplyr::tally(.) %>%
dplyr::filter(n == min(n)) %>%
dplyr::ungroup(.) %>%
dplyr::select(n) %>%
purrr::flatten_int(.)
}
}
subsample.list <- purrr::map(
.x = 1:iteration.subsample,
.f = subsampling_data,
strata = strata.bk,
subsample = subsample
)
# keep track of subsampling individuals and write to directory
if (!is.null(subsample)) {
if (verbose) message("Subsampling: selected")
res$subsample$subsampling.individuals <- subsample.list %>%
dplyr::bind_rows() %>%
readr::write_tsv(
x = .,
file = file.path(path.folder, "subsampling.individuals.tsv")
)
} # End subsampling
# Calculations ----------------------------------------------------------------
subsample.fst <- purrr::map(
.x = subsample.list,
.f = fst_subsample,
data = data,
snprelate = snprelate,
strata = strata.bk,
holdout.samples = holdout.samples,
pairwise = pairwise,
ci = ci,
iteration.ci = iteration.ci,
quantiles.ci = quantiles.ci,
digits = digits,
subsample = subsample,
path.folder = path.folder,
parallel.core = parallel.core,
verbose = verbose
)
subsample.list <- NULL
# Compiling results-----------------------------------------------------------
if (verbose) message("Generating statistics...")
# no subsampling --------------------------
if (is.null(subsample)) {
# These are the objects:
# sigma.loc
# fst.markers
# fst.ranked
# fst.overall
# fis.markers
# fis.overall
# fst.plot
# pairwise.fst & pairwise.fst.mean
# pairwise.fst.upper.matrix & pairwise.fst.upper.matrix.mean
# pairwise.fst.full.matrix & pairwise.fst.full.matrix.mean
# merge upper and lower matrix
# pairwise.fst.ci.matrix
# subsample.fst <- purrr::flatten(subsample.fst)
# res <- purrr::prepend(x = res, values = purrr::flatten(subsample.fst))
# change strata --------
nms <- subsample.fst %>% purrr::map(names) %>% purrr::reduce(union)
res <- purrr::map(
.x = nms,
.f = fst_stats,
l = subsample.fst,
digits = digits,
m = markers.meta.bk,
s = dplyr::distinct(strata.bk, POP_ID, STRATA_SEQ),
subsample = FALSE
) %>%
purrr::flatten(.)
# test1 <- res$pairwise.fst
# test2 <- res$pairwise.fst.upper.matrix
# pairwise.fst.upper.matrix
# pairwise.fst.full.matrix
# pairwise.fst.ci.matrix
# write results --------
if (!is.null(filename)) {
purrr::walk(
.x = list("sigma.loc", "fst.markers", "fst.ranked", "fst.overall",
"fis.markers", "fis.overall", "pairwise.fst"),
.f = fst_write, list.sub = res, path.folder = path.folder
)
# fst.plot
ggplot2::ggsave(
filename = file.path(path.folder, "fst.plot.pdf"),
plot = res$fst.plot,
width = 15, height = 10,
dpi = 300, units = "cm", device = "pdf", limitsize = FALSE,
useDingbats = FALSE
)
saveRDS(
object = res$pairwise.fst.upper.matrix,
file = file.path(path.folder, "pairwise.fst.upper.matrix.RData"))
saveRDS(
object = res$pairwise.fst.full.matrix,
file = file.path(path.folder, "pairwise.fst.full.matrix.RData"))
saveRDS(
object = res$pairwise.fst.ci.matrix,
file = file.path(path.folder, "pairwise.fst.ci.matrix.RData"))
}
}# end of compiling results NO SUBSAMPLE
# compile subsampling results --------------
if (!is.null(subsample)) {
nms <- subsample.fst %>% purrr::map(names) %>% purrr::reduce(union)
res$subsample <- purrr::map(
.x = nms,
fst_stats,
l = subsample.fst,
digits = digits,
m = markers.meta.bk,
s = dplyr::distinct(strata.bk, POP_ID, STRATA_SEQ),
subsample = TRUE
) %>%
purrr::flatten(.)
# These are the objects:
# sigma.loc
# fst.markers
# fst.ranked
# fst.overall
# fis.markers
# fis.overall
# fst.plot
# pairwise.fst & pairwise.fst.mean
# pairwise.fst.upper.matrix & pairwise.fst.upper.matrix.mean
# pairwise.fst.full.matrix & pairwise.fst.full.matrix.mean
# merge upper and lower matrix
# pairwise.fst.ci.matrix
# test1 <- res$subsample$sigma.loc
# test2 <- res$subsample$pairwise.fst
# test3 <- res$subsample$pairwise.fst.full.matrix
# test3[3]
# Work on the matrix of FST-------
res$subsample$pairwise.fst.upper.matrix.mean <- res$subsample$pairwise.fst %>%
dplyr::select(POP1, POP2, FST) %>%
tidyr::complete(data = ., POP1, POP2) %>%
assigner::rad_wide(x = ., formula = "POP1 ~ POP2", values_from = "FST", values_fill = "") %>%
dplyr::rename(POP = POP1)
rn <- res$subsample$pairwise.fst.upper.matrix.mean$POP # rownames
res$subsample$pairwise.fst.upper.matrix.mean <- as.matrix(res$subsample$pairwise.fst.upper.matrix.mean[,-1])# make matrix without first column
rownames(res$subsample$pairwise.fst.upper.matrix.mean) <- rn
# pairwise.fst.full.matrix & pairwise.fst.full.matrix.mean
res$subsample$pairwise.fst.full.matrix.mean <- res$subsample$pairwise.fst.upper.matrix.mean # bk of upper.mat.fst
lower.mat.fst <- t(res$subsample$pairwise.fst.full.matrix.mean) # transpose
# merge upper and lower matrix
res$subsample$pairwise.fst.full.matrix.mean[lower.tri(res$subsample$pairwise.fst.full.matrix.mean)] <- lower.mat.fst[lower.tri(lower.mat.fst)]
diag(res$subsample$pairwise.fst.full.matrix.mean) <- "0"
# write results --------
if (!is.null(filename)) {
purrr::walk(
.x = list("sigma.loc", "fst.markers", "fst.ranked", "fst.overall",
"fis.markers", "fis.overall", "pairwise.fst"),
.f = fst_write, list.sub = res$subsample, path.folder = path.folder
)
saveRDS(
object = res$subsample$pairwise.fst.upper.matrix.mean,
file = file.path(path.folder, "pairwise.fst.upper.matrix.RData")
)
saveRDS(
object = res$subsample$pairwise.fst.full.matrix.mean,
file = file.path(path.folder, "pairwise.fst.full.matrix.RData"))
}
# CI ----------
# defaults
res$subsample$pairwise.fst.ci.matrix <-
res$subsample$pairwise.fst.ci.matrix.mean <-
"confidence intervals not selected"
if (ci) {
# pairwise.fst.ci.matrix
# pairwise.fst.ci.matrix.mean
lower.mat.ci.sub <- res$subsample$pairwise.fst %>%
dplyr::select(POP1, POP2, CI_LOW, CI_HIGH) %>%
tidyr::unite(data = ., CI, CI_LOW, CI_HIGH, sep = " - ") %>%
tidyr::complete(data = ., POP1, POP2) %>%
assigner::rad_wide(x = ., formula = "POP1 ~ POP2", values_from = "CI", values_fill = "") %>%
dplyr::rename(POP = POP1)
cn <- colnames(lower.mat.ci.sub) # bk of colnames
lower.mat.ci.sub <- t(lower.mat.ci.sub[,-1]) # transpose
colnames(lower.mat.ci.sub) <- cn[-1] # colnames - POP
lower.mat.ci.sub = as.matrix(lower.mat.ci.sub) # matrix
# merge upper and lower matrix
pairwise.fst.ci.matrix.sub <- res$subsample$pairwise.fst.upper.matrix.mean # bk upper.mat.fst
pairwise.fst.ci.matrix.sub[lower.tri(pairwise.fst.ci.matrix.sub)] <- lower.mat.ci.sub[lower.tri(lower.mat.ci.sub)]
res$subsample$pairwise.fst.ci.matrix.mean <- pairwise.fst.ci.matrix.sub
pairwise.fst.ci.matrix.sub <- NULL
if (!is.null(filename)) {
saveRDS(
object = res$subsample$pairwise.fst.ci.matrix.mean,
file = file.path(path.folder, "pairwise.fst.ci.matrix.RData")
)
}
}
} # end of compiling subsample results
# heatmap.fst ----------------------------------------------------------------
if (heatmap.fst) {
if (verbose) message("Generating heatmap...")
res$heatmap.fst <- heatmap_fst(
pairwise.fst.full.matrix = res$pairwise.fst.full.matrix,
pairwise.fst.ci.matrix = res$pairwise.fst.ci.matrix,
digits = digits,
path.folder = path.folder,
filename = filename)
}
# End -------------------------------------------------------------------
if (verbose) {
cat("################################### RESULTS ####################################\n")
if (is.null(subsample)) {
if (ci) {
message("Fst (overall): ", res$fst.overall$FST, " [", res$fst.overall$CI_LOW, " - ", res$fst.overall$CI_HIGH, "]")
} else{
message("Fst (overall): ", res$fst.overall$FST)
}
} else {
message("Fst (overall): ", res$subsample$fst.overall$MEAN)
}
}
return(res)
}
# Internal Nested Functions to compute WC84 Fst --------------------------------
# fst_subsample-----------------------------------------------------------------
#' @title fst_subsample
#' @description Function that link all with subsampling
#' @rdname fst_subsample
#' @export
#' @keywords internal
fst_subsample <- function(
x,
data,
snprelate = FALSE,
strata = NULL,
holdout.samples = NULL,
pairwise = FALSE,
ci = FALSE,
iteration.ci = 100,
quantiles.ci = c(0.025,0.975),
digits = 9,
subsample = NULL,
path.folder = NULL,
parallel.core = parallel::detectCores() - 1,
verbose = FALSE,
...
) {
# x <- subsample.list[[1]] # test
res <- list()# create list to store results
# Managing subsampling -------------------------------------------------------
subsample.id <- unique(x$SUBSAMPLE)
if (!is.null(subsample) && (verbose)) message("Analyzing subsample: ", subsample.id)
# genotyped data and holdout sample ------------------------------------------
data %<>%
dplyr::filter(INDIVIDUALS %in% x$ID_SEQ) %>% # Keep only the subsample
dplyr::filter(GT != "000000")
x <- NULL #unused object
# if holdout set, removes individuals
if (!is.null(holdout.samples)) {
message("Removing holdout individuals\nFst computation...")
holdout.samples <- strata %>%
dplyr::filter(INDIVIDUALS %in% holdout.samples) %$%
ID_SEQ
data %<>%
dplyr::filter(!INDIVIDUALS %in% holdout.samples)
}
# Compute global Fst ---------------------------------------------------------
if (verbose) message("Global fst...")
global.res <- compute_fst(
x = data,
ci = ci,
iteration.ci = iteration.ci,
quantiles.ci = quantiles.ci,
digits = digits,
path.folder = path.folder,
global = TRUE,
pairwise = pairwise
)
if (pairwise) {
temp.files <- global.res$temp.files
global.res$temp.files <- NULL
}
res <- append(res, global.res)
global.res <- NULL # unsused object
# Compute pairwise Fst -------------------------------------------------------
if (pairwise) {
if (verbose) message("Pairwise fst...")
if (!is.factor(data$STRATA)) data$STRATA <- factor(data$STRATA)
pop.list <- levels(data$STRATA) # pop list
# all combination of populations
pop.pairwise <- utils::combn(pop.list, 2, simplify = FALSE)
npp <- length(pop.pairwise)
if (verbose) message("Number of pairwise computations: ", npp)
# Fst for all pairwise populations
list.pair <- seq_len(npp)
p <- NULL
progressr::with_progress({
p <- progressr::progressor(along = list.pair)
fst.all.pop <- assigner::assigner_future(
.x = list.pair,
.f = pairwise_fst,
flat.future = "dfr",
split.vec = FALSE,
split.with = NULL,
parallel.core = min(10L, parallel.core),
pop.pairwise = pop.pairwise,
data = data,
ci = ci,
iteration.ci = iteration.ci,
quantiles.ci = quantiles.ci,
path.folder = path.folder,
p = p,
temp.files = temp.files
)
})
# Table with Fst
pairwise.fst <- fst.all.pop %>%
dplyr::mutate(
POP1 = factor(POP1, levels = pop.list),
POP2 = factor(POP2, levels = pop.list)
# N_MARKERS = as.integer(N_MARKERS)
) %>%
dplyr::mutate(dplyr::across(where(is.numeric), .fns = round, digits = digits))
# }#End pairwise Fst
# Matrix--------------------------------------------------------------------
upper.mat.fst <- pairwise.fst %>%
dplyr::select(POP1, POP2, FST) %>%
tidyr::complete(data = ., POP1, POP2) %>%
assigner::rad_wide(x = ., formula = "POP1 ~ POP2", values_from = "FST", values_fill = "") %>%
dplyr::rename(POP = POP1)
rn <- upper.mat.fst$POP # rownames
upper.mat.fst <- as.matrix(upper.mat.fst[,-1])# make matrix without first column
rownames(upper.mat.fst) <- rn
# get the full matrix with identical lower and upper diagonal
# the diagonal is filled with 0
full.mat.fst <- upper.mat.fst # bk of upper.mat.fst
lower.mat.fst <- t(full.mat.fst) # transpose
# merge upper and lower matrix
full.mat.fst[lower.tri(full.mat.fst)] <- lower.mat.fst[lower.tri(lower.mat.fst)]
diag(full.mat.fst) <- "0"
if (ci) {
# bind upper and lower diagonal of matrix
lower.mat.ci <- pairwise.fst %>%
dplyr::select(POP1, POP2, CI_LOW, CI_HIGH) %>%
tidyr::unite(data = ., CI, CI_LOW, CI_HIGH, sep = " - ") %>%
tidyr::complete(data = ., POP1, POP2) %>%
assigner::rad_wide(x = ., formula = "POP1 ~ POP2", values_from = "CI", values_fill = "") %>%
dplyr::rename(POP = POP1)
cn <- colnames(lower.mat.ci) # bk of colnames
lower.mat.ci <- t(lower.mat.ci[,-1]) # transpose
colnames(lower.mat.ci) <- cn[-1] # colnames - POP
lower.mat.ci = as.matrix(lower.mat.ci) # matrix
# merge upper and lower matrix
pairwise.fst.ci.matrix <- upper.mat.fst # bk upper.mat.fst
pairwise.fst.ci.matrix[lower.tri(pairwise.fst.ci.matrix)] <- lower.mat.ci[lower.tri(lower.mat.ci)]
} else {
pairwise.fst.ci.matrix <- "confidence intervals not selected"
}
} else {
pairwise.fst <- "pairwise fst not selected"
upper.mat.fst <- "pairwise fst not selected"
full.mat.fst <- "pairwise fst not selected"
pairwise.fst.ci.matrix <- "pairwise fst not selected"
}
res$pairwise.fst <- pairwise.fst
res$pairwise.fst.upper.matrix <- upper.mat.fst
res$pairwise.fst.full.matrix <- full.mat.fst
res$pairwise.fst.ci.matrix <- pairwise.fst.ci.matrix
return(res)
}#End fst_subsample
# compute_fst------------------------------------------------------------------
#' @title compute_fst
#' @description main function
#' @rdname compute_fst
#' @export
#' @keywords internal
compute_fst <- carrier::crate(function(
x,
ci = FALSE,
iteration.ci = 100,
quantiles.ci = c(0.025,0.975),
digits = 9,
path.folder = NULL,
parallel.core = parallel::detectCores(.) - 2,
p = NULL,
global = TRUE,
pairwise = FALSE,
temp.files = NULL,
...
) {
# TEST
# ci = FALSE
# iteration.ci = 100
# quantiles.ci = c(0.025,0.975)
# digits = 9
# path.folder = NULL
## x = data
# x <- dplyr::filter(data, GT != "000000")
`%>%` <- magrittr::`%>%`
`%<>%` <- magrittr::`%<>%`
`%$%` <- magrittr::`%$%`
if (!is.null(p)) p()
# Removing monomorphic markers
x %<>%
radiator::filter_monomorphic(data = ., internal = TRUE, path.folder = path.folder)
# number of marker used for computation
n.markers <- length(unique(x$MARKERS))
# the bottleneck -----
# a per strata FST analysis that prepares the data ...
# We check if we could speed up execution of the pairwise analysis without
# compromising the computations of the global FST
# global <- pairwise <- TRUE
# Fst prep is used in 3 parts
if (global && pairwise) {
if (is.null(path.folder)) path.folder <- getwd()
tmpdir <- file.path(path.folder, paste0("assigner_temp_", format(Sys.time(), "%Y%m%d@%H%M")))
dir.create(path = tmpdir)
temp.files <- list()
}
pop.select <- unique(x$STRATA)
if (global) {
fst.prep <- x %>%
dplyr::mutate(
`1` = stringi::stri_sub(GT, 1,3),
`2` = stringi::stri_sub(GT, 4,6),
GT = NULL,
HET = dplyr::if_else(`1` != `2`, 1L, 0L)
) %>%
assigner::rad_long(
x = .,
cols = c("MARKERS", "STRATA", "INDIVIDUALS", "HET"),
names_to = "ALLELE_GROUP",
values_to = "ALLELES",
variable_factor = TRUE
) %>%
dplyr::mutate(ALLELE_GROUP = as.integer(ALLELE_GROUP))
if (pairwise) {
temp.files$fst.prep <- fst.prep
# temp.files$fst.prep.temp <- tempfile(tmpdir = tmpdir, fileext = ".tsv")
# vroom::vroom_write(fst.prep, temp.files$fst.prep.temp, num_threads = parallel.core, progress = FALSE)
}
fa <- fst.prep %>%
dplyr::group_by(MARKERS, STRATA, ALLELES) %>%
dplyr::summarise(
n = dplyr::n(),
MHO = length(HET[HET == 1]),
.groups = "drop"
) %>%
tidyr::complete(data = ., STRATA, tidyr::nesting(MARKERS, ALLELES), fill = list(MHO = 0, n = 0)) %>%
dplyr::group_by(MARKERS, STRATA) %>%
dplyr::mutate(
NAPL = sum(n), # Number of alleles per locus
FREQ_APL = n / NAPL # Frequency of alleles per pop and locus
) %>%
dplyr::ungroup(.) #%>% dplyr::arrange(MARKERS, ALLELES, STRATA)
if (pairwise) {
temp.files$fa <- fa
# temp.files$fa.temp <- tempfile(tmpdir = tmpdir, fileext = ".tsv")
# vroom::vroom_write(fa, temp.files$fa.temp, num_threads = parallel.core, progress = FALSE)
}
npl <- dplyr::distinct(x, MARKERS, STRATA) %>% dplyr::mutate(NPL = 1L) %>%
assigner::rad_wide(x = ., formula = "MARKERS ~ STRATA", values_from = "NPL", values_fill = 0L)
if (pairwise) {
temp.files$npl <- npl
# temp.files$npl.temp <- tempfile(tmpdir = tmpdir, fileext = ".tsv")
# vroom::vroom_write(npl, temp.files$npl.temp, num_threads = parallel.core, progress = FALSE)
}
nil <- dplyr::count(x, MARKERS, STRATA, name = "NIL") %>%
assigner::rad_wide(x = ., formula = "MARKERS ~ STRATA", values_from = "NIL", values_fill = 0L)
if (pairwise) {
temp.files$nil <- nil
# temp.files$nil.temp <- tempfile(tmpdir = tmpdir, fileext = ".tsv")
# vroom::vroom_write(nil, temp.files$nil.temp, num_threads = parallel.core, progress = FALSE)
}
} else {
# here we have to read the data in...
fst.prep <- temp.files$fst.prep %>%
# fst.prep <- vroom::vroom(
# file = temp.files$fst.prep.temp,
# delim = "\t",
# col_types = "iiiiic",
# progress = FALSE,
# num_threads = 1
# ) %>%
dplyr::filter(STRATA %in% pop.select)
fa <- temp.files$fa %>%
# fa <- vroom::vroom(
# file = temp.files$fa.temp,
# delim = "\t",
# col_types = "iicdddd",
# num_threads = 1,
# progress = FALSE
# ) %>%
dplyr::filter(STRATA %in% pop.select)
npl <- temp.files$npl %>%
# npl <- vroom::vroom(
# file = temp.files$npl.temp,
# delim = "\t",
# col_types = vroom::cols(.default = vroom::col_integer()),
# num_threads = 1,
# progress = FALSE
# ) %>%
dplyr::select(tidyselect::any_of(c("MARKERS", pop.select))) # here the pop.pair
nil <- temp.files$nil %>%
# nil <- vroom::vroom(
# file = temp.files$nil.temp,
# delim = "\t",
# col_types = vroom::cols(.default = vroom::col_integer()),
# num_threads = 1,
# progress = FALSE
# ) %>%
dplyr::select(tidyselect::any_of(c("MARKERS", pop.select))) # here the pop.pair
}
# both global and pairwise
count.locus <- npl %>%
dplyr::select(MARKERS) %>%
dplyr::mutate(
NPL = rowSums(x = npl[-1], na.rm = TRUE),# much longer using rowwise
NIL = rowSums(x = nil[-1], na.rm = TRUE),
NIPL = rowSums(x = nil[-1]^2, na.rm = TRUE), # read nipl square sum
NC = (NIL - NIPL / NIL) / (NPL - 1)#correction
)
npl <- nil <- NULL
x <- NULL # no longer required
# integrating markers and alleles (like ref and alt for bi-allelic data)
fst.prep %<>%
dplyr::distinct(MARKERS, ALLELES) %>%
dplyr::left_join(count.locus, by = "MARKERS")
count.locus <- NULL
# Not so bad part ----
fst.prep %<>%
dplyr::full_join(
fa %<>%
dplyr::group_by(MARKERS, ALLELES) %>%
dplyr::mutate(FREQ_AL = sum(n) / sum(NAPL)) %>%
dplyr::ungroup(.)
, by = c("MARKERS", "ALLELES")
)
fa <- NULL
fst.prep %<>%
dplyr::mutate(