-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathtest_genotypes.py
More file actions
2237 lines (2047 loc) · 80.3 KB
/
Copy pathtest_genotypes.py
File metadata and controls
2237 lines (2047 loc) · 80.3 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
# MIT License
#
# Copyright (c) 2019-2023 Tskit Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Test cases for generating genotypes/haplotypes.
"""
import itertools
import logging
import random
import re
import textwrap
from xml.etree import ElementTree
import msprime
import numpy as np
import pytest
import tests
import tests.test_wright_fisher as wf
import tests.tsutil as tsutil
import tskit
from tests.test_highlevel import get_example_tree_sequences
from tskit import exceptions
from tskit.genotypes import allele_remap
# ↑ See https://github.com/tskit-dev/tskit/issues/1804 for when
# we can remove this.
# TODO replace this with a call to
# example_tree_sequences(discrete_genome=True, snps_only=True)
@tests.cached_example
def get_example_discrete_genome_tree_sequences():
ret = []
for ts in get_example_tree_sequences(pytest_params=False):
if ts.discrete_genome:
snps = all(len(site.ancestral_state) == 1 for site in ts.sites()) and all(
len(mut.derived_state) == 1 for mut in ts.mutations()
)
if snps:
ret.append(ts)
return ret
def naive_get_ancestral_haplotypes(ts):
"""
Simple implementation using tree traversals. Note that this definition
won't work when we have topology that's not reachable from a root,
but this seems more trouble than it's worth dealing with.
"""
A = np.zeros((ts.num_nodes, ts.num_sites), dtype=np.int8)
A[:] = tskit.MISSING_DATA
for t in ts.trees():
for site in t.sites():
alleles = {site.ancestral_state: 0}
for u in t.nodes():
A[u, site.id] = 0
j = 1
for mutation in site.mutations:
if mutation.derived_state not in alleles:
alleles[mutation.derived_state] = j
j += 1
for u in t.nodes(mutation.node):
A[u, site.id] = alleles[mutation.derived_state]
return A
class TestGetAncestralHaplotypes:
"""
Tests for the engine to the actual ancestors from a simulation.
"""
def verify(self, ts):
A = naive_get_ancestral_haplotypes(ts)
# To detect missing data in ancestors we must set all nodes
# to be samples
tables = ts.dump_tables()
nodes = tables.nodes
flags = nodes.flags[:]
flags[:] = 1
nodes.set_columns(time=nodes.time, flags=flags)
ts = tables.tree_sequence()
B = ts.genotype_matrix().T
assert np.array_equal(A, B)
def test_single_tree(self):
ts = msprime.simulate(5, mutation_rate=1, random_seed=234)
self.verify(ts)
def test_many_trees(self):
ts = msprime.simulate(
8, recombination_rate=10, mutation_rate=10, random_seed=234
)
assert ts.num_trees > 1
assert ts.num_sites > 1
self.verify(ts)
def test_single_tree_jukes_cantor(self):
ts = msprime.simulate(6, random_seed=1, mutation_rate=1)
ts = tsutil.jukes_cantor(ts, 20, 1, seed=10)
self.verify(ts)
def test_single_tree_multichar_mutations(self):
ts = msprime.simulate(6, random_seed=1, mutation_rate=1)
ts = tsutil.insert_multichar_mutations(ts)
self.verify(ts)
def test_many_trees_infinite_sites(self):
ts = msprime.simulate(6, recombination_rate=2, mutation_rate=2, random_seed=1)
assert ts.num_sites > 0
assert ts.num_trees > 2
self.verify(ts)
def test_wright_fisher_initial_generation(self):
tables = wf.wf_sim(
6, 5, seed=3, deep_history=True, initial_generation_samples=True, num_loci=2
)
tables.sort()
tables.simplify()
ts = msprime.mutate(tables.tree_sequence(), rate=0.08, random_seed=2)
assert ts.num_sites > 0
self.verify(ts)
def test_wright_fisher_simplified(self):
tables = wf.wf_sim(
9,
10,
seed=1,
deep_history=True,
initial_generation_samples=False,
num_loci=5,
)
tables.sort()
ts = tables.tree_sequence().simplify()
ts = msprime.mutate(ts, rate=0.2, random_seed=1234)
assert ts.num_sites > 0
self.verify(ts)
def test_empty_ts(self):
tables = tskit.TableCollection(1.0)
for _ in range(10):
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
ts = tables.tree_sequence()
self.verify(ts)
def isolated_samples_genotype_matrix(ts):
"""
Returns the genotype matrix for the specified tree sequence
where isolated samples are marked with MISSING_DATA.
"""
G = ts.genotype_matrix()
samples = ts.samples()
sample_index_map = np.zeros(ts.num_nodes, dtype=int) - 1
for index, sample in enumerate(samples):
sample_index_map[sample] = index
for tree in ts.trees():
for site in tree.sites():
for root in tree.roots:
# An isolated sample is any root that has no children.
if tree.left_child(root) == -1:
assert sample_index_map[root] != -1
G[site.id, sample_index_map[root]] = -1
return G
class TestVariantGenerator:
"""
Tests the variants() method to ensure the output is consistent.
"""
def get_tree_sequence(self):
ts = msprime.simulate(
10, length=10, recombination_rate=1, mutation_rate=10, random_seed=3
)
assert ts.get_num_mutations() > 10
return ts
def test_dtype(self):
ts = self.get_tree_sequence()
for var in ts.variants():
assert var.genotypes.dtype == np.int32
def test_dtype_conversion(self):
# Check if we hit any issues if we assume the variants are uint8
# as they were prior to version 0.2.0
ts = self.get_tree_sequence()
G = ts.genotype_matrix().astype(np.uint8)
assert G.dtype == np.uint8
for var in ts.variants():
assert np.array_equal(G[var.index], var.genotypes)
assert np.all(G[var.index] == var.genotypes)
assert [var.alleles[g] for g in var.genotypes] == [
var.alleles[g] for g in G[var.index]
]
G[var.index, :] = var.genotypes
assert np.array_equal(G[var.index], var.genotypes)
def test_multichar_alleles(self):
ts = tsutil.insert_multichar_mutations(self.get_tree_sequence())
for var in ts.variants():
assert len(var.alleles) == 2
assert var.site.ancestral_state == var.alleles[0]
assert var.site.mutations[0].derived_state == var.alleles[1]
assert all(0 <= var.genotypes)
assert all(var.genotypes <= 1)
def test_many_alleles(self):
ts = self.get_tree_sequence()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
# This gives us a total of 360 permutations.
alleles = list(map("".join, itertools.permutations("ABCDEF", 4)))
assert len(alleles) > 127
tables.sites.add_row(0, alleles[0])
parent = -1
num_alleles = 1
for allele in alleles[1:]:
ts = tables.tree_sequence()
var = next(ts.variants())
assert not var.has_missing_data
assert var.num_alleles == num_alleles
assert len(var.alleles) == num_alleles
assert list(var.alleles) == alleles[:num_alleles]
assert var.alleles[var.genotypes[0]] == alleles[num_alleles - 1]
for u in ts.samples():
if u != 0:
assert var.alleles[var.genotypes[u]] == alleles[0]
tables.mutations.add_row(0, 0, allele, parent=parent)
parent += 1
num_alleles += 1
def test_many_alleles_missing_data(self):
ts = self.get_tree_sequence()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
# Add an isolated sample
tables.nodes.add_row(flags=1, time=0)
# This gives us a total of 360 permutations.
alleles = list(map("".join, itertools.permutations("ABCDEF", 4)))
assert len(alleles) > 127
tables.sites.add_row(0, alleles[0])
parent = -1
num_alleles = 1
for allele in alleles[1:]:
ts = tables.tree_sequence()
var = next(ts.variants())
assert var.has_missing_data
assert var.num_alleles == num_alleles
assert len(var.alleles) == num_alleles + 1
assert list(var.alleles)[:-1] == alleles[:num_alleles]
assert var.alleles[-1] is None
assert var.alleles[var.genotypes[0]] == alleles[num_alleles - 1]
assert var.genotypes[-1] == -1
samples = ts.samples()
for u in samples[:-1]:
if u != 0:
assert var.alleles[var.genotypes[u]] == alleles[0]
tables.mutations.add_row(0, 0, allele, parent=parent)
parent += 1
num_alleles += 1
def test_site_information(self):
ts = self.get_tree_sequence()
for site, variant in zip(ts.sites(), ts.variants()):
assert site.position == variant.position
assert site == variant.site
def test_no_mutations(self):
ts = msprime.simulate(10)
assert ts.get_num_mutations() == 0
variants = list(ts.variants())
assert len(variants) == 0
@pytest.mark.parametrize("samples", [None, [1, 2], [2, 4], []])
def test_genotype_matrix(self, samples):
ts = self.get_tree_sequence()
num_samples = ts.num_samples if samples is None else len(samples)
G = np.empty((ts.num_sites, num_samples), dtype=np.int32)
for v in ts.variants(samples=samples):
G[v.index, :] = v.genotypes
if samples is None:
G2 = ts.genotype_matrix()
else:
G2 = ts.genotype_matrix(samples=samples)
assert np.array_equal(G, G2)
assert G2.dtype == np.int32
def test_recurrent_mutations_over_samples(self):
ts = self.get_tree_sequence()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
num_sites = 5
for j in range(num_sites):
tables.sites.add_row(
position=j * ts.sequence_length / num_sites, ancestral_state="0"
)
for u in range(ts.sample_size):
tables.mutations.add_row(site=j, node=u, derived_state="1")
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == num_sites
for site, variant in zip(ts.sites(), variants):
assert site.position == variant.position
assert site == variant.site
assert site.id == variant.index
assert variant.alleles == ("0", "1")
assert np.all(variant.genotypes == np.ones(ts.sample_size))
def test_silent_mutations(self):
ts = self.get_tree_sequence()
tree = next(ts.trees())
tables = ts.dump_tables()
for u in tree.nodes():
for sample in tree.samples(u):
if sample != u:
tables.sites.clear()
tables.mutations.clear()
site = tables.sites.add_row(position=0, ancestral_state="0")
tables.mutations.add_row(site=site, node=u, derived_state="1")
tables.mutations.add_row(site=site, node=sample, derived_state="1")
ts_new = tables.tree_sequence()
assert all([v.genotypes[sample] == 1 for v in ts_new.variants()])
def test_zero_samples(self):
ts = self.get_tree_sequence()
for var1, var2 in zip(ts.variants(), ts.variants(samples=[])):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape[0] == 0
def test_samples(self):
n = 4
ts = msprime.simulate(
n, length=5, recombination_rate=1, mutation_rate=5, random_seed=2
)
assert ts.num_sites > 1
samples = list(range(n))
# Generate all possible sample lists.
for j in range(n + 1):
for s in itertools.permutations(samples, j):
s = np.array(s, dtype=np.int32)
count = 0
for var1, var2 in zip(ts.variants(), ts.variants(samples=s)):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert np.array_equal(var1.samples, ts.samples())
assert np.array_equal(var2.samples, s)
assert var2.genotypes.shape == (len(s),)
assert np.array_equal(var1.genotypes[s], var2.genotypes)
count += 1
assert count == ts.num_sites
def test_samples_64bit(self):
ts = msprime.simulate(4, length=5, mutation_rate=5, random_seed=2)
s = np.where(ts.nodes_time == 0)[0] # normally returns 64 bit ints
next(ts.variants(samples=s))
s = np.array(s, dtype=np.int64) # cast just to make sure
next(ts.variants(samples=s))
def test_samples_missing_data(self):
n = 4
ts = msprime.simulate(
n, length=5, recombination_rate=1, mutation_rate=5, random_seed=2
)
assert ts.num_sites > 1
tables = ts.dump_tables()
tables.delete_intervals([[0.5, 0.6]])
tables.sites.add_row(0.5, ancestral_state="0")
tables.sort()
ts = tables.tree_sequence()
samples = list(range(n))
# Generate all possible sample lists.
for j in range(1, n + 1):
for s in itertools.permutations(samples, j):
s = np.array(s, dtype=np.int32)
count = 0
for var1, var2 in zip(ts.variants(), ts.variants(samples=s)):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape == (len(s),)
assert np.array_equal(var1.genotypes[s], var2.genotypes)
count += 1
assert count == ts.num_sites
def test_non_sample_samples(self):
# We don't have to use sample nodes. This does make the terminology confusing
# but it's probably still the best option.
ts = msprime.simulate(
10, length=5, recombination_rate=1, mutation_rate=5, random_seed=2
)
tables = ts.dump_tables()
tables.nodes.set_columns(
flags=np.zeros_like(tables.nodes.flags) + tskit.NODE_IS_SAMPLE,
time=tables.nodes.time,
)
all_samples_ts = tables.tree_sequence()
assert all_samples_ts.num_samples == ts.num_nodes
count = 0
samples = range(ts.num_nodes)
for var1, var2 in zip(
all_samples_ts.variants(isolated_as_missing=False),
ts.variants(samples=samples, isolated_as_missing=False),
):
assert var1.site == var2.site
assert var1.alleles == var2.alleles
assert var2.genotypes.shape == (len(samples),)
assert np.array_equal(var1.genotypes, var2.genotypes)
count += 1
assert count == ts.num_sites
def verify_jukes_cantor(self, ts):
assert np.array_equal(ts.genotype_matrix(), ts.genotype_matrix())
tree = ts.first()
for variant in ts.variants():
assert not variant.has_missing_data
mutations = {
mutation.node: mutation.derived_state
for mutation in variant.site.mutations
}
for sample_index, u in enumerate(ts.samples()):
while u not in mutations and u != tskit.NULL:
u = tree.parent(u)
state1 = mutations.get(u, variant.site.ancestral_state)
state2 = variant.alleles[variant.genotypes[sample_index]]
assert state1 == state2
def test_jukes_cantor_n5(self):
ts = msprime.simulate(5, random_seed=2)
ts = tsutil.jukes_cantor(ts, 5, 1, seed=2)
self.verify_jukes_cantor(ts)
def test_jukes_cantor_n20(self):
ts = msprime.simulate(20, random_seed=2)
ts = tsutil.jukes_cantor(ts, 5, 1, seed=2)
self.verify_jukes_cantor(ts)
def test_zero_edge_missing_data(self):
ts = msprime.simulate(10, random_seed=2, mutation_rate=2)
tables = ts.dump_tables()
tables.keep_intervals([[0.25, 0.75]])
# add some sites in the deleted regions
tables.sites.add_row(0.1, "A")
tables.sites.add_row(0.2, "A")
tables.sites.add_row(0.8, "A")
tables.sites.add_row(0.9, "A")
tables.sort()
ts = tables.tree_sequence()
Gnm = ts.genotype_matrix(isolated_as_missing=False)
assert np.all(Gnm[0] == 0)
assert np.all(Gnm[1] == 0)
assert np.all(Gnm[-1] == 0)
assert np.all(Gnm[-2] == 0)
Gm = isolated_samples_genotype_matrix(ts)
assert np.all(Gm[0] == -1)
assert np.all(Gm[1] == -1)
assert np.all(Gm[-1] == -1)
assert np.all(Gm[-2] == -1)
Gm2 = ts.genotype_matrix(isolated_as_missing=True)
assert np.array_equal(Gm, Gm2)
# Test deprecated param
with pytest.warns(FutureWarning):
Gi = ts.genotype_matrix(impute_missing_data=True)
assert np.array_equal(Gnm, Gi)
with pytest.warns(FutureWarning):
Gni = ts.genotype_matrix(impute_missing_data=False)
assert np.array_equal(Gm, Gni)
with pytest.warns(FutureWarning):
G = ts.genotype_matrix(isolated_as_missing=False, impute_missing_data=True)
assert np.array_equal(Gnm, G)
with pytest.warns(FutureWarning):
G = ts.genotype_matrix(isolated_as_missing=True, impute_missing_data=False)
assert np.array_equal(Gm, G)
def test_empty_ts_missing_data(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == 1
var = variants[0]
assert var.alleles == ("A", None)
assert var.num_alleles == 1
assert np.all(var.genotypes == -1)
def test_empty_ts_incomplete_samples(self):
# https://github.com/tskit-dev/tskit/issues/776
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
ts = tables.tree_sequence()
variants = list(ts.variants(samples=[0]))
assert list(variants[0].genotypes) == [-1]
variants = list(ts.variants(samples=[1]))
assert list(variants[0].genotypes) == [-1]
def test_missing_data_samples(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, "T")
ts = tables.tree_sequence()
# If we have no samples we still get a list of variants.
variants = list(ts.variants(samples=[]))
assert len(variants[0].genotypes) == 0
assert not variants[0].has_missing_data
assert variants[0].alleles == ("A", "T")
# If we have a single sample that's not missing, there's no
# missing data.
variants = list(ts.variants(samples=[0]))
assert len(variants[0].genotypes) == 1
assert variants[0].genotypes[0] == 1
assert not variants[0].has_missing_data
assert variants[0].alleles == ("A", "T")
# If we have a single sample that is missing, there is
# missing data.
variants = list(ts.variants(samples=[1]))
assert len(variants[0].genotypes) == 1
assert variants[0].genotypes[0] == -1
assert variants[0].has_missing_data
assert variants[0].alleles == ("A", "T", None)
def test_mutation_over_isolated_sample_not_missing(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, "T")
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == 1
var = variants[0]
assert var.alleles == ("A", "T", None)
assert var.num_alleles == 2
assert list(var.genotypes) == [1, -1]
def test_multiple_mutations_over_isolated_sample(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, "T")
tables.mutations.add_row(0, 0, "G", parent=0)
ts = tables.tree_sequence()
variants = list(ts.variants())
assert len(variants) == 1
var = variants[0]
assert var.alleles == ("A", "T", "G", None)
assert var.num_alleles == 3
assert len(var.site.mutations) == 2
assert list(var.genotypes) == [2, -1]
def test_snipped_tree_sequence_missing_data(self):
ts = msprime.simulate(
10, length=10, recombination_rate=0.1, mutation_rate=10, random_seed=3
)
tables = ts.dump_tables()
tables.delete_intervals([[4, 6]], simplify=False)
tables.sites.add_row(4, ancestral_state="0")
tables.sites.add_row(5, ancestral_state="0")
tables.sites.add_row(5.999999, ancestral_state="0")
tables.sort()
ts = tables.tree_sequence()
G = ts.genotype_matrix()
num_missing = 0
for var in ts.variants():
if 4 <= var.site.position < 6:
assert var.has_missing_data
assert np.all(var.genotypes == tskit.MISSING_DATA)
num_missing += 1
else:
assert not var.has_missing_data
assert np.all(var.genotypes != tskit.MISSING_DATA)
assert np.array_equal(var.genotypes, G[var.site.id])
assert num_missing == 3
G = ts.genotype_matrix(isolated_as_missing=False)
for var in ts.variants(isolated_as_missing=False):
if 4 <= var.site.position < 6:
assert not var.has_missing_data
assert np.all(var.genotypes == 0)
else:
assert not var.has_missing_data
assert np.all(var.genotypes != tskit.MISSING_DATA)
assert np.array_equal(var.genotypes, G[var.site.id])
def test_snipped_tree_sequence_mutations_over_isolated(self):
ts = msprime.simulate(
10, length=10, recombination_rate=0.1, mutation_rate=10, random_seed=3
)
tables = ts.dump_tables()
tables.delete_intervals([[4, 6]], simplify=False)
missing_site = tables.sites.add_row(4, ancestral_state="0")
tables.mutations.add_row(missing_site, node=0, derived_state="1")
# Add another site in which all the samples are marked with a mutation
# to the ancestral state. Note: this would normally not be allowed because
# there's not state change. However, this allows us to mark a sample
# as not-missing, so it's an important feature.
missing_site = tables.sites.add_row(5, ancestral_state="0")
for u in range(10):
tables.mutations.add_row(missing_site, node=u, derived_state="0")
tables.sort()
ts = tables.tree_sequence()
G = ts.genotype_matrix()
missing_found = False
non_missing_found = False
for var in ts.variants():
if var.site.position == 4:
assert var.has_missing_data
assert var.genotypes[0] == 1
assert np.all(var.genotypes[1:] == tskit.MISSING_DATA)
missing_found += 1
elif var.site.position == 5:
assert not var.has_missing_data
assert np.all(var.genotypes == 0)
non_missing_found = 1
else:
assert not var.has_missing_data
assert np.all(var.genotypes != tskit.MISSING_DATA)
assert np.array_equal(var.genotypes, G[var.site.id])
assert non_missing_found
assert missing_found
class TestLimitInterval:
def test_simple_case(self, ts_fixture):
ts = ts_fixture
test_variant = tskit.Variant(ts)
test_variant.decode(1)
v_iter = ts.variants(left=ts.site(1).position, right=ts.site(2).position)
assert len(v_iter) == 1
for v in v_iter:
# should only decode the first variant
assert v.site.id == 1
assert np.all(v.genotypes == test_variant.genotypes)
assert v.alleles == test_variant.alleles
@pytest.mark.parametrize(
["left", "expected"],
[
(None, [0, 1, 2, 3, 4]),
(0, [0, 1, 2, 3, 4]),
(0.999, [1, 2, 3, 4]),
(1, [1, 2, 3, 4]),
(3.999, [4]),
(4, [4]),
(4.00001, []),
(4.99999, []),
(np.array([4.99999])[0], []),
],
)
def test_left(self, left, expected):
tables = tskit.TableCollection(5)
for x in range(int(tables.sequence_length)):
tables.sites.add_row(position=x, ancestral_state="A")
ts = tables.tree_sequence()
v_iter = ts.variants(left=left)
assert len(v_iter) == len(expected)
positions = [var.site.position for var in v_iter]
assert positions == expected
@pytest.mark.parametrize(
["right", "expected"],
[
(None, [0, 1, 2, 3, 4]),
(5, [0, 1, 2, 3, 4]),
(4.00001, [0, 1, 2, 3, 4]),
(4.0, [0, 1, 2, 3]),
(3.9999, [0, 1, 2, 3]),
(0.00001, [0]),
(np.array([1e-200])[0], [0]),
],
)
def test_right(self, right, expected):
tables = tskit.TableCollection(5)
for x in range(int(tables.sequence_length)):
tables.sites.add_row(position=x, ancestral_state="A")
ts = tables.tree_sequence()
v_iter = ts.variants(right=right)
assert len(v_iter) == len(expected)
positions = [var.site.position for var in v_iter]
assert positions == expected
@pytest.mark.parametrize("bad_left", [-1, 10, 100, np.nan, np.inf, -np.inf])
def test_bad_left(self, bad_left):
ts = tskit.TableCollection(10).tree_sequence()
with pytest.raises(ValueError, match="`left` not between"):
list(ts.variants(left=bad_left))
@pytest.mark.parametrize("bad_right", [-1, 0, 100, np.nan, np.inf, -np.inf])
def test_bad_right(self, bad_right):
ts = tskit.TableCollection(10).tree_sequence()
with pytest.raises(ValueError, match="`right` not between"):
list(ts.variants(right=bad_right))
def test_bad_left_right(self):
ts = tskit.TableCollection(10).tree_sequence()
with pytest.raises(ValueError, match="must be less than"):
list(ts.variants(left=1, right=1))
class TestHaplotypeGenerator:
"""
Tests the haplotype generation code.
"""
def verify_haplotypes(self, n, haplotypes):
"""
Verify that the specified set of haplotypes is consistent.
"""
assert len(haplotypes) == n
m = len(haplotypes[0])
for h in haplotypes:
assert len(h) == m
# Examine each column in H; we must have a mixture of 0s and 1s
for k in range(m):
zeros = 0
ones = 0
col = ""
for j in range(n):
b = haplotypes[j][k]
zeros += b == "0"
ones += b == "1"
col += b
assert zeros + ones == n
def verify_tree_sequence(self, tree_sequence):
n = tree_sequence.sample_size
m = tree_sequence.num_sites
haplotypes = list(tree_sequence.haplotypes())
A = np.zeros((n, m), dtype="u1")
B = np.zeros((n, m), dtype="u1")
for j, h in enumerate(haplotypes):
assert len(h) == m
A[j] = np.frombuffer(h.encode("ascii"), np.uint8) - ord("0")
for variant in tree_sequence.variants():
B[:, variant.index] = variant.genotypes
assert np.all(A == B)
self.verify_haplotypes(n, haplotypes)
def verify_simulation(self, n, m, r, theta):
"""
Verifies a simulation for the specified parameters.
"""
recomb_map = msprime.RecombinationMap.uniform_map(m, r, m)
tree_sequence = msprime.simulate(
n, recombination_map=recomb_map, mutation_rate=theta
)
self.verify_tree_sequence(tree_sequence)
def test_random_parameters(self):
num_random_sims = 10
for _ in range(num_random_sims):
n = random.randint(2, 50)
m = random.randint(10, 200)
r = random.random()
theta = random.uniform(0, 2)
self.verify_simulation(n, m, r, theta)
def test_nonbinary_trees(self):
bottlenecks = [
msprime.SimpleBottleneck(0.01, 0, proportion=0.05),
msprime.SimpleBottleneck(0.02, 0, proportion=0.25),
msprime.SimpleBottleneck(0.03, 0, proportion=1),
]
ts = msprime.simulate(
10,
length=100,
recombination_rate=1,
demographic_events=bottlenecks,
random_seed=1,
)
self.verify_tree_sequence(ts)
def test_acgt_mutations(self):
ts = msprime.simulate(10, mutation_rate=10)
assert ts.num_sites > 0
tables = ts.tables
sites = tables.sites
mutations = tables.mutations
sites.set_columns(
position=sites.position,
ancestral_state=np.zeros(ts.num_sites, dtype=np.int8) + ord("A"),
ancestral_state_offset=np.arange(ts.num_sites + 1, dtype=np.uint32),
)
mutations.set_columns(
site=mutations.site,
node=mutations.node,
derived_state=np.zeros(ts.num_sites, dtype=np.int8) + ord("T"),
derived_state_offset=np.arange(ts.num_sites + 1, dtype=np.uint32),
)
tsp = tables.tree_sequence()
H = [h.replace("0", "A").replace("1", "T") for h in ts.haplotypes()]
assert H == list(tsp.haplotypes())
def test_fails_multiletter_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.tables
tables.sites.add_row(0, "ACTG")
tsp = tables.tree_sequence()
with pytest.raises(TypeError):
list(tsp.haplotypes())
def test_fails_deletion_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.tables
tables.sites.add_row(0, "")
tsp = tables.tree_sequence()
with pytest.raises(TypeError):
list(tsp.haplotypes())
def test_nonascii_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.tables
tables.sites.add_row(0, chr(169)) # Copyright symbol
tsp = tables.tree_sequence()
with pytest.raises(TypeError):
list(tsp.haplotypes())
def test_recurrent_mutations_over_samples(self):
ts = msprime.simulate(10, random_seed=2)
num_sites = 5
tables = ts.dump_tables()
for j in range(num_sites):
tables.sites.add_row(
position=j * ts.sequence_length / num_sites, ancestral_state="0"
)
for u in range(ts.sample_size):
tables.mutations.add_row(site=j, node=u, derived_state="1")
ts_new = tables.tree_sequence()
ones = "1" * num_sites
for h in ts_new.haplotypes():
assert ones == h
def test_silent_mutations(self):
ts = msprime.simulate(10, random_seed=2)
tables = ts.dump_tables()
tree = next(ts.trees())
for u in tree.children(tree.root):
tables.sites.clear()
tables.mutations.clear()
site = tables.sites.add_row(position=0, ancestral_state="0")
tables.mutations.add_row(site=site, node=u, derived_state="1")
tables.mutations.add_row(site=site, node=tree.root, derived_state="1")
ts_new = tables.tree_sequence()
all(h == 1 for h in ts_new.haplotypes())
def test_back_mutations(self):
base_ts = msprime.simulate(10, random_seed=2)
for j in [1, 2, 3]:
ts = tsutil.insert_branch_mutations(base_ts, mutations_per_branch=j)
self.verify_tree_sequence(ts)
def test_missing_data(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
ts = tables.tree_sequence()
with pytest.raises(ValueError):
list(ts.haplotypes(missing_data_character="A"))
for c in ("-", ".", "a"):
h = list(ts.haplotypes(missing_data_character=c))
assert h == [c, c]
h = list(ts.haplotypes(isolated_as_missing=True))
assert h == ["N", "N"]
h = list(ts.haplotypes(isolated_as_missing=False))
assert h == ["A", "A"]
h = list(ts.haplotypes())
assert h == ["N", "N"]
# Test deprecated method
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(impute_missing_data=True))
assert h == ["A", "A"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(impute_missing_data=False))
assert h == ["N", "N"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(isolated_as_missing=True, impute_missing_data=True))
assert h == ["N", "N"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(isolated_as_missing=True, impute_missing_data=False))
assert h == ["N", "N"]
with pytest.warns(FutureWarning):
h = list(ts.haplotypes(isolated_as_missing=False, impute_missing_data=True))
assert h == ["A", "A"]
with pytest.warns(FutureWarning):
h = list(
ts.haplotypes(isolated_as_missing=False, impute_missing_data=False)
)
assert h == ["A", "A"]
def test_restrict_samples(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.5, "A")
tables.mutations.add_row(0, 0, derived_state="B")
ts = tables.tree_sequence()
haplotypes = list(ts.haplotypes(samples=[0], isolated_as_missing=False))
assert haplotypes == ["B"]
haplotypes = list(ts.haplotypes(samples=[1], isolated_as_missing=False))
assert haplotypes == ["A"]
def test_restrict_positions(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(tskit.NODE_IS_SAMPLE, 0)
tables.sites.add_row(0.1, "A")
tables.sites.add_row(0.2, "B")
tables.sites.add_row(0.3, "C")
tables.sites.add_row(0.4, "D")
ts = tables.tree_sequence()
haplotypes = list(ts.haplotypes(left=0.2, right=0.4, isolated_as_missing=False))
assert haplotypes == ["BC"]
class TestUserAlleles:
"""
Tests the functionality of providing a user-specified allele mapping.
"""
def test_simple_01(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
G2 = ts.genotype_matrix(alleles=("0", "1"))
assert np.array_equal(G1, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=("0", "1"))
):
assert v1.alleles == v2.alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes, v2.genotypes)
def test_simple_01_trailing_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
alleles = ("0", "1", "2", "xxxxx")
G2 = ts.genotype_matrix(alleles=alleles)
assert np.array_equal(G1, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
assert v2.alleles == alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes, v2.genotypes)
def test_simple_01_leading_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()
alleles = ("A", "B", "C", "0", "1")
G2 = ts.genotype_matrix(alleles=alleles)
assert np.array_equal(G1 + 3, G2)
for v1, v2 in itertools.zip_longest(
ts.variants(), ts.variants(alleles=alleles)
):
assert v2.alleles == alleles
assert v1.site == v2.site
assert np.array_equal(v1.genotypes + 3, v2.genotypes)
def test_simple_01_duplicate_alleles(self):
ts = msprime.simulate(10, mutation_rate=5, random_seed=2)
assert ts.num_sites > 2
G1 = ts.genotype_matrix()