-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslides_slendr.qmd
More file actions
1847 lines (907 loc) · 28.4 KB
/
slides_slendr.qmd
File metadata and controls
1847 lines (907 loc) · 28.4 KB
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
---
format: ### slides
revealjs: ### slides
echo: true ### slides
code-line-numbers: false ### slides
fig-align: center ### slides
slide-number: true ### slides
self-contained: true ### slides
---
```{r}
#| echo: false
library(slendr)
init_env(quiet = TRUE)
```
# Simulations with _slendr_
# Why use simulations?
#
::: {.columns}
::: {.column width="70%"}
> Many problems in population genetics cannot be solved by a mathematician,
no matter how gifted. \[It\] is already clear that computer methods are very
powerful. This is good. It \[...\] permits people with limited mathematical
knowledge to work on important problems \[...\].
:::
::: {.column width="30%"}

[James F. Crow](https://en.wikipedia.org/wiki/James_F._Crow) -- [interview](http://www.gnxp.com/blog/2006/06/10-questions-for-jim-crow.php)
:::
:::
# Why use simulations?
1. Developing intuition into statistics
2. Estimating model parameters
3. Ground truth for method development
## Developing intuition into statistics
<center></center>
::: {.aside}
<small>Image from [Peter (2016)](https://academic.oup.com/genetics/article/202/4/1485/5930214)</small>
:::
## Developing intuition into statistics
<center></center>
::: {.aside}
<small>Image from [Lawson _et al._ (2018)](https://www.nature.com/articles/s41467-018-05257-7)</small>
:::
## Estimating model parameters (i.e. [ABC](https://en.wikipedia.org/wiki/Approximate_Bayesian_computation))
<center>{width="50%"}</center>
::: {.aside}
<small>Image from [Wikipedia on ABC](https://en.wikipedia.org/wiki/Approximate_Bayesian_computation)</small>
:::
## Ground truth for method development
<center></center>
::: {.aside}
<small>Image from [Schiffels and Durbin (2014)](https://www.nature.com/articles/ng.3015)</small>
:::
## Simulation software
The most famous and widely used are [SLiM](https://messerlab.org/slim/) and [_msprime_](https://tskit.dev/msprime/docs/stable/intro.html).
::: {.fragment}
They are <u>very</u> powerful and (nearly) infinitely flexible.
:::
::: {.fragment}
However, they both require:
- quite a bit of code for complex simulations ("complex" is relative, of course)
- relatively high confidence in programming
<!-- (🐛🪲🐜). -->
:::
::: {.fragment}
<center>
<h4>Our exercises will focus on the [_slendr_](http://www.slendr.net)<br> simulation toolkit for population genetics in R.</h4>
</center>
:::
::: {.fragment}
<center><br>But, as a recap, let's look at _msprime_ and SLiM a little bit...</center>
:::
##
::: {.columns}
::: {.column width="60%"}
<h2>What is _msprime_?</h2>
- A Python module for writing **coalescent simulations**
- Extremely fast (genome-scale, population-scale data!)
- You should know Python fairly well to build complex models
:::
::: {.column width="40%"}
<center>
](files/slendr/images/sim_sketches.001.png){width="100%"}
</center>
:::
:::
## Simple simulation using _msprime_
```{bash}
#| echo: false
cat files/slendr/script.py
```
##
::: {.columns}
::: {.column width="60%"}
<h2>What is SLiM?</h2>
- **A forward-time simulator**
- Has its own programming language
- Massive library of functions for:
- demographic events
- various mating systems
- natural selection
- More than 700 pages long [manual](https://github.com/MesserLab/SLiM/releases/download/v4.3/SLiM_Manual.pdf)!
:::
::: {.column width="40%"}
<center>
](files/slendr/images/sim_sketches.001.png){width="100%"}
</center>
:::
:::
## Simple neutral simulation in SLiM
```{bash}
#| echo: false
cat files/slendr/script.slim
```
#
<h3>SLiM and _msprime_ are both incredible pieces of software...</h3>
## ... so why _slendr_?
<center>
{width="30%"}
<h4 style="font-family: 'Courier New'">[www.slendr.net](https://www.slendr.net)</h4>
</center>
<small><br></small>
## First motivation: spatial simulations!
<center>{width="70%"}</center>
## A broader motivation for _slendr_
- Most researchers are not expert programmers
- All but the most trivial simulations require lots of code
::: {.fragment}
- Yet, 90% <sup><font color="blue">\[citation needed\]</font></sup> of simulations are basically the same!
- create populations (splits and $N_e$ changes)
- specify admixture rates and admixture times
- ... all this means duplication of code across many projects
:::
::: {.fragment}
- Computing statistics presents even more hurdles
:::
::: {.fragment}
<center><h4>_slendr_ makes this <u>very easy</u>, even for "complex models"</h4></center>
:::
# _slendr_ crash course
<br> <!-- ### remove for slides -->
You can use this document as a cheat sheet as you work on the exercises. <!-- ### remove for slides -->
It contains everything you need to know about _slendr_, in a compressed form. <!-- ### remove for slides -->
## Typical _slendr_ workflow
We will always start our R scripts with this:
```{r}
#| output: false
library(slendr) # You can safely ignore any potential warnings!
init_env() # This activates the internal Python environmet
```
<br>Followed by some combination of the following:
1. creating populations
2. programming $N_e$ size changes
3. encoding gene-flow events
4. simulating genomic data
5. computing popgen statistics
## Creating populations
At minimum, we need its name, size and "time of appearance":
```{r}
pop1 <- population("pop1", N = 1000, time = 1)
```
::: {.fragment}
This creates a normal R object! Typing it out gives a summary:
```{r}
pop1
```
:::
::: {.aside}
**Note:** Because _slendr_ uses either _msprime_ or SLiM internally for simulation
of genomic data, all individuals are assumed to be diploid.
:::
## Programming population splits
Splits are defined by providing a `parent = <pop>` argument:
```{r}
pop2 <- population("pop2", N = 100, time = 50, parent = pop1)
```
::: {.aside}
**Note:** Here `pop1` is an R object created above, not a string `"pop1"`!
:::
::: {.fragment}
The split is again reported in the "historical summary":
```{r}
pop2
```
:::
## Scheduling resize events
- Step size decrease:
```{r}
#| code-line-numbers: "1|2"
pop1 <- population("pop1", N = 1000, time = 1)
pop1_step <- resize(pop1, N = 100, time = 500, how = "step")
```
::: {.fragment}
- Exponential increase:
```{r}
#| code-line-numbers: true
pop2 <- population("pop2", N = 100, time = 50, parent = pop1)
pop2_exp <- resize(pop2, N = 10000, time = 500, end = 2000, how = "exponential")
```
:::
## Tidyverse-style [pipe](https://magrittr.tidyverse.org) `%>%` interface
The following leads to a more concise (and "elegant") code.
- Step size decrease:
```{r}
pop1 <-
population("pop1", N = 1000, time = 1) %>%
resize(N = 100, time = 500, how = "step")
```
- Exponential increase:
```{r}
pop2 <-
population("pop2", N = 1000, time = 1) %>%
resize(N = 10000, time = 500, end = 2000, how = "exponential")
```
::: {.aside}
**Note:** You can read (and understand) `a() %>% b() %>% c()` as "take the
result of the function `a`, pipe it into function `b`, and then pipe _that_ to
function `c`".
:::
## A more complex model
Using just the two functions introduced so far:
```{r}
#| code-line-numbers: "|15-18"
pop1 <- population("pop1", N = 1000, time = 1)
pop2 <-
population("pop2", N = 1000, time = 300, parent = pop1) %>%
resize(N = 100, how = "step", time = 1000)
pop3 <-
population("pop3", N = 1000, time = 400, parent = pop2) %>%
resize(N = 2500, how = "step", time = 800)
pop4 <-
population("pop4", N = 1500, time = 500, parent = pop3) %>%
resize(N = 700, how = "exponential", time = 1200, end = 2000)
pop5 <-
population("pop5", N = 100, time = 600, parent = pop4) %>%
resize(N = 50, how = "step", time = 900) %>%
resize(N = 1000, how = "exponential", time = 1600, end = 2200)
```
## Again, each object carries its history!
For instance, this is the summary you will get from the last population from
the previous code chunk:
```{r}
pop5
```
::: {.fragment}
**This way, you can build up complex models step by step, checking things
as you go by interacting with the R console.**
:::
## Gene flow / admixture
We can schedule gene flow from `pop1` into `pop2` with:
```{r}
gf <- gene_flow(from = pop1, to = pop2, start = 2000, end = 2200, rate = 0.13)
```
::: {.aside}
**Note:** Here `rate = 0.13` means 13% migrants over the given time window will come from "pop1" into "pop2".
:::
::: {.fragment}
<br>
Multiple gene-flow events can be gathered in a list:
```{r}
#| eval: false
gf <- list(
gene_flow(from = pop1, to = pop2, start = 500, end = 600, rate = 0.13),
gene_flow(from = ..., to = ..., start = ..., end = ..., rate = ...),
...
)
```
:::
## Model compilation
<br>
This is the final step before we can simulate data.
<br>
```{r}
#| code-line-numbers: true
model <- compile_model(
populations = list(pop1, pop2, pop3, pop4, pop5),
generation_time = 1, # (converts the all times into generations)
simulation_length = 3000, # (number of generations to run the simulation for)
direction = "forward" # (not totally necessary but good practice)
)
```
<br>
<center>**`compile_model()` takes a list of components, performs some consistency checks, and returns a single R object**</center>
## Model compilation
<br>
This is the final step before we can simulate data.
<br>
```{r}
#| code-line-numbers: "3"
model <- compile_model(
populations = list(pop1, pop2, pop3, pop4, pop5),
gene_flow = gf, # <----- in case our model includes gene flow(s)
generation_time = 1,
simulation_length = 3000,
direction = "forward"
)
```
<br>
<center>**Gene flow(s) can be included via the `gene_flow` argument.**</center>
## Model summary
Typing the compiled `model` into R prints a brief summary:
```{r}
model
```
This can be useful as a quick overview of the model we are working with.
However, **a better way to check a model is...**
## Model visualization
```{r}
#| eval: false
plot_model(model)
```
```{r}
#| fig-width: 7
#| fig-align: center
#| echo: false
plot_model(model, proportions = TRUE)
```
# A note on units of time (and its direction)
<br>
Sometimes you want to work with time units
such as "years ago" (aDNA radio-carbon dated samples, etc.),
but you have to convert those to "generations forward" for some software.
_slendr_ helps by making it possible to use whatever time units
or time directions are more natural for a particular project.
## "Forward time units"
```{r}
#| code-line-numbers: "|1|22-23"
pop1 <- population("pop1", N = 1000, time = 1)
pop2 <-
population("pop2", N = 1000, time = 300, parent = pop1) %>%
resize(N = 100, how = "step", time = 1000)
pop3 <-
population("pop3", N = 1000, time = 400, parent = pop2) %>%
resize(N = 2500, how = "step", time = 800)
pop4 <-
population("pop4", N = 1500, time = 500, parent = pop3) %>%
resize(N = 700, how = "exponential", time = 1200, end = 2000)
pop5 <-
population("pop5", N = 100, time = 600, parent = pop4) %>%
resize(N = 50, how = "step", time = 900) %>%
resize(N = 1000, how = "exponential", time = 1600, end = 2200)
model <- compile_model(
populations = list(pop1, pop2, pop3, pop4, pop5),
generation_time = 1,
simulation_length = 3000, # forward-time sims need an explicit end
direction = "forward"
)
```
::: {.aside}
**We started with `pop1` in generation 1, with later events at an
increasing time value.**
:::
## "Forward time units"
```{r}
#| fig-width: 7
#| fig-align: center
plot_model(model) # see time progressing from generation 1 forwards
```
::: {.aside}
**We started with `pop1` in generation 1, with later events at an
increasing time value.**
:::
## "Backward time units"
```{r}
#| code-line-numbers: "|1|22-24"
pop1 <- population("pop1", N = 1000, time = 30000)
pop2 <-
population("pop2", N = 1000, time = 27000, parent = pop1) %>%
resize(N = 100, how = "step", time = 20000)
pop3 <-
population("pop3", N = 1000, time = 26000, parent = pop2) %>%
resize(N = 2500, how = "step", time = 22000)
pop4 <-
population("pop4", N = 1500, time = 25000, parent = pop3) %>%
resize(N = 700, how = "exponential", time = 18000, end = 10000)
pop5 <-
population("pop5", N = 100, time = 24000, parent = pop4) %>%
resize(N = 50, how = "step", time = 21000) %>%
resize(N = 1000, how = "exponential", time = 14000, end = 8000)
model <- compile_model(
populations = list(pop1, pop2, pop3, pop4, pop5),
generation_time = 10 # (10 time units for each generation)
# (we don't need to provide `simulation_length =` because
# "backwards" models end at time 0 by default, i.e. "present-day")
)
```
::: {.aside}
**Same model as before, except now expressed in units of "years before present".**
:::
## "Backward time units"
```{r}
#| fig-width: 7
#| fig-align: center
plot_model(model) # see time progressing from "year" 30000 backwards
```
::: {.aside}
**Same model as before, except now expressed in units of "years before present".**
:::
# So we built a model...
<center>
<h3>... but how do we simulate data from it?</h3>
</center>
## Built-in simulation "engines"
_slendr_ has two simulation "engine scripts" built-in:
- _msprime_ engine ([_slendr_ source](https://github.com/bodkan/slendr/blob/main/inst/scripts/script.py)) -- R function `msprime()`
- SLiM engine ([_slendr_ source](https://github.com/bodkan/slendr/blob/main/inst/scripts/script.slim)) -- R function `slim()`
::: {.fragment}
They are designed to "understand" _slendr_ `model`s, meaning that you
can simulate data just with this command:
```{r}
#| eval: false
ts <- msprime(model, sequence_length = 10e6, recombination_rate = 1e-8)
```
:::
::: {.fragment}
<br>
<center><h3>**No need to write any _msprime_ or SLiM code!**</h3></center>
:::
# The result of a simulation is a tree sequence (`ts`)
## What is tree sequence?
{width="80%" fig-align="center"}
- a record of full genetic ancestry of a set of samples
- an encoding of DNA sequence carried by those samples
- an efficient analysis framework
# Why tree sequence?
<br>
<h3>Why not VCF or a normal genotype table?</h3>
## What we usually have
<center>{width="90%"}</center>
## What we usually _want_
An understanding of our samples' evolutionary history:
<center></center>
::: {.fragment}
<center>
<h3>**This is exactly what a tree sequence *is*!**</h3>
</center>
:::
::: {.aside}
<small>Image from the [_tskit_ documentation](https://tskit.dev/tutorials/what_is.html)</small>
:::
## The magic of tree sequences
They allow us to compute statistics _without genotypes_!
<center></center>
There is a "duality" between mutations and branch lengths.
::: aside
**Note:** See an amazing paper by [Ralph _et al._ (2020)](https://academic.oup.com/genetics/article/215/3/779/5930459) for more detail.
:::