-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathtest_tree_stats.py
More file actions
7125 lines (6269 loc) · 253 KB
/
Copy pathtest_tree_stats.py
File metadata and controls
7125 lines (6269 loc) · 253 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) 2018-2024 Tskit Developers
# Copyright (C) 2016 University of Oxford
#
# 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 generalized statistic computation.
"""
import collections
import contextlib
import functools
import io
import itertools
import random
import msprime
import numpy as np
import numpy.testing as nt
import pytest
import tests.test_wright_fisher as wf
import tests.tsutil as tsutil
import tskit
import tskit.exceptions as exceptions
np.random.seed(5)
def cached_np(func):
"""
Decorator to speed up functions that take numpy arrays as positional
arguments that get called a lot with the same arguments.
# See https://github.com/tskit-dev/tskit/issues/1856 for more info
"""
cache = {}
def f(*args):
nonlocal cache # noqa: F824
key = tuple(x.tobytes() for x in args)
if key not in cache:
cache[key] = func(*args)
return cache[key]
return f
def subset_combos(*args, p=0.5, min_tests=3):
# We have too many tests, combinatorially; so we will run a random subset
# of them, using this function, below. If we don't set a seed, a different
# random set is run each time. Ensures that at least min_tests are run.
# Uncomment this line to run all tests (takes about an hour):
# p = 1.0
num_tests = 0
skipped_tests = []
# total_tests = 0
for x in itertools.product(*args):
# total_tests = total_tests + 1
if np.random.uniform() < p:
num_tests += 1
yield x
elif len(skipped_tests) < min_tests:
skipped_tests.append(x)
elif np.random.uniform() < 0.1:
skipped_tests[np.random.randint(min_tests)] = x
while num_tests < min_tests:
yield skipped_tests.pop()
num_tests += 1
# print("tests", num_tests)
assert num_tests >= min_tests
def path_length(tr, x, y):
L = 0
if x >= 0 and y >= 0:
mrca = tr.mrca(x, y)
else:
mrca = -1
for u in x, y:
while u != mrca:
L += tr.branch_length(u)
u = tr.parent(u)
return L
@contextlib.contextmanager
def suppress_division_by_zero_warning():
with np.errstate(invalid="ignore", divide="ignore"):
yield
##############################
# Branch general stat algorithms
##############################
def windowed_tree_stat(ts, stat, windows, span_normalise=True):
shape = list(stat.shape)
shape[0] = len(windows) - 1
A = np.zeros(shape)
tree_breakpoints = np.array(list(ts.breakpoints()))
tree_index = 0
for j in range(len(windows) - 1):
w_left = windows[j]
w_right = windows[j + 1]
while True:
t_left = tree_breakpoints[tree_index]
t_right = tree_breakpoints[tree_index + 1]
left = max(t_left, w_left)
right = min(t_right, w_right)
weight = max(0.0, (right - left) / (t_right - t_left))
A[j] += stat[tree_index] * weight
assert left != right
if t_right <= w_right:
tree_index += 1
# TODO This is inelegant - should include this in the case below
if t_right == w_right:
break
else:
break
if span_normalise:
# re-normalize by window lengths
window_lengths = np.diff(windows)
for j in range(len(windows) - 1):
A[j] /= window_lengths[j]
return A
def naive_branch_general_stat(
ts, w, f, windows=None, time_windows=None, polarised=False, span_normalise=True
):
# NOTE: does not behave correctly for unpolarised stats
# with non-ancestral material.
if windows is None:
windows = [0.0, ts.sequence_length]
drop_time_windows = time_windows is None
if time_windows is None:
time_windows = [0.0, np.inf]
else:
if time_windows[0] != 0:
time_windows = [0] + time_windows
n, k = w.shape
tw = len(time_windows) - 1
# hack to determine m
m = len(f(w[0]))
total = np.sum(w, axis=0)
sigma = np.zeros((ts.num_trees, tw, m))
for j, upper_time in enumerate(time_windows[1:]):
if np.isfinite(upper_time):
decap_ts = ts.decapitate(upper_time)
else:
decap_ts = ts
assert np.all(list(ts.samples()) == list(decap_ts.samples()))
for tree in decap_ts.trees():
x = np.zeros((decap_ts.num_nodes, k))
x[decap_ts.samples()] = w
for u in tree.nodes(order="postorder"):
for v in tree.children(u):
x[u] += x[v]
if polarised:
s = sum(tree.branch_length(u) * f(x[u]) for u in tree.nodes())
else:
s = sum(
tree.branch_length(u) * (f(x[u]) + f(total - x[u]))
for u in tree.nodes()
)
sigma[tree.index, j, :] = s * tree.span
for j in range(1, tw):
sigma[:, j, :] = sigma[:, j, :] - sigma[:, j - 1, :]
if isinstance(windows, str) and windows == "trees":
# need to average across the windows
if span_normalise:
for j, tree in enumerate(ts.trees()):
sigma[j] /= tree.span
out = sigma
else:
out = windowed_tree_stat(ts, sigma, windows, span_normalise=span_normalise)
if drop_time_windows:
assert out.ndim == 3
out = out[:, 0]
return out
def branch_general_stat(
ts,
sample_weights,
summary_func,
windows=None,
time_windows=None,
polarised=False,
span_normalise=True,
):
"""
Efficient implementation of the algorithm used as the basis for the
underlying C version.
"""
n, state_dim = sample_weights.shape
windows = ts.parse_windows(windows)
drop_time_windows = time_windows is None
time_windows = ts.parse_time_windows(time_windows)
num_windows = windows.shape[0] - 1
num_time_windows = time_windows.shape[0] - 1
# Determine result_dim
result_dim = len(summary_func(sample_weights[0]))
result = np.zeros((num_windows, num_time_windows, result_dim))
state = np.zeros((ts.num_nodes, state_dim))
state[ts.samples()] = sample_weights
total_weight = np.sum(sample_weights, axis=0)
time = ts.tables.nodes.time
parent = np.zeros(ts.num_nodes, dtype=np.int32) - 1
branch_length = np.zeros((num_time_windows, ts.num_nodes))
# The value of summary_func(u) for every node.
summary = np.zeros((ts.num_nodes, result_dim))
# The result for the current tree *not* weighted by span.
running_sum = np.zeros((num_time_windows, result_dim))
def polarised_summary(u):
s = summary_func(state[u])
if not polarised:
s += summary_func(total_weight - state[u])
return s
for u in range(ts.num_nodes):
summary[u] = polarised_summary(u)
window_index = 0
def update_sum(u, sign):
time_window_index = 0
if parent[u] != -1:
while (
time_window_index < num_time_windows
and time_windows[time_window_index] < time[parent[u]]
):
running_sum[time_window_index] += sign * (
branch_length[time_window_index, u] * summary[u]
)
time_window_index += 1
for (t_left, t_right), edges_out, edges_in in ts.edge_diffs():
for edge in edges_out:
u = edge.child
update_sum(u, sign=-1)
u = edge.parent
while u != -1:
update_sum(u, sign=-1)
state[u] -= state[edge.child]
summary[u] = polarised_summary(u)
update_sum(u, sign=+1)
u = parent[u]
parent[edge.child] = -1
for tw in range(num_time_windows):
branch_length[tw, edge.child] = 0
for edge in edges_in:
parent[edge.child] = edge.parent
for tw in range(num_time_windows):
branch_length[tw, edge.child] = min(
time[edge.parent], time_windows[tw + 1]
) - max(time[edge.child], time_windows[tw])
u = edge.child
update_sum(u, sign=+1)
u = edge.parent
while u != -1:
update_sum(u, sign=-1)
state[u] += state[edge.child]
summary[u] = polarised_summary(u)
update_sum(u, sign=+1)
u = parent[u]
# Update the windows
assert window_index < num_windows
while windows[window_index] < t_right:
w_left = windows[window_index]
w_right = windows[window_index + 1]
left = max(t_left, w_left)
right = min(t_right, w_right)
span = right - left
assert span > 0
time_window_index = 0
while time_window_index < num_time_windows:
result[window_index, time_window_index] += (
running_sum[time_window_index] * span
)
time_window_index += 1
if w_right <= t_right:
window_index += 1
else:
# This interval crosses a tree boundary, so we update it again in the
# for the next tree
break
# print("window_index:", window_index, windows.shape)
assert window_index == windows.shape[0] - 1
if drop_time_windows:
assert result.ndim == 3
result = result[:, 0]
if span_normalise:
for j in range(num_windows):
result[j] /= windows[j + 1] - windows[j]
return result
##############################
# Site general stat algorithms
##############################
def windowed_sitewise_stat(ts, sigma, windows, span_normalise=True):
M = sigma.shape[1]
A = np.zeros((len(windows) - 1, M))
window = 0
for site in ts.sites():
while windows[window + 1] <= site.position:
window += 1
assert windows[window] <= site.position < windows[window + 1]
A[window] += sigma[site.id]
if span_normalise:
diff = np.zeros((A.shape[0], 1))
diff[:, 0] = np.diff(windows).T
A /= diff
return A
def naive_site_general_stat(
ts, W, f, windows=None, polarised=False, span_normalise=True
):
n, K = W.shape
# Hack to determine M
M = len(f(W[0]))
sigma = np.zeros((ts.num_sites, M))
for tree in ts.trees():
X = np.zeros((ts.num_nodes, K))
X[ts.samples()] = W
for u in tree.nodes(order="postorder"):
for v in tree.children(u):
X[u] += X[v]
for site in tree.sites():
state_map = collections.defaultdict(functools.partial(np.zeros, K))
state_map[site.ancestral_state] = sum(X[root] for root in tree.roots)
for mutation in site.mutations:
state_map[mutation.derived_state] += X[mutation.node]
if mutation.parent != tskit.NULL:
parent = site.mutations[mutation.parent - site.mutations[0].id]
state_map[parent.derived_state] -= X[mutation.node]
else:
state_map[site.ancestral_state] -= X[mutation.node]
if polarised:
del state_map[site.ancestral_state]
sigma[site.id] += sum(map(f, state_map.values()))
return windowed_sitewise_stat(
ts, sigma, ts.parse_windows(windows), span_normalise=span_normalise
)
def site_general_stat(
ts,
sample_weights,
summary_func,
windows=None,
time_windows=None,
polarised=False,
span_normalise=True,
):
"""
Problem: 'sites' is different that the other windowing options
because if we output by site we don't want to normalize by length of the window.
Solution: we pass an argument "normalize", to the windowing function.
"""
assert time_windows is None
windows = ts.parse_windows(windows)
num_windows = windows.shape[0] - 1
n, state_dim = sample_weights.shape
# Determine result_dim
(result_dim,) = summary_func(sample_weights[0]).shape
result = np.zeros((num_windows, result_dim))
state = np.zeros((ts.num_nodes, state_dim))
state[ts.samples()] = sample_weights
total_weight = np.sum(sample_weights, axis=0)
site_index = 0
mutation_index = 0
window_index = 0
sites = ts.tables.sites
mutations = ts.tables.mutations
parent = np.zeros(ts.num_nodes, dtype=np.int32) - 1
for (left, right), edges_out, edges_in in ts.edge_diffs():
for edge in edges_out:
u = edge.parent
while u != -1:
state[u] -= state[edge.child]
u = parent[u]
parent[edge.child] = -1
for edge in edges_in:
parent[edge.child] = edge.parent
u = edge.parent
while u != -1:
state[u] += state[edge.child]
u = parent[u]
while site_index < len(sites) and sites.position[site_index] < right:
assert left <= sites.position[site_index]
ancestral_state = sites[site_index].ancestral_state
allele_state = collections.defaultdict(
functools.partial(np.zeros, state_dim)
)
allele_state[ancestral_state][:] = total_weight
while (
mutation_index < len(mutations)
and mutations[mutation_index].site == site_index
):
mutation = mutations[mutation_index]
allele_state[mutation.derived_state] += state[mutation.node]
if mutation.parent != -1:
parent_allele = mutations[mutation.parent].derived_state
allele_state[parent_allele] -= state[mutation.node]
else:
allele_state[ancestral_state] -= state[mutation.node]
mutation_index += 1
if polarised:
del allele_state[ancestral_state]
pos = sites.position[site_index]
while windows[window_index + 1] <= pos:
window_index += 1
assert windows[window_index] <= pos < windows[window_index + 1]
site_result = result[window_index]
for _allele, value in allele_state.items():
site_result += summary_func(value)
site_index += 1
if span_normalise:
for j in range(num_windows):
span = windows[j + 1] - windows[j]
result[j] /= span
return result
##############################
# Node general stat algorithms
##############################
def naive_node_general_stat(
ts, W, f, windows=None, polarised=False, span_normalise=True
):
windows = ts.parse_windows(windows)
n, K = W.shape
M = f(W[0]).shape[0]
total = np.sum(W, axis=0)
sigma = np.zeros((ts.num_trees, ts.num_nodes, M))
for tree in ts.trees():
X = np.zeros((ts.num_nodes, K))
X[ts.samples()] = W
for u in tree.nodes(order="postorder"):
for v in tree.children(u):
X[u] += X[v]
s = np.zeros((ts.num_nodes, M))
for u in range(ts.num_nodes):
s[u] = f(X[u])
if not polarised:
s[u] += f(total - X[u])
sigma[tree.index] = s * tree.span
return windowed_tree_stat(ts, sigma, windows, span_normalise=span_normalise)
def node_general_stat(
ts,
sample_weights,
summary_func,
windows=None,
time_windows=None,
polarised=False,
span_normalise=True,
):
"""
Efficient implementation of the algorithm used as the basis for the
underlying C version.
"""
assert time_windows is None
n, state_dim = sample_weights.shape
windows = ts.parse_windows(windows)
num_windows = windows.shape[0] - 1
result_dim = summary_func(sample_weights[0]).shape[0]
result = np.zeros((num_windows, ts.num_nodes, result_dim))
state = np.zeros((ts.num_nodes, state_dim))
state[ts.samples()] = sample_weights
total_weight = np.sum(sample_weights, axis=0)
def node_summary(u):
s = summary_func(state[u])
if not polarised:
s += summary_func(total_weight - state[u])
return s
window_index = 0
parent = np.zeros(ts.num_nodes, dtype=np.int32) - 1
# contains summary_func(state[u]) for each node
current_values = np.zeros((ts.num_nodes, result_dim))
for u in range(ts.num_nodes):
current_values[u] = node_summary(u)
# contains the location of the last time we updated the output for a node.
last_update = np.zeros((ts.num_nodes, 1))
for (t_left, t_right), edges_out, edges_in in ts.edge_diffs():
for edge in edges_out:
u = edge.child
v = edge.parent
while v != -1:
result[window_index, v] += (t_left - last_update[v]) * current_values[v]
last_update[v] = t_left
state[v] -= state[u]
current_values[v] = node_summary(v)
v = parent[v]
parent[u] = -1
for edge in edges_in:
u = edge.child
v = edge.parent
parent[u] = v
while v != -1:
result[window_index, v] += (t_left - last_update[v]) * current_values[v]
last_update[v] = t_left
state[v] += state[u]
current_values[v] = node_summary(v)
v = parent[v]
# Update the windows
while window_index < num_windows and windows[window_index + 1] <= t_right:
w_right = windows[window_index + 1]
# Flush the contribution of all nodes to the current window.
for u in range(ts.num_nodes):
result[window_index, u] += (w_right - last_update[u]) * current_values[
u
]
last_update[u] = w_right
window_index += 1
assert window_index == windows.shape[0] - 1
if span_normalise:
for j in range(num_windows):
result[j] /= windows[j + 1] - windows[j]
return result
def general_stat(
ts,
sample_weights,
summary_func,
windows=None,
time_windows=None,
polarised=False,
mode="site",
span_normalise=True,
):
"""
General iterface for algorithms above. Directly corresponds to the interface
for TreeSequence.general_stat.
"""
method_map = {
"site": site_general_stat,
"node": node_general_stat,
"branch": branch_general_stat,
}
return method_map[mode](
ts,
sample_weights,
summary_func,
windows=windows,
time_windows=time_windows,
polarised=polarised,
span_normalise=span_normalise,
)
def upper_tri_to_matrix(x):
"""
Given x, a vector of entries of the upper triangle of a matrix
in row-major order, including the diagonal, return the corresponding matrix.
"""
# n^2 + n = 2 u => n = (-1 + sqrt(1 + 8*u))/2
n = int((np.sqrt(1 + 8 * len(x)) - 1) / 2.0)
out = np.ones((n, n))
k = 0
for i in range(n):
for j in range(i, n):
out[i, j] = out[j, i] = x[k]
k += 1
return out
##################################
# Test cases
##################################
class StatsTestCase:
"""
Provides convenience functions.
"""
def assertListAlmostEqual(self, x, y):
assert len(x) == len(y)
for a, b in zip(x, y):
self.assertAlmostEqual(a, b)
def assertArrayEqual(self, x, y):
nt.assert_equal(x, y)
def assertArrayAlmostEqual(self, x, y, atol=1e-6, rtol=1e-7):
nt.assert_allclose(x, y, atol=atol, rtol=rtol)
def identity_f(self, ts):
return lambda x: x * (x < ts.num_samples)
def cumsum_f(self, ts):
return lambda x: np.cumsum(x) * (x < ts.num_samples)
def sum_f(self, ts, k=1):
return lambda x: np.array([sum(x) * (sum(x) < 2 * ts.num_samples)] * k)
class TopologyExamplesMixin:
"""
Defines a set of test cases on different example tree sequence topologies.
Derived classes need to define a 'verify' function which will perform the
actual tests.
"""
def test_single_tree_sequence_length(self):
ts = msprime.simulate(6, length=10, random_seed=1)
self.verify(ts)
def test_single_tree_multiple_roots(self):
ts = msprime.simulate(8, random_seed=1, end_time=0.5)
assert ts.first().num_roots > 1
self.verify(ts)
def test_many_trees(self, ts_4_recomb_fixture):
ts = ts_4_recomb_fixture
assert ts.num_trees > 2
self.verify(ts)
# @pytest.mark.skip(reason="Skipping short sequence length test")
def test_short_sequence_length(self):
ts = msprime.simulate(6, length=0.5, recombination_rate=2, random_seed=1)
assert ts.num_trees > 2
self.verify(ts)
@pytest.mark.slow
def test_wright_fisher_unsimplified(self, wf_sim_fixture):
self.verify(wf_sim_fixture["unsimplified"])
@pytest.mark.slow
def test_wright_fisher_initial_generation(self, wf_sim_fixture):
self.verify(wf_sim_fixture["initial_generation"])
def test_wright_fisher_initial_generation_no_deep_history(self, wf_sim_fixture):
self.verify(wf_sim_fixture["no_deep_history"])
def test_wright_fisher_unsimplified_multiple_roots(self, wf_sim_fixture):
self.verify(wf_sim_fixture["unsimplified_multi_roots"])
def test_wright_fisher_simplified(self, wf_sim_fixture):
self.verify(wf_sim_fixture["simplified"])
def test_wright_fisher_simplified_multiple_roots(self, wf_sim_fixture):
self.verify(wf_sim_fixture["simplified_multi_roots"])
def test_empty_ts(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(1, 0)
tables.nodes.add_row(1, 0)
tables.nodes.add_row(1, 0)
tables.nodes.add_row(1, 0)
ts = tables.tree_sequence()
self.verify(ts)
def test_non_sample_ancestry(self):
tables = tskit.TableCollection(1.0)
tables.nodes.add_row(1, 0)
tables.nodes.add_row(1, 0)
tables.nodes.add_row(0, 1)
tables.nodes.add_row(0, 0) # 3 is a leaf but not a sample.
# Make sure we have 4 samples for the tests.
tables.nodes.add_row(1, 1)
tables.nodes.add_row(1, 1)
tables.edges.add_row(0, 1, 2, 0)
tables.edges.add_row(0, 1, 2, 1)
tables.edges.add_row(0, 1, 4, 3)
ts = tables.tree_sequence()
self.verify(ts)
# Fixtures for commonly used simulations in test_tree_stats.py
# Naming convention: ts_{num_samples}_{features}_fixture
# Features: mut (mutations), recomb (recombination), highmut/highrecomb (high rates)
@pytest.fixture(scope="session")
def ts_6_fixture():
"""Basic 6-sample tree sequence, no mutations or recombination."""
return msprime.simulate(6, random_seed=1)
@pytest.fixture(scope="session")
def ts_10_recomb_fixture():
"""10-sample tree sequence with recombination (used 3+ times)."""
return msprime.simulate(10, recombination_rate=1, random_seed=2)
@pytest.fixture(scope="session")
def ts_10_mut_fixture():
"""10-sample tree sequence with mutations (used 10 times)."""
return msprime.simulate(10, mutation_rate=1, random_seed=1)
@pytest.fixture(scope="session")
def ts_10_mut_recomb_fixture():
"""10-sample tree sequence with mutations and recombination (used 5+ times)."""
return msprime.simulate(10, mutation_rate=1, recombination_rate=2, random_seed=1)
@pytest.fixture(scope="session")
def ts_4_recomb_fixture():
"""4-sample tree sequence with recombination (used 4+ times)."""
return msprime.simulate(4, recombination_rate=1, random_seed=2)
@pytest.fixture(scope="session")
def ts_12_highrecomb_fixture():
"""12-sample tree sequence with high recombination (used 4+ times)."""
return msprime.simulate(12, recombination_rate=3, random_seed=2)
@pytest.fixture(scope="session")
def ts_44_recomb_fixture():
"""44-sample tree sequence with recombination (used 2 times)."""
return msprime.simulate(44, recombination_rate=1, random_seed=2)
@pytest.fixture(scope="session")
def ts_ancestry_10_fixture():
"""Standard ancestry simulation for 10 samples."""
return msprime.sim_ancestry(10, random_seed=1, sequence_length=10)
@pytest.fixture(scope="session")
def ts_6_length_factory_fixture():
"""Factory fixture for 6-sample tree sequences with variable length."""
def _make_ts(length):
return msprime.simulate(
6, length=length, recombination_rate=2, mutation_rate=1, random_seed=1
)
return _make_ts
# Wright-Fisher simulation fixtures
@pytest.fixture(scope="session")
def wf_sim_fixture():
"""Common Wright-Fisher simulations used across test classes."""
# Pre-compute all common WF simulations
simulations = {}
# Used in TopologyExamplesMixin tests
tables = wf.wf_sim(
4, 5, seed=1, deep_history=True, initial_generation_samples=False, num_loci=5
)
tables.sort()
simulations["unsimplified"] = tables.tree_sequence()
tables = wf.wf_sim(
6, 5, seed=3, deep_history=True, initial_generation_samples=True, num_loci=2
)
tables.sort()
tables.simplify()
simulations["initial_generation"] = tables.tree_sequence()
tables = wf.wf_sim(
6, 15, seed=202, deep_history=False, initial_generation_samples=True, num_loci=5
)
tables.sort()
tables.simplify()
simulations["no_deep_history"] = tables.tree_sequence()
tables = wf.wf_sim(
6, 5, seed=1, deep_history=False, initial_generation_samples=False, num_loci=4
)
tables.sort()
simulations["unsimplified_multi_roots"] = tables.tree_sequence()
tables = wf.wf_sim(
5, 8, seed=1, deep_history=True, initial_generation_samples=False, num_loci=5
)
tables.sort()
simulations["simplified"] = tables.tree_sequence().simplify()
tables = wf.wf_sim(
6, 8, seed=1, deep_history=False, initial_generation_samples=False, num_loci=3
)
tables.sort()
simulations["simplified_multi_roots"] = tables.tree_sequence().simplify()
return simulations
@pytest.fixture(scope="session")
def wf_mut_sim_fixture():
"""Wright-Fisher simulations with mutations for MutatedTopologyExamplesMixin."""
simulations = {}
# With mutations for site-based tests
tables = wf.wf_sim(
4, 5, seed=1, deep_history=True, initial_generation_samples=False, num_loci=10
)
tables.sort()
ts = msprime.mutate(tables.tree_sequence(), rate=0.05, random_seed=234)
simulations["unsimplified"] = ts
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)
simulations["initial_generation"] = ts
tables = wf.wf_sim(
7, 15, seed=202, deep_history=False, initial_generation_samples=True, num_loci=5
)
tables.sort()
tables.simplify()
ts = msprime.mutate(tables.tree_sequence(), rate=0.1, random_seed=3)
simulations["no_deep_history"] = ts
tables = wf.wf_sim(
8, 15, seed=1, deep_history=False, initial_generation_samples=False, num_loci=20
)
tables.sort()
ts = msprime.mutate(tables.tree_sequence(), rate=0.01, random_seed=2)
simulations["unsimplified_multi_roots"] = ts
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 = tsutil.jukes_cantor(ts, 10, 0.01, seed=1)
simulations["simplified"] = ts
return simulations
class MutatedTopologyExamplesMixin:
"""
Defines a set of test cases on different example tree sequence topologies.
Derived classes need to define a 'verify' function which will perform the
actual tests.
"""
def test_single_tree_no_sites(self, ts_6_fixture):
ts = ts_6_fixture
assert ts.num_sites == 0
self.verify(ts)
def test_ghost_allele(self):
tables = tskit.TableCollection(1)
tables.nodes.add_row(flags=1, time=0)
tables.nodes.add_row(flags=1, time=0)
tables.nodes.add_row(flags=0, time=1)
tables.edges.add_row(0, 1, 2, 0)
tables.edges.add_row(0, 1, 2, 1)
tables.sites.add_row(position=0.5, ancestral_state="A")
# Make sure there's 4 samples
tables.nodes.add_row(flags=1, time=0)
tables.nodes.add_row(flags=1, time=0)
# The ghost mutation that's never seen in the genotypes
tables.mutations.add_row(site=0, node=0, derived_state="T")
tables.mutations.add_row(site=0, node=0, derived_state="G", parent=0)
ts = tables.tree_sequence()
self.verify(ts)
def test_ghost_allele_all_ancestral(self):
tables = tskit.TableCollection(1)
tables.nodes.add_row(flags=1, time=0)
tables.nodes.add_row(flags=1, time=0)
tables.nodes.add_row(flags=0, time=1)
# Make sure there's 4 samples
tables.nodes.add_row(flags=1, time=0)
tables.nodes.add_row(flags=1, time=0)
tables.edges.add_row(0, 1, 2, 0)
tables.edges.add_row(0, 1, 2, 1)
tables.sites.add_row(position=0.5, ancestral_state="A")
tables.mutations.add_row(site=0, node=0, derived_state="T")
# Mutate back to the ancestral state so that all genotypes are zero
tables.mutations.add_row(site=0, node=0, derived_state="A", parent=0)
ts = tables.tree_sequence()
self.verify(ts)
def test_non_sample_ancestry(self):
# 2.00┊ 5 ┊
# ┊ ┏━━┻━┓ ┊
# 1.00┊ 4 ┃ ┊
# ┊ ┏━┳┻┳━┓ ┃ ┊
# 0.00┊ 0 1 2 3 6 ┊
# 0.00 1.00
tables = tskit.TableCollection(1)
# Four sample nodes
for j in range(4):
tables.nodes.add_row(flags=1, time=0)
tables.edges.add_row(0, 1, 4, j)
# Their MRCA, 4, joins to older ancestor 5
tables.nodes.add_row(flags=0, time=1)
tables.nodes.add_row(flags=0, time=2)
tables.edges.add_row(0, 1, 5, 4)
# Which has non-sample leaf at time 0
tables.nodes.add_row(flags=0, time=0)
tables.edges.add_row(0, 1, 5, 6)
# Two sites with mutations. One over the MRCA of the
# samples so it's fixed at 1 and one over the non sample
# leaf so that samples are fixed at zero.
tables.sites.add_row(position=0.25, ancestral_state="0")
tables.sites.add_row(position=0.5, ancestral_state="0")
tables.mutations.add_row(site=0, node=4, derived_state="1")
tables.mutations.add_row(site=1, node=6, derived_state="1")
ts = tables.tree_sequence()
self.verify(ts)
def test_single_tree_infinite_sites(self, ts_10_mut_fixture):
ts = ts_10_mut_fixture
assert ts.num_sites > 0
self.verify(ts)
def test_single_tree_sites_no_mutations(self, ts_6_fixture):
ts = ts_6_fixture
tables = ts.dump_tables()
tables.sites.add_row(0.1, "a")
tables.sites.add_row(0.2, "aaa")
self.verify(tables.tree_sequence())
@pytest.mark.slow
def test_single_tree_jukes_cantor(self, ts_10_mut_fixture):
ts = ts_10_mut_fixture
ts = tsutil.jukes_cantor(ts, 20, 1, seed=10)
self.verify(ts)
def test_single_tree_single_site_many_silent(self, ts_6_fixture):
ts = ts_6_fixture
ts = tsutil.jukes_cantor(ts, 1, 20, seed=10)
self.verify(ts)
def test_single_tree_multichar_mutations(self, ts_10_mut_fixture):
ts = ts_10_mut_fixture
ts = tsutil.insert_multichar_mutations(ts)
self.verify(ts)
def test_many_trees_infinite_sites(self, ts_10_mut_recomb_fixture):
ts = ts_10_mut_recomb_fixture
assert ts.num_sites > 0
assert ts.num_trees > 2
self.verify(ts)
@pytest.mark.slow
def test_many_trees_sequence_length_infinite_sites(
self, ts_6_length_factory_fixture
):
for L in [0.5, 1.5, 3.3333]:
ts = ts_6_length_factory_fixture(L)
self.verify(ts)
def test_wright_fisher_unsimplified(self, wf_mut_sim_fixture):
ts = wf_mut_sim_fixture["unsimplified"]
assert ts.num_sites > 0
self.verify(ts)
def test_wright_fisher_initial_generation(self, wf_mut_sim_fixture):
ts = wf_mut_sim_fixture["initial_generation"]
assert ts.num_sites > 0
self.verify(ts)