/
tree-sequences.R
2978 lines (2625 loc) Β· 115 KB
/
tree-sequences.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
# tree sequence processing ------------------------------------------------
#' Load a tree sequence file produced by a given model
#'
#' This function loads a tree sequence file simulated from a given slendr model.
#' Optionally, the tree sequence can be recapitated and simplified.
#'
#' The loading, recapitation and simplification is performed using the Python
#' module pyslim which serves as a link between tree sequences generated by SLiM
#' and the tskit module for manipulation of tree sequence data. All of these
#' steps have been modelled after the official pyslim tutorial and documentation
#' available at: <https://tskit.dev/pyslim/docs/latest/tutorial.html>.
#'
#' The recapitation and simplification steps can also be performed individually
#' using the functions \code{\link{ts_recapitate}} and
#' \code{\link{ts_simplify}}.
#'
#' @param file A path to the tree-sequence file (either originating from a
#' slendr model or a standard non-slendr tree sequence).
#' @param model Optional \code{slendr_model} object which produced the
#' tree-sequence \code{file}. Used for adding various annotation data and
#' metadata to the standard tskit tree-sequence object.
#'
#' @return Tree-sequence object of the class \code{slendr_ts}, which serves as
#' an interface point for the Python module tskit using slendr functions with
#' the \code{ts_} prefix.
#'
#' @seealso \code{\link{ts_nodes}} for extracting useful information about
#' individuals, nodes, coalescent times and geospatial locations of nodes on a
#' map
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' # load tree sequence generated by a given model
#' ts <- ts_load(slendr_ts, model)
#'
#' # even tree sequences generated by non-slendr models can be
#' msprime_ts <- system.file("extdata/models/msprime.trees", package = "slendr")
#' ts <- ts_load(msprime_ts)
#'
#' # load tree sequence and immediately simplify it only to sampled individuals
#' # (note that the example tree sequence is already simplified so this operation
#' # does not do anything in this case)
#' ts <- ts_load(slendr_ts, model = model) %>% ts_simplify(keep_input_roots = TRUE)
#'
#' # load tree sequence and simplify it to a subset of sampled individuals
#' ts_small <- ts_simplify(ts, simplify_to = c("CH_1", "NEA_1", "NEA_2",
#' "AFR_1", "AFR_2", "EUR_1", "EUR_2"))
#'
#' # load tree sequence, recapitate it and simplify it
#' ts <- ts_load(slendr_ts, model) %>%
#' ts_recapitate(recombination_rate = 1e-8, Ne = 10000, random_seed = 42) %>%
#' ts_simplify()
#'
#' # load tree sequence, recapitate it, simplify it and overlay neutral mutations
#' ts <- ts_load(slendr_ts, model) %>%
#' ts_recapitate(recombination_rate = 1e-8, Ne = 10000, random_seed = 42) %>%
#' ts_simplify() %>%
#' ts_mutate(mutation_rate = 1e-8)
#'
#' ts
#' @export
ts_load <- function(file, model = NULL) {
# load the tree sequence, converting it to a SLiM tree sequence if necessary
ts <- if (is.character(file)) tskit$load(path.expand(file)) else file
if (length(ts$metadata) == 0 || is.null(ts$metadata$SLiM))
type <- "generic"
else
type <- "SLiM"
attr(ts, "type") <- type
attr(ts, "model") <- model
attr(ts, "spatial") <- type == "SLiM" && ts$metadata$SLiM$spatial_dimensionality != ""
if (attr(ts, "spatial")) check_spatial_pkgs()
attr(ts, "metadata") <- get_slendr_metadata(ts)
attr(ts, "recapitated") <- FALSE
attr(ts, "simplified") <- FALSE
attr(ts, "mutated") <- FALSE
class(ts) <- c("slendr_ts", class(ts))
# Extract "raw" tree sequence tables -- these can be later accessed via
# ts_table(ts, "<nodes|edges|individuals|mutations>") but note that these are
# not necessary for standard slendr data analysis. For that purpose, the
# annotated tables provided by ts_nodes() and ts_edges() are more useful.
attr(ts, "raw_nodes") <- get_ts_raw_nodes(ts)
attr(ts, "raw_edges") <- get_ts_raw_edges(ts)
attr(ts, "raw_individuals") <- get_ts_raw_individuals(ts)
attr(ts, "raw_mutations") <- get_ts_raw_mutations(ts)
attr(ts, "nodes") <- if (type == "SLiM") get_pyslim_table_data(ts) else get_tskit_table_data(ts)
# if the tree sequence was loaded from a file, save the path
if (is.character(file)) attr(ts, "path") <- normalizePath(file)
ts
}
#' Save a tree sequence to a file
#'
#' @param ts Tree sequence object loaded by \code{ts_load}
#' @param file File to which the tree sequence should be saved
#'
#' @return No return value, called for side effects
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' # load the tree sequence
#' ts <- ts_load(slendr_ts, model)
#'
#' # save the tree-sequence object to a different location
#' another_file <- paste(tempfile(), ".trees")
#' ts_save(ts, another_file)
#' @export
ts_save <- function(ts, file) {
check_ts_class(ts)
type <- attr(ts, "type")
from_slendr <- !is.null(attr(ts, "model"))
# overwrite the original list of sample names (if the tree sequence was simplified
# down to a smaller number of individuals than originally sampled)
if (from_slendr && nrow(ts_samples(ts)) != nrow(attr(ts, "metadata")$sampling)) {
tables <- ts$dump_tables()
tables$metadata_schema = tskit$MetadataSchema(list("codec" = "json"))
sample_names <- attr(ts, "metadata")$sample_names
pedigree_ids <- attr(ts, "metadata")$sample_ids
if (type == "SLiM") {
tables$metadata$SLiM$user_metadata$slendr[[1]]$sample_names <- sample_names
tables$metadata$SLiM$user_metadata$slendr[[1]]$sample_ids <- pedigree_ids
} else
tables$metadata$slendr$sample_names <- sample_names
# put the tree sequence object back together
ts <- tables$tree_sequence()
}
ts$dump(path.expand(file))
}
#' Recapitate the tree sequence
#'
#' @param ts Tree sequence object loaded by \code{ts_load}
#' @param recombination_rate A constant value of the recombination rate
#' @param Ne Effective population size during the recapitation process
#' @param demography Ancestral demography to be passed internally to
#' \code{msprime.sim_ancestry()} (see msprime's documentation for mode detail)
#' @param random_seed Random seed passed to pyslim's \code{recapitate} method
#'
#' @return Tree-sequence object of the class \code{slendr_ts}, which serves as
#' an interface point for the Python module tskit using slendr functions with
#' the \code{ts_} prefix.
#'
#' @seealso \code{\link{ts_nodes}} for extracting useful information about
#' individuals, nodes, coalescent times and geospatial locations of nodes on a
#' map
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' ts <- ts_load(slendr_ts, model) %>%
#' ts_recapitate(recombination_rate = 1e-8, Ne = 10000, random_seed = 42)
#'
#' ts
#' @export
ts_recapitate <- function(ts, recombination_rate, Ne = NULL, demography = NULL, random_seed = NULL) {
check_ts_class(ts)
if ((is.null(Ne) & is.null(demography)) | !is.null(Ne) & !is.null(demography))
stop("Either ancestral Ne or demography (but not both) must be specified for\n",
"recapitation. See documentation of pyslim.recapitate for more detail.", call. = FALSE)
model <- attr(ts, "model")
type <- attr(ts, "type")
spatial <- attr(ts, "spatial")
if (type == "SLiM") {
if (!is.null(Ne))
ts_new <- pyslim$recapitate(
ts,
recombination_rate = recombination_rate,
ancestral_Ne = Ne,
random_seed = random_seed
)
else
ts_new <- pyslim$recapitate(
ts,
recombination_rate = recombination_rate,
demography = demography,
random_seed = random_seed
)
} else {
warning("There is no need to recapitate an already coalesced msprime tree sequence",
call. = FALSE)
ts_new <- ts
}
# copy attributes over to the new tree-sequence object or generate updates
# ones where necessary
attr(ts_new, "model") <- model
attr(ts_new, "type") <- type
attr(ts_new, "spatial") <- spatial
attr(ts_new, "metadata") <- attr(ts, "metadata")
attr(ts_new, "recapitated") <- TRUE
attr(ts_new, "simplified") <- attr(ts, "simplified")
attr(ts_new, "mutated") <- attr(ts, "mutated")
attr(ts_new, "raw_nodes") <- get_ts_raw_nodes(ts_new)
attr(ts_new, "raw_edges") <- get_ts_raw_edges(ts_new)
attr(ts_new, "raw_individuals") <- get_ts_raw_individuals(ts_new)
attr(ts_new, "raw_mutations") <- get_ts_raw_mutations(ts_new)
attr(ts_new, "path") <- attr(ts, "path")
if (type == "SLiM") {
# inherit the information about which individuals should be marked as
# explicitly "sampled" from the previous tree sequence object (if that
# was specified) -- this is only necessary for a SLiM sequence
# TODO: no longer necessary
old_individuals <- attr(ts, "raw_individuals")
sampled_ids <- old_individuals[old_individuals$sampled, ]$pedigree_id
attr(ts_new, "raw_individuals") <- attr(ts_new, "raw_individuals") %>%
dplyr::mutate(sampled = pedigree_id %in% sampled_ids)
}
attr(ts_new, "nodes") <- if (type == "SLiM") get_pyslim_table_data(ts_new) else get_tskit_table_data(ts_new)
class(ts_new) <- c("slendr_ts", class(ts_new))
ts_new
}
#' Simplify the tree sequence down to a given set of individuals
#'
#' This function is a convenience wrapper around the \code{simplify} method
#' implemented in tskit, designed to work on tree sequence data simulated by
#' SLiM using the \pkg{slendr} R package.
#'
#' The simplification process is used to remove redundant information from the
#' tree sequence and retains only information necessary to describe the
#' genealogical history of a set of samples.
#'
#' For more information on how simplification works in pyslim and tskit, see the
#' official documentation at
#' <https://tskit.dev/tskit/docs/stable/python-api.html#tskit.TreeSequence.simplify>
#' and <https://tskit.dev/pyslim/docs/latest/tutorial.html#simplification>.
#'
#' A very clear description of the difference between remembering and retaining
#' and how to use these techniques to implement historical individuals (i.e.
#' ancient DNA samples) is in the pyslim documentation at
#' <https://tskit.dev/pyslim/docs/latest/tutorial.html#historical-individuals>.
#'
#' @param ts Tree sequence object of the class \code{slendr_ts}
#' @param simplify_to A character vector of individual names. If NULL, all
#' explicitly remembered individuals (i.e. those specified via the
#' \code{\link{schedule_sampling}} function will be left in the tree sequence
#' after the simplification.
#' @param keep_input_roots Should the history ancestral to the MRCA of all
#' samples be retained in the tree sequence? Default is \code{FALSE}.
#' @param keep_unary Should unary nodes be preserved through simplification?
#' Default is \code{FALSE}.
#' @param keep_unary_in_individuals Should unary nodes be preserved through
#' simplification if they are associated with an individual recorded in
#' the table of individuals? Default is \code{FALSE}. Cannot be set to
#' \code{TRUE} if \code{keep_unary} is also TRUE
#' @param filter_nodes Should nodes be reindexed after simplification? Default is
#' \code{TRUE}. See tskit's documentation for the Python method \code{simplify()}
# for more detail.
#'
#' @return Tree-sequence object of the class \code{slendr_ts}, which serves as
#' an interface point for the Python module tskit using slendr functions with
#' the \code{ts_} prefix.
#'
#' @seealso \code{\link{ts_nodes}} for extracting useful information about
#' individuals, nodes, coalescent times and geospatial locations of nodes on a
#' map
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' ts <- ts_load(slendr_ts, model)
#' ts
#'
#' # simplify tree sequence to sampled individuals
#' ts_simplified <- ts_simplify(ts)
#'
#' # simplify to a subset of sampled individuals
#' ts_small <- ts_simplify(ts, simplify_to = c("CH_1", "NEA_1", "NEA_2", "AFR_1",
#' "AFR_2", "EUR_1", "EUR_2"))
#'
#' ts_small
#' @export
ts_simplify <- function(ts, simplify_to = NULL, keep_input_roots = FALSE,
keep_unary = FALSE, keep_unary_in_individuals = FALSE,
filter_nodes = TRUE) {
check_ts_class(ts)
model <- attr(ts, "model")
type <- attr(ts, "type")
spatial <- attr(ts, "spatial")
from_slendr <- !is.null(model)
if (!attr(ts, "recapitated") && !keep_input_roots && !ts_coalesced(ts))
warning("Simplifying a non-recapitated tree sequence. Make sure this is what you really want",
call. = FALSE)
data <- attr(ts, "nodes")
if (is.null(simplify_to)) { # no individuals/nodes were given to guide the simplification
samples <- dplyr::filter(data, sampled)$node_id # simplify to all sampled nodes
} else if (is.character(simplify_to)) { # a vector of slendr individual names was given
if (!from_slendr)
stop("Symbolic character names can only be provided for slendr-generated\n",
"tree sequences", call. = FALSE)
if (!all(simplify_to %in% data$name))
stop("The following individuals are not present in the tree sequence: ",
paste0(simplify_to[!simplify_to %in% data$name], collapse = ", "),
call. = FALSE)
samples <- dplyr::filter(data, name %in% simplify_to)$node_id
} else if (is.numeric(simplify_to)) {
if (!all(simplify_to %in% data$node_id))
stop("The following nodes are not among sampled nodes: ",
paste0(simplify_to[!simplify_to %in% data$node_id], collapse = ", "),
call. = FALSE)
samples <- simplify_to
} else
stop("Unknown type of simplification nodes", call. = FALSE)
ts_new <- ts$simplify(as.integer(samples),
filter_populations = FALSE,
filter_nodes = filter_nodes,
keep_input_roots = keep_input_roots,
keep_unary = keep_unary,
keep_unary_in_individuals = keep_unary_in_individuals)
# copy attributes over to the new tree-sequence object or generate updates
# ones where necessary
attr(ts_new, "model") <- model
attr(ts_new, "type") <- type
attr(ts_new, "spatial") <- spatial
attr(ts_new, "metadata") <- attr(ts, "metadata")
attr(ts_new, "recapitated") <- attr(ts, "recapitated")
attr(ts_new, "simplified") <- TRUE
attr(ts_new, "mutated") <- attr(ts, "mutated")
attr(ts_new, "raw_nodes") <- get_ts_raw_nodes(ts_new)
attr(ts_new, "raw_edges") <- get_ts_raw_edges(ts_new)
attr(ts_new, "raw_individuals") <- get_ts_raw_individuals(ts_new)
attr(ts_new, "raw_mutations") <- get_ts_raw_mutations(ts_new)
# use pedigree IDs to cross-check the original data with simplified table
if (type == "SLiM") {
# mark only explicitly simplified individuals as "focal"
sample_ids <- data[data$node_id %in% samples, ]$pedigree_id
attr(ts_new, "raw_individuals")$sampled <-
attr(ts_new, "raw_individuals")$pedigree_id %in% sample_ids
# get the name and location from the original table with the pedigree_id key
cols <- c("pedigree_id", "pop")
if (from_slendr) cols <- c(cols, "name")
if (spatial) cols <- c(cols, "location")
# we need to deduplicate the rows because the table is stored in a long format
# (but we removed the node_id column which each diploid individual has two
# values of)
keep_data <- data[, cols] %>% dplyr::filter(!duplicated(pedigree_id))
# get node IDs of individuals present in the simplified tree sequence
# (sort by individual ID and time)
nodes_new <- get_ts_raw_nodes(ts_new) %>%
dplyr::arrange(ind_id, time) %>%
dplyr::select(node_id, ind_id) %>%
.$node_id
location_col <- if (spatial) "location" else NULL
# get other data about individuals in the simplified tree sequence, sort them
# also by their IDs and times, and add their node IDs extracted above
# (this works because we sorted both in the same way)
data_new <- get_pyslim_table_data(ts_new, simplify_to) %>%
as.data.frame() %>%
dplyr::arrange(ind_id, time) %>%
dplyr::select(pop_id, ind_id, pedigree_id, time, time_tskit, sampled, remembered, retained, alive) %>%
dplyr::inner_join(keep_data, by = "pedigree_id") %>%
dplyr::mutate(node_id = nodes_new) %>%
dplyr::as_tibble()
if (spatial)
data_new <- sf::st_as_sf(data_new, crs = sf::st_crs(data))
name_col <- if (from_slendr) "name" else NULL
attr(ts_new, "nodes") <- data_new[, c(name_col, "pop", "node_id",
"time", "time_tskit", location_col, "sampled", "remembered",
"retained", "alive", "pedigree_id", "ind_id", "pop_id")]
} else
attr(ts_new, "nodes") <- get_tskit_table_data(ts_new, simplify_to)
attr(ts_new, "path") <- attr(ts, "path")
# replace the names of sampled individuals (if simplification led to subsetting)
if (from_slendr) {
sampled_nodes <- attr(ts_new, "nodes") %>% dplyr::filter(sampled)
attr(ts_new, "metadata")$sample_names <- unique(sampled_nodes$name)
if (type == "SLiM")
attr(ts_new, "metadata")$sample_ids <- unique(sampled_nodes$pedigree_id)
}
class(ts_new) <- c("slendr_ts", class(ts_new))
ts_new
}
#' Add mutations to the given tree sequence
#'
#' @param ts Tree sequence object of the class \code{slendr_ts}
#' @param mutation_rate Mutation rate used by msprime to simulate mutations
#' @param random_seed Random seed passed to msprime's \code{mutate} method
#' @param keep_existing Keep existing mutations?
#' @param mut_type Assign SLiM mutation type to neutral mutations? If
#' \code{NULL} (default), no special mutation type will be used. If an
#' integer number is given, mutations of the SLiM mutation type with that
#' integer identifier will be created.
#'
#' @return Tree-sequence object of the class \code{slendr_ts}, which serves as
#' an interface point for the Python module tskit using slendr functions with
#' the \code{ts_} prefix.
#'
#' @seealso \code{\link{ts_nodes}} for extracting useful information about
#' individuals, nodes, coalescent times and geospatial locations of nodes on a
#' map
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' ts <- ts_load(slendr_ts, model)
#' ts_mutate <- ts_mutate(ts, mutation_rate = 1e-8, random_seed = 42)
#'
#' ts_mutate
#' @export
ts_mutate <- function(ts, mutation_rate, random_seed = NULL,
keep_existing = TRUE, mut_type = NULL) {
check_ts_class(ts)
if (attr(ts, "mutated")) stop("Tree sequence already mutated", call. = FALSE)
if (is.numeric(mut_type) && attr(ts, "type") == "SLiM")
mut_type <- msp$SLiMMutationModel(type = as.integer(mut_type))
ts_new <-
msp$sim_mutations(
ts,
rate = mutation_rate,
model = mut_type,
keep = keep_existing,
random_seed = random_seed
)
# copy attributes over to the new tree-sequence object or generate updates
# ones where necessary
attr(ts_new, "model") <- attr(ts, "model")
attr(ts_new, "type") <- attr(ts, "type")
attr(ts_new, "spatial") <- attr(ts, "spatial")
attr(ts_new, "metadata") <- attr(ts, "metadata")
attr(ts_new, "recapitated") <- attr(ts, "recapitated")
attr(ts_new, "simplified") <- attr(ts, "simplified")
attr(ts_new, "mutated") <- TRUE
attr(ts_new, "raw_nodes") <- attr(ts, "raw_nodes")
attr(ts_new, "raw_edges") <- attr(ts, "raw_edges")
attr(ts_new, "raw_individuals") <- attr(ts, "raw_individuals")
attr(ts_new, "raw_mutations") <- get_ts_raw_mutations(ts_new)
attr(ts_new, "nodes") <- attr(ts, "nodes")
attr(ts_new, "path") <- attr(ts, "path")
class(ts_new) <- c("slendr_ts", class(ts_new))
ts_new
}
#' Extract list with tree sequence metadata saved by SLiM
#'
#' @param ts Tree sequence object of the class \code{slendr_ts}
#'
#' @return List of metadata fields extracted from the tree-sequence object
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' # load the tree-sequence object from disk
#' ts <- ts_load(slendr_ts, model)
#'
#' # extract the list of metadata information from the tree sequence
#' ts_metadata(ts)
#' @export
ts_metadata <- function(ts) {
check_ts_class(ts)
attr(ts, "metadata")
}
# output formats ----------------------------------------------------------
#' Extract genotype table from the tree sequence
#'
#' @param ts Tree sequence object of the class \code{slendr_ts}
#'
#' @return Data frame object of the class \code{tibble} containing genotypes
#' of simulated individuals in columns
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' # load the tree-sequence object from disk, recapitate it, simplify it, and mutate it
#' ts <- ts_load(slendr_ts, model) %>%
#' ts_recapitate(Ne = 10000, recombination_rate = 1e-8) %>%
#' ts_simplify() %>%
#' ts_mutate(mutation_rate = 1e-8)
#'
#' # extract the genotype matrix (this could take a long time consume lots
#' # of memory!)
#' gts <- ts_genotypes(ts)
#' @export
ts_genotypes <- function(ts) {
if (!attr(ts, "mutated"))
stop("Extracting genotypes from a tree sequence which has not been mutated",
call. = FALSE)
type <- attr(ts, "type")
data <- ts_nodes(ts)
gts <- ts$genotype_matrix()
positions <- ts$tables$sites$position
biallelic_pos <- get_biallelic_indices(ts)
n_multiallelic <- sum(!biallelic_pos)
if (n_multiallelic > 0) {
message(sprintf("%i multiallelic sites (%.3f%% out of %i total) detected and removed",
n_multiallelic, n_multiallelic / length(positions) * 100,
length(positions)))
gts <- gts[biallelic_pos, ]
positions <- positions[biallelic_pos]
}
chromosomes <- ts_nodes(ts) %>%
dplyr::filter(!is.na(name)) %>%
dplyr::as_tibble() %>%
dplyr::mutate(chr_name = sprintf("%s_chr%i", name, 1:2)) %>%
dplyr::select(chr_name, node_id) %>%
dplyr::arrange(node_id)
colnames(gts) <- chromosomes$chr_name
dplyr::as_tibble(gts) %>%
dplyr::mutate(pos = as.integer(positions)) %>%
dplyr::select(pos, dplyr::everything())
}
#' Convert genotypes to the EIGENSTRAT file format
#'
#' EIGENSTRAT data produced by this function can be used by the admixr R package
#' (<https://bodkan.net/admixr/>).
#'
#' In case an outgroup was not formally specified in a slendr model which
#' generated the tree sequence data, it is possible to artificially create an
#' outgroup sample with the name specified by the \code{outgroup} argument,
#' which will carry all ancestral alleles (i.e. value "2" in a geno file
#' for each position in a snp file).
#'
#' @param ts Tree sequence object of the class \code{slendr_ts}
#' @param prefix EIGENSTRAT trio prefix
#' @param chrom The name of the chromosome in the EIGENSTRAT snp file
#' (default "chr1")
#' @param outgroup Should a formal, artificial outgroup be added? If \code{NULL}
#' (default), no outgroup is added. A non-NULL character name will serve as
#' the name of the outgroup in an ind file.
#'
#' @return Object of the class EIGENSTRAT created by the admixr package
#'
#' @export
ts_eigenstrat <- function(ts, prefix, chrom = "chr1", outgroup = NULL) {
if (!requireNamespace("admixr", quietly = TRUE))
message("For EIGENSTRAT conversion, please install the R package ",
"admixr by calling `install.packages(\"admixr\")")
if (!attr(ts, "recapitated") && !ts_coalesced(ts))
stop("Tree sequence was not recapitated and some nodes do not ",
"have parents over some portion of their genome. This is interpreted as ",
"missing data, which is not currently supported. For more context, take ",
"a look at <https://github.com/tskit-dev/tskit/issues/301#issuecomment-520990038>.",
call. = FALSE)
if (!attr(ts, "mutated"))
stop("Attempting to extract genotypes from a tree sequence which has not been mutated",
call. = FALSE)
chrom_genotypes <- ts_genotypes(ts)
chr1_genotypes <- dplyr::select(chrom_genotypes, dplyr::ends_with("_chr1"))
chr2_genotypes <- dplyr::select(chrom_genotypes, dplyr::ends_with("_chr2"))
# create a geno file table
geno <- dplyr::as_tibble(2 - (chr1_genotypes + chr2_genotypes))
individuals <- gsub("_chr.", "", colnames(geno))
colnames(geno) <- individuals
# create an ind file table
ind <- dplyr::tibble(id = individuals, sex = "U", label = individuals)
# create a snp file table
positions <- chrom_genotypes$pos
snp <- dplyr::tibble(
id = sprintf("%s_%s", chrom, as.character(positions)),
chrom = chrom,
gen = 0.0,
pos = positions,
ref = "G",
alt = "T"
)
# add an artificial outgroup individual carrying ancestral alleles only
if (!is.null(outgroup)) {
geno[[as.character(outgroup)]] <- 2
ind <- data.frame(
id = as.character(outgroup),
sex = "U",
label = as.character(outgroup)
) %>%
dplyr::bind_rows(ind, .)
}
# save the EIGENSTRAT trio
if (!dir.exists(dirname(prefix))) dir.create(dirname(prefix))
admixr::write_geno(geno, paste0(prefix, ".geno"))
admixr::write_snp(snp, paste0(prefix, ".snp"))
admixr::write_ind(ind, paste0(prefix, ".ind"))
# return the admixr eigenstrat object
admixr::eigenstrat(prefix = prefix)
}
#' Save genotypes from the tree sequence as a VCF file
#'
#' @param ts Tree sequence object of the class \code{slendr_ts}
#' @param path Path to a VCF file
#' @param chrom Chromosome name to be written in the CHROM column of the VCF
#' @param individuals A character vector of individuals in the tree sequence. If
#' missing, all individuals present in the tree sequence will be saved.
#'
#' @return No return value, called for side effects
#'
#' @export
ts_vcf <- function(ts, path, chrom = NULL, individuals = NULL) {
if (!attr(ts, "recapitated") && !ts_coalesced(ts))
stop("Tree sequence was not recapitated and some nodes do not ",
"have parents over some portion of their genome. This is interpreted as ",
"missing data, which is not currently supported by tskit. For more context, ",
"take a look at <https://github.com/tskit-dev/tskit/issues/301#issuecomment-520990038>.",
call. = FALSE)
if (!attr(ts, "mutated"))
stop("Attempting to extract genotypes from a tree sequence which has not been mutated",
call. = FALSE)
data <- ts_nodes(ts) %>%
dplyr::filter(!is.na(name)) %>%
dplyr::as_tibble() %>%
dplyr::distinct(name, ind_id)
if (is.null(individuals)) individuals <- data$name
present <- individuals %in% unique(data$name)
if (!all(present))
stop("", paste(individuals[!present], collapse = ", "),
" not present in the tree sequence", call. = FALSE)
gzip <- reticulate::import("gzip")
with(reticulate::`%as%`(gzip$open(path.expand(path), "wt"), vcf_file), {
ts$write_vcf(vcf_file,
contig_id = chrom,
individuals = as.integer(data$ind_id),
individual_names = data$name)
})
}
#' Convert a tree in the tree sequence to an object of the class \code{phylo}
#'
#' @inheritParams ts_tree
#' @param labels What should be stored as node labels in the final \code{phylo}
#' object? Options are either a population name or a tskit integer node ID
#' (which is a different thing from a \code{phylo} class node integer index).
#' @param quiet Should ape's internal phylo validity test be printed out?
#'
#' @return Standard phylogenetic tree object implemented by the R package ape
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' # load the tree-sequence object from disk
#' ts <- ts_load(slendr_ts, model) %>%
#' ts_recapitate(Ne = 10000, recombination_rate = 1e-8) %>%
#' ts_simplify()
#'
#' # extract the 1st tree from a given tree sequence, return ape object
#' tree <- ts_phylo(ts, i = 1, mode = "index", quiet = TRUE)
#' tree
#'
#' # extract the tree at a 42th basepair in the given tree sequence
#' tree <- ts_phylo(ts, i = 42, mode = "position", quiet = TRUE)
#'
#' # because the tree is a standard ape phylo object, we can plot it easily
#' plot(tree, use.edge.length = FALSE)
#' ape::nodelabels()
#' @export
ts_phylo <- function(ts, i, mode = c("index", "position"),
labels = c("tskit", "pop"), quiet = FALSE) {
labels <- match.arg(labels)
from_slendr <- !is.null(attr(ts, "model"))
tree <- ts_tree(ts, i, mode)
if (tree$num_roots > 1)
stop("A tree sequence tree which is not fully coalesced or recapitated\n",
"cannot be converted to an R phylo tree representation (see the help\n",
"page of ?ts_recapitate for more details)", call. = FALSE)
if (!attr(ts, "simplified") && attr(ts, "type") != "generic")
stop("Please simplify your tree sequence first before converting a tree to\n",
"an R phylo tree object format (see the help page of ?ts_simplify for\n",
"more details)", call. = FALSE)
# get tree sequence nodes which are present in the tskit tree object
# (tree$preorder() just get the numerical node IDs, nothing else)
data <- ts_nodes(ts) %>%
dplyr::as_tibble() %>%
dplyr::filter(node_id %in% tree$preorder())
model <- attr(ts, "model")
type <- attr(ts, "type")
spatial <- attr(ts, "spatial")
if (from_slendr)
direction <- model$direction
else
direction <- "backward"
if (direction == "forward")
data <- dplyr::arrange(data, sampled, time)
else
data <- dplyr::arrange(data, sampled, -time)
# convert the edge table to a proper ape phylo object
# see http://ape-package.ird.fr/misc/FormatTreeR.pdf for more details
n_tips <- sum(data$sampled, na.rm = TRUE)
n_internal <- nrow(data) - n_tips
n_all <- n_internal + n_tips; stopifnot(n_all == nrow(data))
present_ids <- data$node_id
# design a lookup table of consecutive integer numbers (reversing it because
# in the ordered tree sequence table of nodes `data`, the sampled nodes which
# will become the tips of the tree are at the end)
lookup_ids <- rev(seq_along(present_ids))
tip_labels <- dplyr::filter(data, sampled) %>%
{ if (from_slendr) sprintf("%s (%s)", .$node_id, .$name) else .$node_id } %>%
as.character() %>%
rev()
# flip the index of the root in the lookup table
lookup_ids[length(lookup_ids) - n_tips] <- lookup_ids[1]
lookup_ids[1] <- n_tips + 1
child_ids <- present_ids[present_ids != tree$root]
parent_ids <- sapply(child_ids, function(i) tree$parent(i))
children <- sapply(child_ids, function(n) lookup_ids[present_ids == n])
parents <- sapply(parent_ids, function(n) lookup_ids[present_ids == n])
# find which sampled nodes are not leaves:
# - first look for those nodes in the tree sequence node IDs
internal_ts_samples <- intersect(parent_ids, data[data$sampled, ]$node_id)
# - then convert them to the phylo numbering
internal_phylo_samples <- sapply(internal_ts_samples, function(n) lookup_ids[present_ids == n])
# and then link them to dummy internal nodes, effectively turning them into
# proper leaves
dummies <- vector(mode = "integer", length(internal_ts_samples))
if (length(dummies) > 0)
warning("Some sampled nodes in the tree are internal nodes (i.e. represent ancestors\n",
"of some sampled nodes forming the tips of the tree). This is not permitted\n",
"by standard phylogenetic tree framework such as that implemented by the ape\n",
"R package, which assumes that samples are present at the tips of a tree.\n",
"To circumvent this problem, these sampled internal nodes have been\n",
"attached to the tree via zero-length branches linking them to 'dummy' nodes.\n",
"In total ", length(dummies), " of such nodes have been created and they are ",
"indicated by `phylo_id`\nvalues larger than ", n_all, ".", call. = FALSE)
for (d in seq_along(dummies)) {
ts_node <- as.integer(internal_ts_samples[d])
phylo_node <- as.integer(internal_phylo_samples[d])
dummy <- n_all + d
node_parent <- lookup_ids[present_ids == tree$parent(ts_node)]
node_children <- sapply(unlist(tree$children(ts_node)), function(n) lookup_ids[present_ids == n])
# replace the sampled node with a dummy node, linking to its parent and
# children (all done in the phylo index space)
parents[children %in% node_children] <- dummy
children[children == phylo_node] <- dummy
# add a new link from the dummy node to the real sample
children <- c(children, phylo_node)
parents <- c(parents, dummy)
dummies[d] <- dummy
}
# bind the two columns back into an edge matrix
edge <- cbind(as.integer(parents), as.integer(children))
# create vector of edge lengths (adding zero-length branches linking the dummy
# nodes)
children_times <- sapply(child_ids, function(n) data[data$node_id == n, ]$time)
parent_times <- sapply(parent_ids, function(n) data[data$node_id == n, ]$time)
edge_lengths <- c(abs(parent_times - children_times), rep(0, length(dummies)))
data$phylo_id <- sapply(data$node_id, function(n) lookup_ids[present_ids == n])
columns <- c()
if (type == "SLiM") {
if (spatial) columns <- c(columns, "location")
columns <- c(columns, c("sampled", "remembered", "retained", "alive", "pedigree_id"))
} else
columns <- "sampled"
name_col <- if (from_slendr) "name" else NULL
data <- dplyr::select(
data, !!name_col, pop, node_id, phylo_id, time, time_tskit, !!columns, ind_id, pop_id
)
# add fake dummy information to the processed tree sequence table so that
# the user knows what is real and what is not straight from the ts_phylo()
# output
if (length(dummies)) {
data <- dplyr::bind_rows(
data,
data.frame(
name = NA,
pop = sapply(internal_ts_samples,
function(n) data[data$node_id == n, ]$pop),
node_id = NA, phylo_id = dummies,
time = sapply(internal_ts_samples,
function(n) data[data$node_id == n, ]$time),
time_tskit = sapply(internal_ts_samples,
function(n) data[data$node_id == n, ]$time_tskit)
)
)
}
if (type == "SLiM" && spatial) {
check_spatial_pkgs()
data <- sf::st_as_sf(data)
}
class(data) <- set_class(data, "nodes")
# generate appropriate internal node labels based on the user's choice
elem <- if (labels == "pop") "pop" else "node_id"
node_labels <- purrr::map_chr(unique(sort(parents)),
~ as.character(data[data$phylo_id == .x, ][[elem]]))
tree <- list(
edge = edge,
edge.length = edge_lengths,
node.label = node_labels,
tip.label = tip_labels,
Nnode = n_internal + length(dummies)
)
class(tree) <- c("slendr_phylo", "phylo")
check_log <- utils::capture.output(ape::checkValidPhylo(tree))
# if there are fatal issues, report them and signal an error
if (any(grepl("FATAL", check_log)))
stop(paste(check_log, collapse = "\n"), call. = FALSE)
if (!quiet) cat(check_log, sep = "\n")
# subset ts_nodes result to only those nodes that are present in the phylo
# object, adding another column with the rearranged node IDs
attr(tree, "model") <- attr(ts, "model")
attr(tree, "ts") <- ts
attr(tree, "spatial") <- attr(ts, "spatial")
attr(tree, "nodes") <- data
attr(tree, "edges") <- get_annotated_edges(tree)
attr(tree, "type") <- attr(ts, "type")
tree
}
# tree sequence tables ----------------------------------------------------
#' Extract combined annotated table of individuals and nodes
#'
#' This function combines information from the table of individuals and table of
#' nodes into a single data frame which can be used in downstream analyses.
#'
#' The source of data (tables of individuals and nodes recorded in the tree
#' sequence generated by SLiM) are combined into a single data frame. If the
#' model which generated the data was spatial, coordinates of nodes (which are
#' pixel-based by default because SLiM spatial simulations occur on a raster),
#' the coordinates are automatically converted to an explicit spatial object of
#' the \code{sf} class unless \code{spatial = FALSE}. See
#' <https://r-spatial.github.io/sf/> for an extensive introduction to the sf
#' package and the ways in which spatial data can be processed, analysed, and
#' visualised.
#'
#' @seealso \code{\link{ts_table}} for accessing raw tree sequence tables
#' without added metadata annotation. See also \code{\link{ts_ancestors}} to
#' learn how to extract information about relationship beteween nodes in the
#' tree sequence, and how to analysed data about distances between nodes in
#' the spatial context.
#'
#' @param x Tree sequence object of the class \code{slendr_ts} or a \code{phylo}
#' object extracted by \code{ts_phylo}
#' @param sf Should spatial data be returned in an sf format? If \code{FALSE},
#' spatial geometries will be returned simply as x and y columns, instead of
#' the standard POINT data type.
#'
#' @return Data frame with processed information from the tree sequence object.
#' If the model which generated this data was spatial, result will be returned
#' as a spatial object of the class \code{sf}.
#'
#' @examples
#' \dontshow{check_dependencies(python = TRUE, quit = TRUE) # dependencies must be present
#' }
#' init_env()
#'
#' # load an example model with an already simulated tree sequence
#' slendr_ts <- system.file("extdata/models/introgression.trees", package = "slendr")
#' model <- read_model(path = system.file("extdata/models/introgression", package = "slendr"))
#'
#' # load the tree-sequence object from disk
#' ts <- ts_load(slendr_ts, model)