-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathtsutil.py
1742 lines (1585 loc) · 62.6 KB
/
tsutil.py
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-2019 Tskit Developers
# Copyright (C) 2017 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.
"""
A collection of utilities to edit and construct tree sequences.
"""
import collections
import functools
import json
import random
import string
import struct
import numpy as np
import tskit
import tskit.provenance as provenance
def random_bytes(max_length):
"""
Returns a random bytearray of the specified maximum length.
"""
length = random.randint(0, max_length)
return bytearray(random.randint(0, 255) for _ in range(length))
def random_strings(max_length):
"""
Returns a random bytearray of the specified maximum length.
"""
length = random.randint(0, max_length)
return "".join(random.choice(string.printable) for _ in range(length))
def add_provenance(provenance_table, method_name):
d = provenance.get_provenance_dict({"command": f"tsutil.{method_name}"})
provenance_table.add_row(json.dumps(d))
def subsample_sites(ts, num_sites):
"""
Returns a copy of the specified tree sequence with a random subsample of the
specified number of sites.
"""
t = ts.dump_tables()
t.sites.reset()
t.mutations.reset()
sites_to_keep = set(random.sample(list(range(ts.num_sites)), num_sites))
for site in ts.sites():
if site.id in sites_to_keep:
site_id = t.sites.append(site)
for mutation in site.mutations:
t.mutations.append(mutation.replace(site=site_id))
add_provenance(t.provenances, "subsample_sites")
return t.tree_sequence()
def decapitate(ts, num_edges):
"""
Returns a copy of the specified tree sequence in which the specified number of
edges have been retained.
"""
t = ts.dump_tables()
t.edges.set_columns(
left=t.edges.left[:num_edges],
right=t.edges.right[:num_edges],
parent=t.edges.parent[:num_edges],
child=t.edges.child[:num_edges],
)
add_provenance(t.provenances, "decapitate")
# Simplify to get rid of any mutations that are lying around above roots.
t.simplify()
return t.tree_sequence()
def insert_branch_mutations(ts, mutations_per_branch=1):
"""
Returns a copy of the specified tree sequence with a mutation on every branch
in every tree.
"""
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
for tree in ts.trees():
site = tables.sites.add_row(position=tree.interval.left, ancestral_state="0")
for root in tree.roots:
state = {tskit.NULL: 0}
mutation = {tskit.NULL: -1}
stack = [root]
while len(stack) > 0:
u = stack.pop()
stack.extend(tree.children(u))
v = tree.parent(u)
state[u] = state[v]
parent = mutation[v]
for _ in range(mutations_per_branch):
state[u] = (state[u] + 1) % 2
metadata = f"{len(tables.mutations)}".encode()
mutation[u] = tables.mutations.add_row(
site=site,
node=u,
derived_state=str(state[u]),
parent=parent,
metadata=metadata,
)
parent = mutation[u]
add_provenance(tables.provenances, "insert_branch_mutations")
return tables.tree_sequence()
def remove_mutation_times(ts):
tables = ts.tables
tables.mutations.time = np.full_like(tables.mutations.time, tskit.UNKNOWN_TIME)
return tables.tree_sequence()
def insert_discrete_time_mutations(ts, num_times=4, num_sites=10):
"""
Inserts mutations in the tree sequence at regularly-spaced num_sites
positions, at only a discrete set of times (the same for all trees): at
num_times times evenly spaced between 0 and the maximum time.
"""
tables = ts.tables
tables.sites.clear()
tables.mutations.clear()
height = max([t.time(t.roots[0]) for t in ts.trees()])
for j, pos in enumerate(np.linspace(0, tables.sequence_length, num_sites + 1)[:-1]):
anc = "X" * j
tables.sites.add_row(position=pos, ancestral_state=anc)
t = ts.at(pos)
for k, s in enumerate(np.linspace(0, height, num_times)):
for n in t.nodes():
if t.time(n) <= s and (
(t.parent(n) == tskit.NULL) or (t.time(t.parent(n)) > s)
):
tables.mutations.add_row(
site=j, node=n, derived_state=anc + str(k), time=s
)
k += 1
tables.sort()
tables.build_index()
tables.compute_mutation_parents()
return tables.tree_sequence()
def insert_branch_sites(ts):
"""
Returns a copy of the specified tree sequence with a site on every branch
of every tree.
"""
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
for tree in ts.trees():
left, right = tree.interval
delta = (right - left) / len(list(tree.nodes()))
x = left
for u in tree.nodes():
if tree.parent(u) != tskit.NULL:
site = tables.sites.add_row(position=x, ancestral_state="0")
tables.mutations.add_row(site=site, node=u, derived_state="1")
x += delta
add_provenance(tables.provenances, "insert_branch_sites")
return tables.tree_sequence()
def insert_multichar_mutations(ts, seed=1, max_len=10):
"""
Returns a copy of the specified tree sequence with multiple chararacter
mutations on a randomly chosen branch in every tree.
"""
rng = random.Random(seed)
letters = ["A", "C", "T", "G"]
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
for tree in ts.trees():
ancestral_state = rng.choice(letters) * rng.randint(0, max_len)
site = tables.sites.add_row(
position=tree.interval.left, ancestral_state=ancestral_state
)
nodes = list(tree.nodes())
nodes.remove(tree.root)
u = rng.choice(nodes)
derived_state = ancestral_state
while ancestral_state == derived_state:
derived_state = rng.choice(letters) * rng.randint(0, max_len)
tables.mutations.add_row(site=site, node=u, derived_state=derived_state)
add_provenance(tables.provenances, "insert_multichar_mutations")
return tables.tree_sequence()
def insert_random_ploidy_individuals(
ts, min_ploidy=0, max_ploidy=5, max_dimension=3, seed=1
):
"""
Takes random contiguous subsets of the samples an assigns them to individuals.
Also creates random locations in variable dimensions in the unit interval,
and assigns random parents (including NULL parents).
"""
rng = random.Random(seed)
samples = np.array(ts.samples(), dtype=int)
j = 0
tables = ts.dump_tables()
tables.individuals.clear()
individual = tables.nodes.individual[:]
individual[:] = tskit.NULL
ind_id = -1
while j < len(samples):
ploidy = rng.randint(min_ploidy, max_ploidy)
nodes = samples[j : min(j + ploidy, len(samples))]
dimension = rng.randint(0, max_dimension)
location = [rng.random() for _ in range(dimension)]
parents = rng.sample(range(-1, 1 + ind_id), min(1 + ind_id, rng.randint(0, 3)))
ind_id = tables.individuals.add_row(location=location, parents=parents)
individual[nodes] = ind_id
j += ploidy
tables.nodes.individual = individual
return tables.tree_sequence()
def insert_individuals(ts, nodes=None, ploidy=1):
"""
Inserts individuals into the tree sequence using the specified list
of node (or use all sample nodes if None) with the specified ploidy by combining
ploidy-sized chunks of the list. Add metadata to the individuals so we can
track them
"""
if nodes is None:
nodes = ts.samples()
assert len(nodes) % ploidy == 0 # To allow mixed ploidies we could comment this out
tables = ts.dump_tables()
tables.individuals.clear()
individual = tables.nodes.individual[:]
individual[:] = tskit.NULL
j = 0
while j < len(nodes):
nodes_in_individual = nodes[j : min(len(nodes), j + ploidy)]
# should we warn here if nodes[j : j + ploidy] are at different times?
# probably not, as although this is unusual, it is actually allowed
ind_id = tables.individuals.add_row(
metadata=f"orig_id {tables.individuals.num_rows}".encode()
)
individual[nodes_in_individual] = ind_id
j += ploidy
tables.nodes.individual = individual
return tables.tree_sequence()
def mark_metadata(ts, table_name, prefix="orig_id:"):
"""
Add metadata to all rows of the form prefix + row_number
"""
tables = ts.dump_tables()
table = getattr(tables, table_name)
table.packset_metadata([(prefix + str(i)).encode() for i in range(table.num_rows)])
return tables.tree_sequence()
def permute_nodes(ts, node_map):
"""
Returns a copy of the specified tree sequence such that the nodes are
permuted according to the specified map.
"""
tables = ts.dump_tables()
tables.nodes.clear()
tables.edges.clear()
tables.mutations.clear()
# Mapping from nodes in the new tree sequence back to nodes in the original
reverse_map = [0 for _ in node_map]
for j in range(ts.num_nodes):
reverse_map[node_map[j]] = j
old_nodes = list(ts.nodes())
for j in range(ts.num_nodes):
old_node = old_nodes[reverse_map[j]]
tables.nodes.append(old_node)
for edge in ts.edges():
tables.edges.append(
edge.replace(parent=node_map[edge.parent], child=node_map[edge.child])
)
for site in ts.sites():
for mutation in site.mutations:
tables.mutations.append(
mutation.replace(site=site.id, node=node_map[mutation.node])
)
tables.sort()
add_provenance(tables.provenances, "permute_nodes")
return tables.tree_sequence()
def insert_redundant_breakpoints(ts):
"""
Builds a new tree sequence containing redundant breakpoints.
"""
tables = ts.dump_tables()
tables.edges.reset()
for r in ts.edges():
x = r.left + (r.right - r.left) / 2
tables.edges.append(r.replace(right=x))
tables.edges.append(r.replace(left=x))
add_provenance(tables.provenances, "insert_redundant_breakpoints")
new_ts = tables.tree_sequence()
assert new_ts.num_edges == 2 * ts.num_edges
return new_ts
def single_childify(ts):
"""
Builds a new equivalent tree sequence which contains an extra node in the
middle of all existing branches.
"""
tables = ts.dump_tables()
mutations_above_node = collections.defaultdict(list)
for mut in tables.mutations:
mutations_above_node[mut.node].append(mut)
mutations_on_edge = collections.defaultdict(list)
for edge_idx, edge in enumerate(tables.edges):
for mut in mutations_above_node[edge.child]:
if edge.left <= tables.sites[mut.site].position < edge.right:
mutations_on_edge[edge_idx].append(mut)
time = tables.nodes.time[:]
tables.edges.reset()
tables.mutations.reset()
for edge in ts.edges():
# Insert a new node in between the parent and child.
t = time[edge.child] + (time[edge.parent] - time[edge.child]) / 2
u = tables.nodes.add_row(time=t)
tables.edges.append(edge.replace(parent=u))
tables.edges.append(edge.replace(child=u))
for mut in mutations_on_edge[edge.id]:
if mut.time < t:
tables.mutations.append(mut)
else:
tables.mutations.append(mut.replace(node=u))
tables.sort()
add_provenance(tables.provenances, "insert_redundant_breakpoints")
return tables.tree_sequence()
def add_random_metadata(ts, seed=1, max_length=10):
"""
Returns a copy of the specified tree sequence with random metadata assigned
to the nodes, sites and mutations.
"""
tables = ts.dump_tables()
np.random.seed(seed)
length = np.random.randint(0, max_length, ts.num_nodes)
offset = np.cumsum(np.hstack(([0], length)), dtype=np.uint32)
# Older versions of numpy didn't have a dtype argument for randint, so
# must use astype instead.
metadata = np.random.randint(-127, 127, offset[-1]).astype(np.int8)
nodes = tables.nodes
nodes.set_columns(
flags=nodes.flags,
population=nodes.population,
time=nodes.time,
metadata_offset=offset,
metadata=metadata,
individual=nodes.individual,
)
length = np.random.randint(0, max_length, ts.num_sites)
offset = np.cumsum(np.hstack(([0], length)), dtype=np.uint32)
metadata = np.random.randint(-127, 127, offset[-1]).astype(np.int8)
sites = tables.sites
sites.set_columns(
position=sites.position,
ancestral_state=sites.ancestral_state,
ancestral_state_offset=sites.ancestral_state_offset,
metadata_offset=offset,
metadata=metadata,
)
length = np.random.randint(0, max_length, ts.num_mutations)
offset = np.cumsum(np.hstack(([0], length)), dtype=np.uint32)
metadata = np.random.randint(-127, 127, offset[-1]).astype(np.int8)
mutations = tables.mutations
mutations.set_columns(
site=mutations.site,
node=mutations.node,
time=mutations.time,
parent=mutations.parent,
derived_state=mutations.derived_state,
derived_state_offset=mutations.derived_state_offset,
metadata_offset=offset,
metadata=metadata,
)
length = np.random.randint(0, max_length, ts.num_individuals)
offset = np.cumsum(np.hstack(([0], length)), dtype=np.uint32)
metadata = np.random.randint(-127, 127, offset[-1]).astype(np.int8)
individuals = tables.individuals
individuals.set_columns(
flags=individuals.flags,
location=individuals.location,
location_offset=individuals.location_offset,
parents=individuals.parents,
parents_offset=individuals.parents_offset,
metadata_offset=offset,
metadata=metadata,
)
length = np.random.randint(0, max_length, ts.num_populations)
offset = np.cumsum(np.hstack(([0], length)), dtype=np.uint32)
metadata = np.random.randint(-127, 127, offset[-1]).astype(np.int8)
populations = tables.populations
populations.set_columns(metadata_offset=offset, metadata=metadata)
add_provenance(tables.provenances, "add_random_metadata")
ts = tables.tree_sequence()
return ts
def jiggle_samples(ts):
"""
Returns a copy of the specified tree sequence with the sample nodes switched
around. The first n / 2 existing samples become non samples, and the last
n / 2 node become samples.
"""
tables = ts.dump_tables()
nodes = tables.nodes
flags = nodes.flags
oldest_parent = tables.edges.parent[-1]
n = ts.sample_size
flags[: n // 2] = 0
flags[oldest_parent - n // 2 : oldest_parent] = 1
nodes.set_columns(flags, nodes.time)
add_provenance(tables.provenances, "jiggle_samples")
return tables.tree_sequence()
def generate_site_mutations(
tree, position, mu, site_table, mutation_table, multiple_per_node=True
):
"""
Generates mutations for the site at the specified position on the specified
tree. Mutations happen at rate mu along each branch. The site and mutation
information are recorded in the specified tables. Note that this records
more than one mutation per edge.
"""
assert tree.interval.left <= position < tree.interval.right
states = ["A", "C", "G", "T"]
ancestral_state = random.choice(states)
site_table.add_row(position, ancestral_state)
site = site_table.num_rows - 1
for root in tree.roots:
stack = [(root, ancestral_state, tskit.NULL)]
while len(stack) != 0:
u, state, parent = stack.pop()
if u != root:
branch_length = tree.branch_length(u)
x = random.expovariate(mu)
new_state = state
while x < branch_length:
new_state = random.choice(states)
if multiple_per_node:
mutation_table.add_row(site, u, new_state, parent)
parent = mutation_table.num_rows - 1
state = new_state
x += random.expovariate(mu)
else:
if not multiple_per_node:
mutation_table.add_row(site, u, new_state, parent)
parent = mutation_table.num_rows - 1
state = new_state
stack.extend(reversed([(v, state, parent) for v in tree.children(u)]))
def jukes_cantor(ts, num_sites, mu, multiple_per_node=True, seed=None):
"""
Returns a copy of the specified tree sequence with Jukes-Cantor mutations
applied at the specified rate at the specified number of sites. Site positions
are chosen uniformly.
"""
random.seed(seed)
positions = [ts.sequence_length * random.random() for _ in range(num_sites)]
positions.sort()
tables = ts.dump_tables()
tables.sites.clear()
tables.mutations.clear()
trees = ts.trees()
t = next(trees)
for position in positions:
while position >= t.interval.right:
t = next(trees)
generate_site_mutations(
t,
position,
mu,
tables.sites,
tables.mutations,
multiple_per_node=multiple_per_node,
)
add_provenance(tables.provenances, "jukes_cantor")
new_ts = tables.tree_sequence()
return new_ts
def caterpillar_tree(n, num_sites=0, num_mutations=1):
"""
Returns caterpillar tree with n samples. For each of the sites and
path of at most n - 2 mutations are put down along the internal
nodes. Each site gets exactly the same set of mutations.
"""
if num_sites > 0 and num_mutations > n - 2:
raise ValueError("At most n - 2 mutations allowed")
tables = tskit.TableCollection(1)
for _ in range(n):
tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0)
last_node = 0
# Add the internal nodes
for j in range(n - 1):
u = tables.nodes.add_row(time=j + 1)
tables.edges.add_row(0, tables.sequence_length, u, last_node)
tables.edges.add_row(0, tables.sequence_length, u, j + 1)
last_node = u
for j in range(num_sites):
tables.sites.add_row(position=(j + 1) / n, ancestral_state="0")
node = 2 * n - 3
state = 0
for _ in range(num_mutations):
state = (state + 1) % 2
tables.mutations.add_row(site=j, derived_state=str(state), node=node)
node -= 1
tables.sort()
tables.build_index()
tables.compute_mutation_parents()
return tables.tree_sequence()
def compute_mutation_parent(ts):
"""
Compute the `parent` column of a MutationTable. Correct computation uses
topological information in the nodes and edges, as well as the fact that
each mutation must be listed after the mutation on whose background it
occurred (i.e., its parent).
:param TreeSequence ts: The tree sequence to compute for. Need not
have a valid mutation parent column.
"""
mutation_parent = np.zeros(ts.num_mutations, dtype=np.int32) - 1
# Maps nodes to the bottom mutation on each branch
bottom_mutation = np.zeros(ts.num_nodes, dtype=np.int32) - 1
for tree in ts.trees():
for site in tree.sites():
# Go forward through the mutations creating a mapping from the
# mutations to the nodes. If we see more than one mutation
# at a node, then these must be parents since we're assuming
# they are in order.
for mutation in site.mutations:
if bottom_mutation[mutation.node] != tskit.NULL:
mutation_parent[mutation.id] = bottom_mutation[mutation.node]
bottom_mutation[mutation.node] = mutation.id
# There's no point in checking the first mutation, since this cannot
# have a parent.
for mutation in site.mutations[1:]:
if mutation_parent[mutation.id] == tskit.NULL:
v = tree.parent(mutation.node)
# Traverse upwards until we find a another mutation or root.
while v != tskit.NULL and bottom_mutation[v] == tskit.NULL:
v = tree.parent(v)
if v != tskit.NULL:
mutation_parent[mutation.id] = bottom_mutation[v]
# Reset the maps for the next site.
for mutation in site.mutations:
bottom_mutation[mutation.node] = tskit.NULL
assert np.all(bottom_mutation == -1)
return mutation_parent
def py_subset(
tables,
nodes,
record_provenance=True,
reorder_populations=True,
remove_unreferenced=True,
):
"""
Naive implementation of the TableCollection.subset method using the Python API.
"""
if np.any(nodes > tables.nodes.num_rows) or np.any(nodes < 0):
raise ValueError("Nodes out of bounds.")
full = tables.copy()
tables.clear()
# mapping from old to new ids
node_map = {}
ind_map = {tskit.NULL: tskit.NULL}
pop_map = {tskit.NULL: tskit.NULL}
if not reorder_populations:
for j, pop in enumerate(full.populations):
pop_map[j] = j
tables.populations.append(pop)
# first build individual map
if not remove_unreferenced:
keep_ind = [True for _ in full.individuals]
else:
keep_ind = [False for _ in full.individuals]
for old_id in nodes:
i = full.nodes[old_id].individual
if i != tskit.NULL:
keep_ind[i] = True
new_ind_id = 0
for j, k in enumerate(keep_ind):
if k:
ind_map[j] = new_ind_id
new_ind_id += 1
# now the individual table
for j, k in enumerate(keep_ind):
if k:
ind = full.individuals[j]
new_ind_id = tables.individuals.append(
ind.replace(parents=[ind_map[i] for i in ind.parents if i in ind_map])
)
assert new_ind_id == ind_map[j]
for old_id in nodes:
node = full.nodes[old_id]
if node.population not in pop_map and node.population != tskit.NULL:
pop = full.populations[node.population]
new_pop_id = tables.populations.append(pop)
pop_map[node.population] = new_pop_id
new_id = tables.nodes.append(
node.replace(
population=pop_map[node.population],
individual=ind_map[node.individual],
)
)
node_map[old_id] = new_id
if not remove_unreferenced:
for j, ind in enumerate(full.populations):
if j not in pop_map:
pop_map[j] = tables.populations.append(ind)
for edge in full.edges:
if edge.child in nodes and edge.parent in nodes:
tables.edges.append(
edge.replace(parent=node_map[edge.parent], child=node_map[edge.child])
)
if full.migrations.num_rows > 0:
raise ValueError("Migrations are currently not supported in this operation.")
site_map = {}
if not remove_unreferenced:
for j, site in enumerate(full.sites):
site_map[j] = tables.sites.append(site)
mutation_map = {tskit.NULL: tskit.NULL}
for i, mut in enumerate(full.mutations):
if mut.node in nodes:
if mut.site not in site_map:
site = full.sites[mut.site]
new_site = tables.sites.append(site)
site_map[mut.site] = new_site
new_mut = tables.mutations.append(
mut.replace(
site=site_map[mut.site],
node=node_map[mut.node],
parent=mutation_map.get(mut.parent, tskit.NULL),
)
)
mutation_map[i] = new_mut
def py_union(tables, other, nodes, record_provenance=True, add_populations=True):
"""
Python implementation of TableCollection.union().
"""
# mappings of id in other to new id in tables
# the +1 is to take care of mapping tskit.NULL(-1) to tskit.NULL
pop_map = [tskit.NULL for _ in range(other.populations.num_rows + 1)]
ind_map = [tskit.NULL for _ in range(other.individuals.num_rows + 1)]
node_map = [tskit.NULL for _ in range(other.nodes.num_rows + 1)]
site_map = [tskit.NULL for _ in range(other.sites.num_rows + 1)]
mut_map = [tskit.NULL for _ in range(other.mutations.num_rows + 1)]
original_num_individuals = tables.individuals.num_rows
for other_id, node in enumerate(other.nodes):
if nodes[other_id] != tskit.NULL and node.individual != tskit.NULL:
ind_map[node.individual] = tables.nodes[nodes[other_id]].individual
for other_id, node in enumerate(other.nodes):
if nodes[other_id] != tskit.NULL:
node_map[other_id] = nodes[other_id]
else:
if ind_map[node.individual] == tskit.NULL and node.individual != tskit.NULL:
ind = other.individuals[node.individual]
ind_id = tables.individuals.append(ind)
ind_map[node.individual] = ind_id
if pop_map[node.population] == tskit.NULL and node.population != tskit.NULL:
if not add_populations:
pop_map[node.population] = node.population
else:
pop = other.populations[node.population]
pop_id = tables.populations.append(pop)
pop_map[node.population] = pop_id
node_id = tables.nodes.append(
node.replace(
population=pop_map[node.population],
individual=ind_map[node.individual],
)
)
node_map[other_id] = node_id
individuals = tables.individuals
new_parents = individuals.parents
for i in range(
individuals.parents_offset[original_num_individuals], len(individuals.parents)
):
new_parents[i] = ind_map[individuals.parents[i]]
individuals.parents = new_parents
for edge in other.edges:
if (nodes[edge.parent] == tskit.NULL) or (nodes[edge.child] == tskit.NULL):
tables.edges.append(
edge.replace(parent=node_map[edge.parent], child=node_map[edge.child])
)
for other_id, mut in enumerate(other.mutations):
if nodes[mut.node] == tskit.NULL:
# add site: may already be in tables, but we deduplicate
if site_map[mut.site] == tskit.NULL:
site = other.sites[mut.site]
site_id = tables.sites.append(site)
site_map[mut.site] = site_id
mut_id = tables.mutations.append(
mut.replace(
site=site_map[mut.site],
node=node_map[mut.node],
parent=tskit.NULL,
)
)
mut_map[other_id] = mut_id
# migration table
# grafting provenance table
if record_provenance:
pass
# sorting, deduplicating sites, and re-computing mutation parents
tables.sort()
tables.deduplicate_sites()
# need to sort again since after deduplicating sites, mutations may not be
# sorted by time within sites
tables.sort()
tables.build_index()
tables.compute_mutation_parents()
def compute_mutation_times(ts):
"""
Compute the `time` column of a MutationTable in a TableCollection.
Finds the set of mutations on an edge that share a site and spreads
the times evenly over the edge.
:param TreeSequence ts: The tree sequence to compute for. Need not
have a valid mutation time column.
"""
tables = ts.dump_tables()
mutations = tables.mutations
mutations_above_node = collections.defaultdict(list)
for mut_idx, mut in enumerate(mutations):
mutations_above_node[mut.node].append((mut_idx, mut))
mutations_at_site_on_edge = collections.defaultdict(list)
for edge_idx, edge in enumerate(tables.edges):
for mut_idx, mut in mutations_above_node[edge.child]:
if edge.left <= tables.sites[mut.site].position < edge.right:
mutations_at_site_on_edge[(mut.site, edge_idx)].append(mut_idx)
edges = tables.edges
nodes = tables.nodes
times = np.full(len(mutations), -1, dtype=np.float64)
for (_, edge_idx), edge_mutations in mutations_at_site_on_edge.items():
start_time = nodes[edges[edge_idx].child].time
end_time = nodes[edges[edge_idx].parent].time
duration = end_time - start_time
for i, mut_idx in enumerate(edge_mutations):
times[mut_idx] = end_time - (
duration * ((i + 1) / (len(edge_mutations) + 1))
)
# Mutations not on a edge (i.e. above a root) get given their node's time
for i in range(len(mutations)):
if times[i] == -1:
times[i] = nodes[mutations[i].node].time
tables.mutations.time = times
tables.sort()
return tables.mutations.time
def shuffle_tables(
tables,
seed,
shuffle_edges=True,
shuffle_populations=True,
shuffle_individuals=True,
shuffle_sites=True,
shuffle_mutations=True,
shuffle_migrations=True,
keep_mutation_parent_order=False,
):
"""
Randomizes the order of rows in (possibly) all except the Node table. Note
that if mutations are completely shuffled, then TableCollection.sort() will
not necessarily produce valid tables (unless all mutation times are present
and distinct), since currently only canonicalise puts parent mutations
before children. However, setting keep_mutation_parent_order to True will
maintain the order of mutations within each site.
:param TableCollection tables: The table collection that is shuffled (in place).
"""
rng = random.Random(seed)
orig = tables.copy()
tables.nodes.clear()
tables.individuals.clear()
tables.populations.clear()
tables.edges.clear()
tables.sites.clear()
tables.mutations.clear()
tables.drop_index()
# populations
randomised_pops = list(enumerate(orig.populations))
if shuffle_populations:
rng.shuffle(randomised_pops)
pop_id_map = {tskit.NULL: tskit.NULL}
for j, p in randomised_pops:
pop_id_map[j] = tables.populations.append(p)
# individuals
randomised_inds = list(enumerate(orig.individuals))
if shuffle_individuals:
rng.shuffle(randomised_inds)
ind_id_map = {tskit.NULL: tskit.NULL}
for j, i in randomised_inds:
ind_id_map[j] = tables.individuals.append(i)
tables.individuals.parents = [
tskit.NULL if i == tskit.NULL else ind_id_map[i]
for i in tables.individuals.parents
]
# nodes (same order, but remapped populations and individuals)
for n in orig.nodes:
tables.nodes.append(
n.replace(
population=pop_id_map[n.population],
individual=ind_id_map[n.individual],
)
)
# edges
randomised_edges = list(orig.edges)
if shuffle_edges:
rng.shuffle(randomised_edges)
for e in randomised_edges:
tables.edges.append(e)
# migrations
randomised_migrations = list(orig.migrations)
if shuffle_migrations:
rng.shuffle(randomised_migrations)
for m in randomised_migrations:
tables.migrations.append(
m.replace(source=pop_id_map[m.source], dest=pop_id_map[m.dest])
)
# sites
randomised_sites = list(enumerate(orig.sites))
if shuffle_sites:
rng.shuffle(randomised_sites)
site_id_map = {}
for j, s in randomised_sites:
site_id_map[j] = tables.sites.append(s)
# mutations
randomised_mutations = list(enumerate(orig.mutations))
if shuffle_mutations:
if keep_mutation_parent_order:
# randomise *except* keeping parent mutations before children
mut_site_order = [mut.site for mut in orig.mutations]
rng.shuffle(mut_site_order)
mut_by_site = {s: [] for s in mut_site_order}
for j, m in enumerate(orig.mutations):
mut_by_site[m.site].insert(0, (j, m))
randomised_mutations = []
for s in mut_site_order:
randomised_mutations.append(mut_by_site[s].pop())
else:
rng.shuffle(randomised_mutations)
mut_id_map = {tskit.NULL: tskit.NULL}
for j, (k, _) in enumerate(randomised_mutations):
mut_id_map[k] = j
for _, m in randomised_mutations:
tables.mutations.append(
m.replace(site=site_id_map[m.site], parent=mut_id_map[m.parent])
)
if keep_mutation_parent_order:
assert np.all(tables.mutations.parent < np.arange(tables.mutations.num_rows))
return tables
def cmp_site(i, j, tables):
ret = tables.sites.position[i] - tables.sites.position[j]
if ret == 0:
ret = i - j
return ret
def cmp_mutation_canonical(i, j, tables, site_order, num_descendants=None):
site_i = tables.mutations.site[i]
site_j = tables.mutations.site[j]
ret = site_order[site_i] - site_order[site_j]
if (
ret == 0
and (not tskit.is_unknown_time(tables.mutations.time[i]))
and (not tskit.is_unknown_time(tables.mutations.time[j]))
):
ret = tables.mutations.time[j] - tables.mutations.time[i]
if ret == 0:
ret = num_descendants[j] - num_descendants[i]
if ret == 0:
ret = tables.mutations.node[i] - tables.mutations.node[j]
if ret == 0:
ret = i - j
return ret
def cmp_mutation(i, j, tables, site_order):
site_i = tables.mutations.site[i]
site_j = tables.mutations.site[j]
ret = site_order[site_i] - site_order[site_j]
if (
ret == 0
and (not tskit.is_unknown_time(tables.mutations.time[i]))
and (not tskit.is_unknown_time(tables.mutations.time[j]))
):
ret = tables.mutations.time[j] - tables.mutations.time[i]
if ret == 0:
ret = i - j
return ret
def cmp_edge(i, j, tables):
ret = (
tables.nodes.time[tables.edges.parent[i]]
- tables.nodes.time[tables.edges.parent[j]]
)
if ret == 0:
ret = tables.edges.parent[i] - tables.edges.parent[j]
if ret == 0:
ret = tables.edges.child[i] - tables.edges.child[j]
if ret == 0:
ret = tables.edges.left[i] - tables.edges.left[j]
return ret
def cmp_migration(i, j, tables):
ret = tables.migrations.time[i] - tables.migrations.time[j]
if ret == 0:
ret = tables.migrations.source[i] - tables.migrations.source[j]
if ret == 0:
ret = tables.migrations.dest[i] - tables.migrations.dest[j]
if ret == 0:
ret = tables.migrations.left[i] - tables.migrations.left[j]
if ret == 0:
ret = tables.migrations.node[i] - tables.migrations.node[j]
return ret
def cmp_individual_canonical(i, j, tables, num_descendants):
ret = num_descendants[j] - num_descendants[i]
if ret == 0:
node_i = node_j = tables.nodes.num_rows
ni = np.where(tables.nodes.individual == i)[0]
if len(ni) > 0:
node_i = np.min(ni)
nj = np.where(tables.nodes.individual == j)[0]
if len(nj) > 0:
node_j = np.min(nj)
ret = node_i - node_j
if ret == 0:
ret = i - j
return ret
def compute_mutation_num_descendants(tables):
mutations = tables.mutations
num_descendants = np.zeros(mutations.num_rows)