forked from tskit-dev/tskit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_coalrate.py
More file actions
1921 lines (1758 loc) · 76.7 KB
/
test_coalrate.py
File metadata and controls
1921 lines (1758 loc) · 76.7 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) 2024 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 coalescence rate calculation in tskit.
"""
import itertools
import msprime
import numpy as np
import pytest
import tests
import tskit
from tests import tsutil
def _single_tree_example(L, T):
"""
For testing numerical issues with sequence scaling
"""
tables = tskit.TableCollection(sequence_length=L)
tables.nodes.set_columns(
time=np.array([0.0] * 8 + [0.1, 0.2, 0.2, 0.6, 0.8, 1.0]) * T,
flags=np.repeat([1, 0], [8, 6]).astype("uint32"),
)
tables.edges.set_columns(
left=np.repeat([0], 13),
right=np.repeat([L], 13),
parent=np.array(
[8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13], dtype="int32"
),
child=np.array([1, 2, 3, 8, 0, 7, 4, 5, 10, 6, 11, 9, 12], dtype="int32"),
)
tables.populations.add_row()
tables.populations.add_row()
tables.nodes.population = np.array(
[0, 1, 1, 1, 0, 0, 1, 0] + [tskit.NULL] * 6, dtype="int32"
)
return tables.tree_sequence()
# --- prototype --- #
def _nonmissing_window_span(ts, windows):
num_windows = windows.size - 1
sequence_length = ts.sequence_length
missing_span = np.zeros(num_windows)
missing = 0.0
num_edges = 0
w = 0
position = tsutil.TreePosition(ts)
while position.interval.right < sequence_length:
position.next()
left, right = position.interval.left, position.interval.right
out_range, in_range = position.out_range, position.in_range
for _ in range(out_range.start, out_range.stop): # edges_out
num_edges -= 1
for _ in range(in_range.start, in_range.stop): # edges_out
num_edges += 1
if num_edges == 0:
missing += right - left
while w < num_windows and windows[w + 1] <= right: # flush window
missing_span[w] = missing
missing = 0.0
if num_edges == 0:
x = max(0, right - windows[w + 1])
missing_span[w] -= x
missing += x
w += 1
window_span = np.diff(windows) - missing_span
return window_span
def _pair_coalescence_weights(
coalescing_pairs,
nodes_time,
):
return coalescing_pairs
def _pair_coalescence_rates(
coalescing_pairs,
nodes_time,
time_windows,
):
"""
Estimate pair coalescence rate from empirical CDF. `coalescing_pairs` and
`nodes_time` are assumed to have been aggregated into time bins (by
summation/averaging respectively). The terminal bin(s) use a different
estimator (the mean time since the start of the first terminal bin).
"""
assert time_windows.size - 1 == coalescing_pairs.size
assert time_windows.size - 1 == nodes_time.size
assert np.all(np.diff(time_windows) > 0)
assert np.isfinite(time_windows[0])
assert time_windows[-1] == np.inf
num_time_windows = time_windows.size - 1
coalescence_rate = np.full(num_time_windows, np.nan)
coalesced = 0.0
for j in np.arange(num_time_windows, 0, -1): # find last window containing nodes
if not np.isnan(nodes_time[j - 1]):
break
for i in range(j):
a, b = time_windows[i : i + 2]
assert 0.0 <= coalescing_pairs[i] <= 1.0
if i + 1 == j:
coalescence_rate[i] = 1 / (nodes_time[i] - a)
break
else:
rate = -np.log(1 - coalescing_pairs[i] / (1 - coalesced)) / (b - a)
assert rate >= 0
coalescence_rate[i] = abs(rate)
coalesced += coalescing_pairs[i]
return coalescence_rate
def _pair_coalescence_quantiles(
coalescing_pairs,
nodes_time,
quantiles,
):
"""
Estimate `quantiles` of the distribution of `nodes_time` weighted by
`coalescing_pairs`, by inverting the empirical CDF. Nodes are assumed
to be sorted in ascending time order.
"""
assert nodes_time.size == coalescing_pairs.size
assert np.all(np.diff(quantiles) > 0)
assert np.all(np.logical_and(0 <= quantiles, quantiles <= 1))
num_nodes = coalescing_pairs.size
num_quantiles = quantiles.size
output = np.full(num_quantiles, np.nan)
i, j = 0, 0
coalesced = 0.0
time = -np.inf
while i < num_nodes:
if coalescing_pairs[i] > 0:
coalesced += coalescing_pairs[i]
assert nodes_time[i] > time
time = nodes_time[i]
while j < num_quantiles and quantiles[j] <= coalesced:
output[j] = time
j += 1
i += 1
if quantiles[-1] == 1.0:
output[-1] = time
return output
def _pair_coalescence_stat(
ts,
summary_func,
summary_func_dim,
summary_func_kwargs,
sample_sets=None,
indexes=None,
windows=None,
time_windows=None,
span_normalise=True,
pair_normalise=False,
):
"""
Apply `summary_func(node_weights, node_times, node_order, **summary_func_kwargs)` to
the empirical distribution of pair coalescence times for each index / window.
"""
if sample_sets is None:
sample_sets = [list(ts.samples())]
for s in sample_sets:
if len(s) == 0:
raise ValueError("Sample sets must contain at least one element")
if not (min(s) >= 0 and max(s) < ts.num_nodes):
raise ValueError("Sample is out of bounds")
drop_middle_dimension = False
if indexes is None:
drop_middle_dimension = True
if len(sample_sets) == 1:
indexes = [(0, 0)]
elif len(sample_sets) == 2:
indexes = [(0, 1)]
else:
raise ValueError(
"Must specify indexes if there are more than two sample sets"
)
for i in indexes:
if not len(i) == 2:
raise ValueError("Sample set indexes must be length two")
if not (min(i) >= 0 and max(i) < len(sample_sets)):
raise ValueError("Sample set index is out of bounds")
drop_left_dimension = False
if windows is None:
drop_left_dimension = True
windows = np.array([0.0, ts.sequence_length])
if not (isinstance(windows, np.ndarray) and windows.size > 1):
raise ValueError("Windows must be an array of breakpoints")
if not (windows[0] == 0.0 and windows[-1] == ts.sequence_length):
raise ValueError("First and last window breaks must be sequence boundary")
if not np.all(np.diff(windows) > 0):
raise ValueError("Window breaks must be strictly increasing")
if isinstance(time_windows, str) and time_windows == "nodes":
nodes_map = np.arange(ts.num_nodes)
num_time_windows = ts.num_nodes
else:
if not (isinstance(time_windows, np.ndarray) and time_windows.size > 1):
raise ValueError("Time windows must be an array of breakpoints")
if not np.all(np.diff(time_windows) > 0):
raise ValueError("Time windows must be strictly increasing")
if ts.time_units == tskit.TIME_UNITS_UNCALIBRATED:
raise ValueError("Time windows require calibrated node times")
nodes_map = np.searchsorted(time_windows, ts.nodes_time, side="right") - 1
nodes_oob = np.logical_or(nodes_map < 0, nodes_map >= time_windows.size)
nodes_map[nodes_oob] = tskit.NULL
num_time_windows = time_windows.size - 1
num_nodes = ts.num_nodes
num_windows = windows.size - 1
num_sample_sets = len(sample_sets)
num_indexes = len(indexes)
edges_child = ts.edges_child
edges_parent = ts.edges_parent
nodes_time = ts.nodes_time
sequence_length = ts.sequence_length
output_size = summary_func_dim
samples = np.concatenate(sample_sets)
nodes_parent = np.full(num_nodes, tskit.NULL)
nodes_sample = np.zeros((num_nodes, num_sample_sets))
nodes_weight = np.zeros((num_time_windows, num_indexes))
nodes_values = np.zeros((num_time_windows, num_indexes))
coalescing_pairs = np.zeros((num_time_windows, num_indexes))
coalescence_time = np.zeros((num_time_windows, num_indexes))
output = np.zeros((num_windows, output_size, num_indexes))
visited = np.full(num_nodes, False)
total_pairs = np.zeros(num_indexes)
sizes = [len(s) for s in sample_sets]
for i, (j, k) in enumerate(indexes):
if j == k:
total_pairs[i] = sizes[j] * (sizes[k] - 1) / 2
else:
total_pairs[i] = sizes[j] * sizes[k]
if span_normalise:
window_span = _nonmissing_window_span(ts, windows)
for i, s in enumerate(sample_sets): # initialize
nodes_sample[s, i] = 1
sample_counts = nodes_sample.copy()
w = 0
position = tsutil.TreePosition(ts)
while position.interval.right < sequence_length:
position.next()
left, right = position.interval.left, position.interval.right
out_range, in_range = position.out_range, position.in_range
remainder = sequence_length - left
for b in range(out_range.start, out_range.stop): # edges_out
e = out_range.order[b]
p = edges_parent[e]
c = edges_child[e]
nodes_parent[c] = tskit.NULL
inside = sample_counts[c]
while p != tskit.NULL:
u = nodes_map[p]
t = nodes_time[p]
if u != tskit.NULL:
outside = sample_counts[p] - sample_counts[c] - nodes_sample[p]
for i, (j, k) in enumerate(indexes):
weight = inside[j] * outside[k]
if j != k:
weight += inside[k] * outside[j]
coalescing_pairs[u, i] -= weight * remainder
coalescence_time[u, i] -= weight * remainder * t
c, p = p, nodes_parent[p]
p = edges_parent[e]
while p != tskit.NULL:
sample_counts[p] -= inside
p = nodes_parent[p]
for b in range(in_range.start, in_range.stop): # edges_in
e = in_range.order[b]
p = edges_parent[e]
c = edges_child[e]
nodes_parent[c] = p
inside = sample_counts[c]
while p != tskit.NULL:
sample_counts[p] += inside
p = nodes_parent[p]
p = edges_parent[e]
while p != tskit.NULL:
u = nodes_map[p]
t = nodes_time[p]
if u != tskit.NULL:
outside = sample_counts[p] - sample_counts[c] - nodes_sample[p]
for i, (j, k) in enumerate(indexes):
weight = inside[j] * outside[k]
if j != k:
weight += inside[k] * outside[j]
coalescing_pairs[u, i] += weight * remainder
coalescence_time[u, i] += weight * remainder * t
c, p = p, nodes_parent[p]
while w < num_windows and windows[w + 1] <= right: # flush window
remainder = sequence_length - windows[w + 1]
nodes_weight[:] = coalescing_pairs[:]
nodes_values[:] = coalescence_time[:]
coalescing_pairs[:] = 0.0
coalescence_time[:] = 0.0
for c in samples:
p = nodes_parent[c]
while not visited[c] and p != tskit.NULL:
u = nodes_map[p]
t = nodes_time[p]
if u != tskit.NULL:
inside = sample_counts[c]
outside = sample_counts[p] - sample_counts[c] - nodes_sample[p]
for i, (j, k) in enumerate(indexes):
weight = inside[j] * outside[k]
if j != k:
weight += inside[k] * outside[j]
x = weight * remainder / 2
nodes_weight[u, i] -= x
nodes_values[u, i] -= t * x
coalescing_pairs[u, i] += x
coalescence_time[u, i] += t * x
visited[c] = True
p, c = nodes_parent[p], p
for c in samples:
p = nodes_parent[c]
while visited[c] and p != tskit.NULL:
visited[c] = False
p, c = nodes_parent[p], p
for i in range(num_indexes): # normalise values
nonzero = nodes_weight[:, i] > 0
nodes_values[nonzero, i] /= nodes_weight[nonzero, i]
nodes_values[~nonzero, i] = np.nan
if span_normalise:
nodes_weight /= window_span[w]
if pair_normalise:
nodes_weight /= total_pairs[np.newaxis, :]
for i in range(num_indexes): # apply function to empirical distribution
output[w, :, i] = summary_func(
nodes_weight[:, i],
nodes_values[:, i],
**summary_func_kwargs,
)
w += 1
output = output.transpose(0, 2, 1)
if drop_middle_dimension:
output = output.squeeze(1)
if drop_left_dimension:
output = output.squeeze(0)
return output
def proto_pair_coalescence_counts(
ts,
sample_sets=None,
indexes=None,
windows=None,
span_normalise=True,
pair_normalise=False,
time_windows="nodes",
):
"""
Prototype for ts.pair_coalescence_counts.
Calculate the number of coalescing sample pairs per node, summed over
trees and weighted by tree span.
The number of coalescing pairs may be calculated within or between the
non-overlapping lists of samples contained in `sample_sets`. In the
latter case, pairs are counted if they have exactly one member in each
of two sample sets. If `sample_sets` is omitted, a single group
containing all samples is assumed.
The argument `indexes` may be used to specify which pairs of sample
sets to compute the statistic between, and in what order. If
`indexes=None`, then `indexes` is assumed to equal `[(0,0)]` for a
single sample set and `[(0,1)]` for two sample sets. For more than two
sample sets, `indexes` must be explicitly passed.
The argument `time_windows` may be used to count coalescence
events within time intervals (if an array of breakpoints is supplied)
rather than for individual nodes (the default).
The output array has dimension `(windows, indexes, nodes)` with
dimensions dropped when the corresponding argument is set to None.
:param list sample_sets: A list of lists of Node IDs, specifying the
groups of nodes to compute the statistic with, or None.
:param list indexes: A list of 2-tuples, or None.
:param list windows: An increasing list of breakpoints between the
sequence windows to compute the statistic in, or None.
:param bool span_normalise: Whether to divide the result by the span of
the window (defaults to True).
:param bool pair_normalise: Whether to divide the result by the total
number of pairs for a given index (defaults to False).
:param time_windows: Either a string "nodes" or an increasing
list of breakpoints between time intervals.
"""
if isinstance(time_windows, str) and time_windows == "nodes":
summary_func_dim = ts.num_nodes
else:
if not (isinstance(time_windows, np.ndarray) and time_windows.size > 1):
raise ValueError("Time windows must be an array of breakpoints")
if not np.all(np.diff(time_windows) > 0):
raise ValueError("Time windows must be strictly increasing")
if ts.time_units == tskit.TIME_UNITS_UNCALIBRATED:
raise ValueError("Time windows require calibrated node times")
summary_func_dim = time_windows.size - 1
summary_func = _pair_coalescence_weights
summary_func_kwargs = {}
return _pair_coalescence_stat(
ts,
summary_func=summary_func,
summary_func_dim=summary_func_dim,
summary_func_kwargs=summary_func_kwargs,
sample_sets=sample_sets,
indexes=indexes,
windows=windows,
time_windows=time_windows,
span_normalise=span_normalise,
pair_normalise=pair_normalise,
)
def proto_pair_coalescence_rates(
ts,
time_windows,
sample_sets=None,
indexes=None,
windows=None,
):
r"""
Prototype for ts.pair_coalescence_rates.
Estimate the rate at which pairs of samples coalesce within time windows,
from the empirical CDF of pair coalescence times. Assuming that pair
coalescence events follow a nonhomogeneous Poisson process, the empirical
rate for a time window :math:`[a, b)` where `ecdf(b) < 1` is,
..math:
log(1 - \frac{ecdf(b) - ecdf(a)}{1 - ecdf(a)}) / (a - b)
If the last coalescence event is within `[a, b)` so that `ecdf(b) = 1`, then
an estimate of the empirical rate is
..math:
(\mathbb{E}[t | t > a] - a)^{-1}
where :math:`\mathbb{E}[t | t < a]` is the average pair coalescence time
conditional on coalescence after the start of the last epoch.
The first breakpoint in `time_windows` must start at the age of the
samples, and the last must end at infinity.
Pair coalescence rates may be calculated within or between the
non-overlapping lists of samples contained in `sample_sets`. In the
latter case, pairs are counted if they have exactly one member in each
of two sample sets. If `sample_sets` is omitted, a single group
containing all samples is assumed.
The argument `indexes` may be used to specify which pairs of sample
sets to compute the statistic between, and in what order. If
`indexes=None`, then `indexes` is assumed to equal `[(0,0)]` for a
single sample set and `[(0,1)]` for two sample sets. For more than two
sample sets, `indexes` must be explicitly passed.
The output array has dimension `(windows, indexes, time_windows)` with
dimensions dropped when the corresponding argument is set to None.
:param time_windows: An increasing list of breakpoints between time
intervals, starting at the age of the samples and ending at
infinity.
:param list sample_sets: A list of lists of Node IDs, specifying the
groups of nodes to compute the statistic with, or None.
:param list indexes: A list of 2-tuples, or None.
:param list windows: An increasing list of breakpoints between the
sequence windows to compute the statistic in, or None.
"""
# TODO^^^
if not (isinstance(time_windows, np.ndarray) and time_windows.size > 1):
raise ValueError("Time windows must be an array of breakpoints")
if not np.all(np.diff(time_windows) > 0):
raise ValueError("Time windows must be strictly increasing")
if ts.time_units == tskit.TIME_UNITS_UNCALIBRATED:
raise ValueError("Time windows require calibrated node times")
summary_func = _pair_coalescence_rates
summary_func_dim = time_windows.size - 1
summary_func_kwargs = {"time_windows": time_windows}
return _pair_coalescence_stat(
ts,
summary_func=summary_func,
summary_func_dim=summary_func_dim,
summary_func_kwargs=summary_func_kwargs,
sample_sets=sample_sets,
indexes=indexes,
windows=windows,
time_windows=time_windows,
span_normalise=True,
pair_normalise=True,
)
def proto_pair_coalescence_quantiles(
ts,
quantiles,
sample_sets=None,
indexes=None,
windows=None,
):
"""
Prototype for ts.pair_coalescence_quantiles.
Estimate quantiles of pair coalescence times by inverting the empirical
CDF. This is equivalent to the "inverted_cdf" method of `numpy.quantile`
applied to node times, with weights proportional to the number of
coalescing pairs per node (averaged over trees). The weights are calculated
using `pair_coalescence_counts`.
Quantiles of pair coalescence times may be calculated within or
between the non-overlapping lists of samples contained in `sample_sets`. In
the latter case, pairs are counted if they have exactly one member in each
of two sample sets. If `sample_sets` is omitted, a single group containing
all samples is assumed.
The argument `indexes` may be used to specify which pairs of sample sets to
compute coalescences between, and in what order. If `indexes=None`, then
`indexes` is assumed to equal `[(0,0)]` for a single sample set and
`[(0,1)]` for two sample sets. For more than two sample sets, `indexes`
must be explicitly passed.
The output array has dimension `(windows, indexes, quantiles)` with
dimensions dropped when the corresponding argument is set to None.
:param quantiles: A list of breakpoints between [0, 1].
:param list sample_sets: A list of lists of Node IDs, specifying the
groups of nodes to compute the statistic with, or None.
:param list indexes: A list of 2-tuples, or None.
:param list windows: An increasing list of breakpoints between the
sequence windows to compute the statistic in, or None.
"""
if not isinstance(quantiles, np.ndarray):
raise ValueError("Quantiles must be an array of breakpoints")
if not np.all(np.logical_and(quantiles >= 0, quantiles <= 1.0)):
raise ValueError("Quantiles must be in [0, 1]")
summary_func = _pair_coalescence_quantiles
summary_func_dim = quantiles.size
summary_func_kwargs = {"quantiles": quantiles}
time_windows = np.append(
np.unique(ts.nodes_time), np.inf
) # sort nodes in time order
return _pair_coalescence_stat(
ts,
summary_func=summary_func,
summary_func_dim=summary_func_dim,
summary_func_kwargs=summary_func_kwargs,
sample_sets=sample_sets,
indexes=indexes,
windows=windows,
time_windows=time_windows,
span_normalise=True,
pair_normalise=True,
)
# --- testing --- #
def naive_pair_coalescence_counts(ts, sample_set_0, sample_set_1):
"""
Naive implementation of ts.pair_coalescence_counts.
Count pairwise coalescences tree by tree, by enumerating nodes in each
tree. For a binary node, the number of pairs of samples that coalesce in a
given node is the product of the number of samples subtended by the left
and right child. For higher arities, the count is summed over all possible
pairs of children.
"""
output = np.zeros(ts.num_nodes)
for t in ts.trees():
sample_counts = np.zeros((ts.num_nodes, 2), dtype=np.int32)
pair_counts = np.zeros(ts.num_nodes)
for p in t.postorder():
samples = list(t.samples(p))
sample_counts[p, 0] = np.intersect1d(samples, sample_set_0).size
sample_counts[p, 1] = np.intersect1d(samples, sample_set_1).size
for i, j in itertools.combinations(t.children(p), 2):
pair_counts[p] += sample_counts[i, 0] * sample_counts[j, 1]
pair_counts[p] += sample_counts[i, 1] * sample_counts[j, 0]
output += pair_counts * t.span
return output
def _numpy_weighted_quantile(values, weights, quantiles):
"""
Requires numpy 2.0. Enforcing `weights > 0` avoids odd behaviour where
numpy assigns the 0th quantile to the sample minimum, even if this minimum
has zero weight.
"""
assert np.all(weights >= 0.0)
return np.quantile(
values[weights > 0],
quantiles,
weights=weights[weights > 0] / weights.sum(),
method="inverted_cdf",
)
def _numpy_hazard_rate(values, weights, breaks):
"""
Estimate hazard rate from empirical CDF over intervals
"""
assert np.all(weights >= 0)
assert np.all(np.diff(breaks) >= 0)
assert np.isfinite(breaks[0]) # should equal sample time
assert ~np.isfinite(breaks[-1])
assert np.sum(weights) < 1.0 or np.isclose(np.sum(weights), 1.0)
values = values[weights > 0]
weights = weights[weights > 0]
assert breaks[0] < np.min(values)
max_value = np.max(values)
rates = np.full(breaks.size - 1, np.nan)
for i, (a, b) in enumerate(zip(breaks[:-1], breaks[1:])):
if a < max_value <= b: # terminal window
keep = values >= a
mean = np.sum(values[keep] * weights[keep]) / np.sum(weights[keep])
rates[i] = 1.0 / (mean - a)
break
else:
wa = np.sum(weights[values < a])
wb = np.sum(weights[values < b])
rates[i] = np.log(1 - (wb - wa) / (1 - wa)) / (b - a)
assert rates[i] <= 0.0
rates[i] = abs(rates[i])
return rates
def convert_to_nonsuccinct(ts):
"""
Give the edges and internal nodes in each tree distinct IDs
"""
tables = tskit.TableCollection(sequence_length=ts.sequence_length)
for _ in range(ts.num_populations):
tables.populations.add_row()
nodes_count = 0
for n in ts.samples():
tables.nodes.add_row(
time=ts.nodes_time[n],
flags=ts.nodes_flags[n],
population=ts.nodes_population[n],
)
nodes_count += 1
for t in ts.trees():
nodes_map = {n: n for n in ts.samples()}
for n in t.nodes():
if t.num_samples(n) > 1:
tables.nodes.add_row(
time=ts.nodes_time[n],
flags=ts.nodes_flags[n],
population=ts.nodes_population[n],
)
nodes_map[n] = nodes_count
nodes_count += 1
for n in t.nodes():
if t.edge(n) != tskit.NULL:
tables.edges.add_row(
parent=nodes_map[t.parent(n)],
child=nodes_map[n],
left=t.interval.left,
right=t.interval.right,
)
tables.sort()
ts_unroll = tables.tree_sequence()
assert nodes_count == ts_unroll.num_nodes
return ts_unroll
class TestCoalescingPairsOneTree:
"""
Test against worked example (single tree)
"""
def example_ts(self):
"""
10.0┊ 13 ┊
┊ ┏━━┻━━┓ ┊
8.0┊ 12 ┃ ┊
┊ ┏━┻━┓ ┃ ┊
6.0┊ 11 ┃ ┃ ┊
┊ ┏━━╋━┓ ┃ ┃ ┊
2.0┊ 10 ┃ ┃ ┃ 9 ┊
┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊
1.0┊ ┃ ┃ ┃ ┃ ┃ 8 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
0.0┊ 0 7 4 5 6 1 2 3 ┊
┊ A A A A B B B B ┊
"""
tables = tskit.TableCollection(sequence_length=100)
tables.nodes.set_columns(
time=np.array([0] * 8 + [1, 2, 2, 6, 8, 10]),
flags=np.repeat([1, 0], [8, 6]).astype("uint32"),
)
tables.edges.set_columns(
left=np.repeat([0], 13),
right=np.repeat([100], 13),
parent=np.array(
[8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13], dtype="int32"
),
child=np.array([1, 2, 3, 8, 0, 7, 4, 5, 10, 6, 11, 9, 12], dtype="int32"),
)
tables.populations.add_row()
tables.populations.add_row()
tables.nodes.population = np.array(
[0, 1, 1, 1, 0, 0, 1, 0] + [tskit.NULL] * 6, dtype="int32"
)
return tables.tree_sequence()
def test_total_pairs(self):
"""
┊ 15 pairs ┊
┊ ┏━━┻━━┓ ┊
┊ 4 ┃ ┊
┊ ┏━┻━┓ ┃ ┊
┊ 5 ┃ ┃ ┊
┊ ┏━━╋━┓ ┃ ┃ ┊
┊ 1 ┃ ┃ ┃ 2 ┊
┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊
┊ ┃ ┃ ┃ ┃ ┃ 1 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
┊ 0 0 0 0 0 0 0 0 ┊
"""
ts = self.example_ts()
check = np.array([0.0] * 8 + [1, 2, 1, 5, 4, 15])
implm = ts.pair_coalescence_counts()
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(ts)
np.testing.assert_allclose(proto, check)
def test_population_pairs(self):
"""
┊ AA 0 pairs ┊ AB 12 pairs ┊ BB 3 pairs ┊
┊ ┏━━┻━━┓ ┊ ┏━━┻━━┓ ┊ ┏━━┻━━┓ ┊
┊ 0 ┃ ┊ 4 ┃ ┊ 0 ┃ ┊
┊ ┏━┻━┓ ┃ ┊ ┏━┻━┓ ┃ ┊ ┏━┻━┓ ┃ ┊
┊ 5 ┃ ┃ ┊ 0 ┃ ┃ ┊ 0 ┃ ┃ ┊
┊ ┏━━╋━┓ ┃ ┃ ┊ ┏━━╋━┓ ┃ ┃ ┊ ┏━━╋━┓ ┃ ┃ ┊
┊ 1 ┃ ┃ ┃ 0 ┊ 0 ┃ ┃ ┃ 0 ┊ 0 ┃ ┃ ┃ 2 ┊
┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊
┊ ┃ ┃ ┃ ┃ ┃ 0 ┃ ┊ ┃ ┃ ┃ ┃ ┃ 0 ┃ ┊ ┃ ┃ ┃ ┃ ┃ 1 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
┊ A A A A B B B B ┊ A A A A B B B B ┊ A A A A B B B B ┊
"""
ts = self.example_ts()
ss0 = np.flatnonzero(ts.nodes_population == 0)
ss1 = np.flatnonzero(ts.nodes_population == 1)
indexes = [(0, 0), (0, 1), (1, 1)]
implm = ts.pair_coalescence_counts(sample_sets=[ss0, ss1], indexes=indexes)
check = np.full(implm.shape, np.nan)
check[0] = np.array([0.0] * 8 + [0, 0, 1, 5, 0, 0])
check[1] = np.array([0.0] * 8 + [0, 0, 0, 0, 4, 12])
check[2] = np.array([0.0] * 8 + [1, 2, 0, 0, 0, 3])
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(
ts, sample_sets=[ss0, ss1], indexes=indexes
)
np.testing.assert_allclose(proto, check)
def test_internal_samples(self):
"""
┊ Not ┊ 24 pairs ┊
┊ ┏━━┻━━┓ ┊ ┏━━┻━━┓ ┊
┊ N ┃ ┊ 5 ┃ ┊
┊ ┏━┻━┓ ┃ ┊ ┏━┻━┓ ┃ ┊
┊ S ┃ ┃ ┊ 5 ┃ ┃ ┊
┊ ┏━━╋━┓ ┃ ┃ ┊ ┏━━╋━┓ ┃ ┃ ┊
┊ N ┃ ┃ ┃ Samp ┊ 1 ┃ ┃ ┃ 2 ┊
┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊
┊ ┃ ┃ ┃ ┃ ┃ N ┃ ┊ ┃ ┃ ┃ ┃ ┃ 1 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
┊ S S S S S S S S ┊ 0 0 0 0 0 0 0 0 ┊
"""
ts = self.example_ts()
tables = ts.dump_tables()
nodes_flags = tables.nodes.flags.copy()
nodes_flags[9] = tskit.NODE_IS_SAMPLE
nodes_flags[11] = tskit.NODE_IS_SAMPLE
tables.nodes.flags = nodes_flags
ts = tables.tree_sequence()
assert ts.num_samples == 10
implm = ts.pair_coalescence_counts(span_normalise=False)
check = np.array([0] * 8 + [1, 2, 1, 5, 5, 24]) * ts.sequence_length
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(ts, span_normalise=False)
np.testing.assert_allclose(proto, check)
def test_windows(self):
ts = self.example_ts()
check = np.array([0.0] * 8 + [1, 2, 1, 5, 4, 15]) * ts.sequence_length / 2
implm = ts.pair_coalescence_counts(
windows=np.linspace(0, ts.sequence_length, 3), span_normalise=False
)
np.testing.assert_allclose(implm[0], check)
np.testing.assert_allclose(implm[1], check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(
ts, windows=np.linspace(0, ts.sequence_length, 3), span_normalise=False
)
np.testing.assert_allclose(proto[0], check)
np.testing.assert_allclose(proto[1], check)
def test_time_windows(self):
"""
┊ 15 pairs ┊
┊ ┏━━┻━━┓ ┊
┊ 4 ┃ ┊
7.0┊-----┏━┻━┓---┃----┊
┊ 5 ┃ ┃ ┊
5.0┊--┏━━╋━┓-┃---┃----┊
┊ 1 ┃ ┃ ┃ 2 ┊
┊ ┏┻┓ ┃ ┃ ┃ ┏┻━┓ ┊
┊ ┃ ┃ ┃ ┃ ┃ 1 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
0.0┊ 0 0 0 0 0 0 0 0 ┊
"""
ts = self.example_ts()
time_windows = np.array([0.0, 5.0, 7.0, np.inf])
check = np.array([4, 5, 19]) * ts.sequence_length
implm = ts.pair_coalescence_counts(
span_normalise=False, time_windows=time_windows
)
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(
ts, span_normalise=False, time_windows=time_windows
)
np.testing.assert_allclose(proto, check)
def test_pair_normalise(self):
ts = self.example_ts()
ss0 = np.flatnonzero(ts.nodes_population == 0)
ss1 = np.flatnonzero(ts.nodes_population == 1)
indexes = [(0, 0), (0, 1), (1, 1)]
implm = ts.pair_coalescence_counts(
sample_sets=[ss0, ss1],
indexes=indexes,
pair_normalise=True,
)
check = np.full(implm.shape, np.nan)
check[0] = np.array([0.0] * 8 + [0, 0, 1, 5, 0, 0])
check[1] = np.array([0.0] * 8 + [0, 0, 0, 0, 4, 12])
check[2] = np.array([0.0] * 8 + [1, 2, 0, 0, 0, 3])
total_pairs = np.array([6, 16, 6])
check /= total_pairs[:, np.newaxis]
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(
ts,
sample_sets=[ss0, ss1],
indexes=indexes,
pair_normalise=True,
)
np.testing.assert_allclose(proto, check)
def test_multiple_roots(self):
ts = self.example_ts().decapitate(6.0)
implm = ts.pair_coalescence_counts(pair_normalise=True)
total_pairs = ts.num_samples * (ts.num_samples - 1) / 2
check = np.array([0.0] * 8 + [1, 2, 1, 5, 0, 0, 0, 0])
check /= total_pairs
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(ts, pair_normalise=True)
np.testing.assert_allclose(proto, check)
class TestCoalescingPairsTwoTree:
"""
Test against worked example (two trees)
"""
def example_ts(self, S, L):
"""
0 S L
4.0┊ 7 ┊ 7 ┊
┊ ┏━┻━┓ ┊ ┏━┻━┓ ┊
3.0┊ ┃ 6 ┊ ┃ ┃ ┊
┊ ┃ ┏━┻┓ ┊ ┃ ┃ ┊
2.0┊ ┃ ┃ 5 ┊ ┃ 5 ┊
┊ ┃ ┃ ┏┻┓ ┊ ┃ ┏┻━┓ ┊
1.0┊ ┃ ┃ ┃ ┃ ┊ ┃ 4 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┊ ┃ ┏┻┓ ┃ ┊
0.0┊ 0 1 2 3 ┊ 0 1 2 3 ┊
A A B B A A B B
"""
tables = tskit.TableCollection(sequence_length=L)
tables.nodes.set_columns(
time=np.array([0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0]),
flags=np.array([1, 1, 1, 1, 0, 0, 0, 0], dtype="uint32"),
)
tables.edges.set_columns(
left=np.array([S, S, 0, 0, S, 0, 0, 0, S, 0]),
right=np.array([L, L, S, L, L, S, S, L, L, S]),
parent=np.array([4, 4, 5, 5, 5, 6, 6, 7, 7, 7], dtype="int32"),
child=np.array([1, 2, 2, 3, 4, 1, 5, 0, 5, 6], dtype="int32"),
)
return tables.tree_sequence()
def test_total_pairs(self):
"""
┊ 3 pairs 3 ┊
┊ ┏━┻━┓ ┏━┻━┓ ┊
┊ ┃ 2 ┃ ┃ ┊
┊ ┃ ┏━┻┓ ┃ ┃ ┊
┊ ┃ ┃ 1 ┃ 2 ┊
┊ ┃ ┃ ┏┻┓ ┃ ┏┻━┓ ┊
┊ ┃ ┃ ┃ ┃ ┃ 1 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
┊ 0 0 0 0 0 0 0 0 ┊
0 S L
"""
L, S = 1e8, 1.0
ts = self.example_ts(S, L)
implm = ts.pair_coalescence_counts(span_normalise=False)
check = np.array([0] * 4 + [1 * (L - S), 2 * (L - S) + 1 * S, 2 * S, 3 * L])
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(ts, span_normalise=False)
np.testing.assert_allclose(proto, check)
def test_population_pairs(self):
"""
┊AA ┊AB ┊BB ┊
┊ 1 pairs 1 ┊ 2 pairs 2 ┊ 0 pairs 0 ┊
┊ ┏━┻━┓ ┏━┻━┓ ┊ ┏━┻━┓ ┏━┻━┓ ┊ ┏━┻━┓ ┏━┻━┓ ┊
┊ ┃ 0 ┃ ┃ ┊ ┃ 2 ┃ ┃ ┊ ┃ 0 ┃ ┃ ┊
┊ ┃ ┏━┻┓ ┃ ┃ ┊ ┃ ┏━┻┓ ┃ ┃ ┊ ┃ ┏━┻┓ ┃ ┃ ┊
┊ ┃ ┃ 0 ┃ 0 ┊ ┃ ┃ 0 ┃ 1 ┊ ┃ ┃ 1 ┃ 1 ┊
┊ ┃ ┃ ┏┻┓ ┃ ┏┻━┓ ┊ ┃ ┃ ┏┻┓ ┃ ┏┻━┓ ┊ ┃ ┃ ┏┻┓ ┃ ┏┻━┓ ┊
┊ ┃ ┃ ┃ ┃ ┃ 0 ┃ ┊ ┃ ┃ ┃ ┃ ┃ 1 ┃ ┊ ┃ ┃ ┃ ┃ ┃ 0 ┃ ┊
┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊ ┃ ┃ ┃ ┃ ┃ ┏┻┓ ┃ ┊
┊ A A B B A A B B ┊ A A B B A A B B ┊ A A B B A A B B ┊
0 S L S L S L
"""
L, S = 1e8, 1.0
ts = self.example_ts(S, L)
indexes = [(0, 0), (0, 1), (1, 1)]
implm = ts.pair_coalescence_counts(
sample_sets=[[0, 1], [2, 3]], indexes=indexes, span_normalise=False
)
check = np.empty(implm.shape)
check[0] = np.array([0] * 4 + [0, 0, 0, 1 * L])
check[1] = np.array([0] * 4 + [1 * (L - S), 1 * (L - S), 2 * S, 2 * L])
check[2] = np.array([0] * 4 + [0, 1 * L, 0, 0])
np.testing.assert_allclose(implm, check)
# TODO: remove with prototype
proto = proto_pair_coalescence_counts(
ts, sample_sets=[[0, 1], [2, 3]], indexes=indexes, span_normalise=False