-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathevaluation.py
2159 lines (1985 loc) · 75.3 KB
/
evaluation.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
"""
Script for statistically evaluating various aspects of tsinfer performance.
"""
import argparse
import concurrent.futures
import json
import logging
import os.path
import random
import time
import warnings
import colorama
import daiquiri
import matplotlib as mp
import msprime
import numpy as np
import pandas as pd
import tqdm
import tskit
import tsinfer
import tsinfer.cli as cli
# We break the normal conventions for ordering imports here
# because we have to make this ugly hack to make matplotlib
# work from a shell session and keep flake8 happy.
# Force matplotlib to not use any Xwindows backend.
mp.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
from matplotlib import collections as mc # noqa: E402
import seaborn as sns # noqa: E402
# Set by the CLI.
global _output_format
_output_format = None
def save_figure(basename):
plt.savefig(basename + "." + _output_format)
plt.clf()
def make_errors(v, p):
"""
For each sample an error occurs with probability p. Errors are generated by
sampling values from the stationary distribution, that is, if we have an
allele frequency of f, a 1 is emitted with probability f and a
0 with probability 1 - f. Thus, there is a possibility that an 'error'
will in fact result in the same value.
"""
w = np.copy(v)
if p > 0:
m = v.shape[0]
frequency = np.sum(v) / m
# Randomly choose samples with probability p
samples = np.where(np.random.random(m) < p)[0]
# Generate observations from the stationary distribution.
errors = (np.random.random(samples.shape[0]) < frequency).astype(int)
w[samples] = errors
return w
def make_errors_genotype_model(g, error_probs):
"""
Given an empirically estimated error probability matrix, resample for a particular
variant. Determine variant frequency and true genotype (g0, g1, or g2),
then return observed genotype based on row in error_probs with nearest
frequency. Treat each pair of alleles as a diploid individual.
"""
w = np.copy(g)
# Make diploid (iterate each pair of alleles)
genos = [(w[i], w[i + 1]) for i in range(0, w.shape[0], 2)]
# Record the true genotypes
g0 = [i for i, x in enumerate(genos) if x == (0, 0)]
g1a = [i for i, x in enumerate(genos) if x == (1, 0)]
g1b = [i for i, x in enumerate(genos) if x == (0, 1)]
g2 = [i for i, x in enumerate(genos) if x == (1, 1)]
for idx in g0:
result = [(0, 0), (1, 0), (1, 1)][
np.random.choice(3, p=error_probs[["p00", "p01", "p02"]].values[0])
]
if result == (1, 0):
genos[idx] = [(0, 1), (1, 0)][np.random.choice(2)]
else:
genos[idx] = result
for idx in g1a:
genos[idx] = [(0, 0), (1, 0), (1, 1)][
np.random.choice(3, p=error_probs[["p10", "p11", "p12"]].values[0])
]
for idx in g1b:
genos[idx] = [(0, 0), (0, 1), (1, 1)][
np.random.choice(3, p=error_probs[["p10", "p11", "p12"]].values[0])
]
for idx in g2:
result = [(0, 0), (1, 0), (1, 1)][
np.random.choice(3, p=error_probs[["p20", "p21", "p22"]].values[0])
]
if result == (1, 0):
genos[idx] = [(0, 1), (1, 0)][np.random.choice(2)]
else:
genos[idx] = result
return np.array(sum(genos, ()))
def generate_samples(ts, error_param=0):
"""
Generate a samples file from a simulated ts based on the empirically estimated
error matrix saved in self.error_matrix.
Reject any variants that result in a fixed column.
"""
assert ts.num_sites != 0
sd = tsinfer.SampleData(sequence_length=ts.sequence_length)
try:
e = float(error_param)
for v in ts.variants():
g = v.genotypes if error_param == 0 else make_errors(v.genotypes, e)
sd.add_site(position=v.site.position, alleles=v.alleles, genotypes=g)
except ValueError:
error_matrix = pd.read_csv(error_param)
# Error_param is not a number => is a error file
# First record the allele frequency
for v in ts.variants():
m = v.genotypes.shape[0]
frequency = np.sum(v.genotypes) / m
# Find closest row in error matrix file
closest_row = (error_matrix["freq"] - frequency).abs().argsort()[:1]
closest_freq = error_matrix.iloc[closest_row]
g = make_errors_genotype_model(v.genotypes, closest_freq)
sd.add_site(position=v.site.position, alleles=v.alleles, genotypes=g)
sd.finalise()
return sd
def run_infer(
ts, engine=tsinfer.C_ENGINE, path_compression=True, exact_ancestors=False
):
"""
Runs the perfect inference process on the specified tree sequence.
"""
sample_data = tsinfer.SampleData.from_tree_sequence(ts)
if exact_ancestors:
ancestor_data = tsinfer.AncestorData(
sample_data.sites_position, sample_data.sequence_length
)
tsinfer.build_simulated_ancestors(sample_data, ancestor_data, ts)
ancestor_data.finalise()
else:
ancestor_data = tsinfer.generate_ancestors(sample_data, engine=engine)
ancestors_ts = tsinfer.match_ancestors(
sample_data, ancestor_data, path_compression=path_compression, engine=engine
)
inferred_ts = tsinfer.match_samples(
sample_data, ancestors_ts, path_compression=path_compression, engine=engine
)
return inferred_ts
def edges_performance_worker(args):
simulation_args, tree_metrics, engine = args
before = time.perf_counter()
smc_ts = msprime.simulate(**simulation_args)
sim_time = time.perf_counter() - before
tmp_ts = tsinfer.strip_singletons(smc_ts)
if tmp_ts.num_sites == 0:
warnings.warn("Dropping simulation with no variants")
return {}
before = time.perf_counter()
estimated_ancestors_ts = run_infer(smc_ts, exact_ancestors=False, engine=engine)
estimated_ancestors_time = time.perf_counter() - before
num_children = []
for edgeset in estimated_ancestors_ts.edgesets():
num_children.append(len(edgeset.children))
estimated_ancestors_num_children = np.array(num_children)
before = time.perf_counter()
exact_ancestors_ts = run_infer(smc_ts, exact_ancestors=True, engine=engine)
exact_ancestors_time = time.perf_counter() - before
num_children = []
for edgeset in exact_ancestors_ts.edgesets():
num_children.append(len(edgeset.children))
exact_ancestors_num_children = np.array(num_children)
results = {
"sim_time": sim_time,
"estimated_anc_time": estimated_ancestors_time,
"exact_anc_time": exact_ancestors_time,
"num_sites": smc_ts.num_sites,
"source_num_trees": smc_ts.num_trees,
"estimated_anc_trees": estimated_ancestors_ts.num_trees,
"exact_anc_trees": exact_ancestors_ts.num_trees,
"source_edges": smc_ts.num_edges,
"estimated_anc_edges": estimated_ancestors_ts.num_edges,
"exact_anc_edges": exact_ancestors_ts.num_edges,
"estimated_anc_max_children": np.max(estimated_ancestors_num_children),
"estimated_anc_mean_children": np.mean(estimated_ancestors_num_children),
"exact_anc_max_children": np.max(exact_ancestors_num_children),
"exact_anc_mean_children": np.mean(exact_ancestors_num_children),
}
results.update(simulation_args)
if tree_metrics:
before = time.perf_counter()
breakpoints, kc_distance = tsinfer.compare(smc_ts, exact_ancestors_ts)
d = breakpoints[1:] - breakpoints[:-1]
d /= breakpoints[-1]
exact_anc_kc_distance_weighted = np.sum(kc_distance * d)
exact_anc_perfect_trees = np.sum((kc_distance == 0) * d)
exact_anc_kc_mean = np.mean(kc_distance)
breakpoints, kc_distance = tsinfer.compare(smc_ts, estimated_ancestors_ts)
d = breakpoints[1:] - breakpoints[:-1]
d /= breakpoints[-1]
estimated_anc_kc_distance_weighted = np.sum(kc_distance * d)
estimated_anc_perfect_trees = np.sum((kc_distance == 0) * d)
estimated_anc_kc_mean = np.mean(kc_distance)
tree_metrics_time = time.perf_counter() - before
results.update(
{
"tree_metrics_time": tree_metrics_time,
"exact_anc_kc_distance_weighted": exact_anc_kc_distance_weighted,
"exact_anc_perfect_trees": exact_anc_perfect_trees,
"exact_anc_kc_mean": exact_anc_kc_mean,
"estimated_anc_kc_distance_weighted": estimated_anc_kc_distance_weighted,
"estimated_anc_perfect_trees": estimated_anc_perfect_trees,
"estimated_anc_kc_mean": estimated_anc_kc_mean,
}
)
return results
def run_edges_performance(args):
num_lengths = 10
MB = 10**6
work = []
rng = random.Random()
rng.seed(args.random_seed)
for L in np.linspace(0, args.length, num_lengths + 1)[1:]:
for _ in range(args.num_replicates):
sim_args = {
"sample_size": args.sample_size,
"length": L * MB,
"recombination_rate": args.recombination_rate,
"mutation_rate": args.mutation_rate,
"Ne": args.Ne,
"model": "smc_prime",
"random_seed": rng.randint(1, 2**30),
}
work.append((sim_args, args.compute_tree_metrics, args.engine))
random.shuffle(work)
progress = tqdm.tqdm(total=len(work), disable=not args.progress)
results = []
try:
with concurrent.futures.ProcessPoolExecutor(args.num_processes) as executor:
for result in executor.map(edges_performance_worker, work):
results.append(result)
progress.update()
except KeyboardInterrupt:
pass
progress.close()
df = pd.DataFrame(results)
df.length /= MB
dfg = df.groupby(df.length).mean(numeric_only=True)
# print(dfg.estimated_anc_edges.describe())
print(dfg)
name_format = os.path.join(
args.destination_dir,
"ancestors_n={}_L={}_mu={}_rho={}_{{}}".format(
args.sample_size, args.length, args.mutation_rate, args.recombination_rate
),
)
plt.plot(
dfg.num_sites,
dfg.estimated_anc_edges / dfg.source_edges,
label="estimated ancestors",
)
plt.plot(
dfg.num_sites, dfg.exact_anc_edges / dfg.source_edges, label="exact ancestors"
)
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.ylabel("inferred # edges / source # edges")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("edges"))
plt.plot(
dfg.num_sites,
dfg.estimated_anc_mean_children,
label="estimated ancestors mean",
color="blue",
)
plt.plot(
dfg.num_sites,
dfg.estimated_anc_max_children,
label="estimated ancestors max",
color="blue",
linestyle=":",
)
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.plot(
dfg.num_sites,
dfg.exact_anc_mean_children,
label="exact ancestors mean",
color="red",
)
plt.plot(
dfg.num_sites,
dfg.exact_anc_max_children,
label="exact ancestors max",
color="red",
linestyle=":",
)
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.ylabel("num_children")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("num_children"))
plt.clf()
if args.compute_tree_metrics:
plt.plot(
dfg.num_sites,
dfg.estimated_anc_kc_distance_weighted,
label="estimated ancestors",
)
plt.plot(
dfg.num_sites, dfg.exact_anc_kc_distance_weighted, label="exact ancestors"
)
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.ylabel("Distance weighted KC metric")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("kc_distance_weighted"))
plt.clf()
plt.plot(dfg.num_sites, dfg.estimated_anc_kc_mean, label="estimated ancestors")
plt.plot(dfg.num_sites, dfg.exact_anc_kc_mean, label="exact ancestors")
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.ylabel("Mean KC metric")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("kc_mean"))
plt.clf()
plt.plot(
dfg.num_sites, dfg.estimated_anc_perfect_trees, label="estimated ancestors"
)
plt.plot(dfg.num_sites, dfg.exact_anc_perfect_trees, label="exact ancestors")
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.ylabel("Mean KC metric")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("perfect_trees"))
plt.clf()
def unrank(samples, n):
"""
Unranks the specified set of samples from a possible n into its position
in a lexicographically sorted list of bitstrings.
"""
bitstring = np.zeros(n, dtype=int)
for s in samples:
bitstring[s] = 1
mult = 2 ** np.arange(n, dtype=int)
unranked = np.sum(mult * bitstring)
return unranked
def edge_plot(ts, filename):
n = ts.num_samples
pallete = sns.color_palette("husl", 2**n - 1)
lines = []
colours = []
for tree in ts.trees():
left, right = tree.interval
for u in tree.nodes():
children = tree.children(u)
# Don't bother plotting unary nodes, which will all have the same
# samples under them as their next non-unary descendant
if len(children) > 1:
for c in children:
lines.append([(left, c), (right, c)])
colours.append(pallete[unrank(tree.samples(c), n)])
lc = mc.LineCollection(lines, linewidths=2, colors=colours)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
save_figure(filename)
def run_hotspot_analysis(args):
MB = 10**6
L = args.length * MB
rng = random.Random()
if args.random_seed is not None:
rng.seed(args.random_seed)
breakpoints = np.linspace(0, L, args.num_hotspots + 2)
end = breakpoints[1:-1] + L * args.hotspot_width
breakpoints = np.hstack([breakpoints, end])
breakpoints.sort()
rates = np.zeros_like(breakpoints)
rates[:-1] = args.recombination_rate
# Set the odd elements of the array to be hotspots.
rates[1::2] *= args.hotspot_intensity
recomb_map = msprime.RecombinationMap(list(breakpoints), list(rates))
sim_args = {
"sample_size": args.sample_size,
"recombination_map": recomb_map,
"mutation_rate": args.mutation_rate,
"Ne": args.Ne,
"random_seed": rng.randint(1, 2**30),
}
ts = msprime.simulate(**sim_args)
print("simulated ", ts.num_trees, "trees and", ts.num_sites, "sites")
inferred_ts = run_infer(ts)
num_bins = 100
hotspot_breakpoints = breakpoints
for density in [True, False]:
for x in hotspot_breakpoints[1:-1]:
plt.axvline(x=x, color="k", ls=":")
breakpoints = np.array(list(inferred_ts.breakpoints()))
v, bin_edges = np.histogram(breakpoints, num_bins, density=density)
plt.plot(bin_edges[:-1], v, label="inferred")
breakpoints = np.array(list(ts.breakpoints()))
v, bin_edges = np.histogram(breakpoints, num_bins, density=density)
plt.plot(bin_edges[:-1], v, label="source")
plt.ylabel("Number of breakpoints")
plt.legend()
name_format = os.path.join(
args.destination_dir,
"hotspots_n={}_L={}_mu={}_rho={}_N={}_I={}_W={}_{{}}".format(
args.sample_size,
args.length,
args.mutation_rate,
args.recombination_rate,
args.num_hotspots,
args.hotspot_intensity,
args.hotspot_width,
),
)
save_figure(name_format.format(f"breakpoints_density={density}"))
plt.clf()
print("Generating edge plots")
# TODO add option for colour mapping.
edge_plot(ts, name_format.format("source_edges"))
edge_plot(inferred_ts, name_format.format("dest_edges"))
def ancestor_properties_worker(args):
simulation_args, compute_exact = args
ts = msprime.simulate(**simulation_args)
sample_data = tsinfer.SampleData.from_tree_sequence(ts)
estimated_anc = tsinfer.generate_ancestors(sample_data)
# Show lengths as a fraction of the total.
estimated_anc_length = estimated_anc.ancestors_length / ts.sequence_length
focal_sites = estimated_anc.ancestors_focal_sites[:]
estimated_anc_focal_distance = np.zeros(estimated_anc.num_ancestors)
pos = np.hstack([estimated_anc.sites_position[:] / ts.sequence_length] + [1])
for j in range(estimated_anc.num_ancestors):
focal = focal_sites[j]
if len(focal) > 0:
estimated_anc_focal_distance[j] = pos[focal[-1]] - pos[focal[0]]
results = {
"num_sites": ts.num_sites,
"num_trees": ts.num_trees,
"estimated_anc_num": estimated_anc.num_ancestors,
"estimated_anc_mean_len": np.mean(estimated_anc_length),
"estimated_anc_mean_focal_distance": np.mean(estimated_anc_focal_distance),
}
if compute_exact:
exact_anc = tsinfer.AncestorData(
sample_data.sites_position, sample_data.sequence_length
)
tsinfer.build_simulated_ancestors(sample_data, exact_anc, ts)
exact_anc.finalise()
# Show lengths as a fraction of the total.
exact_anc_length = exact_anc.ancestors_end[:] - exact_anc.ancestors_start[:]
focal_sites = exact_anc.ancestors_focal_sites[:]
pos = np.hstack([exact_anc.sites_position[:] / ts.sequence_length] + [1])
exact_anc_focal_distance = np.zeros(exact_anc.num_ancestors)
for j in range(exact_anc.num_ancestors):
focal = focal_sites[j]
if len(focal) > 0:
exact_anc_focal_distance[j] = pos[focal[-1]] - pos[focal[0]]
results.update(
{
"exact_anc_num": exact_anc.num_ancestors,
"exact_anc_mean_len": np.mean(exact_anc_length),
"exact_anc_mean_focal_distance": np.mean(exact_anc_focal_distance),
}
)
results.update(simulation_args)
return results
def run_ancestor_properties(args):
num_lengths = 10
MB = 10**6
work = []
rng = random.Random()
if args.random_seed is not None:
rng.seed(args.random_seed)
for L in np.linspace(0, args.length, num_lengths + 1)[1:]:
for _ in range(args.num_replicates):
sim_args = {
"sample_size": args.sample_size,
"length": L * MB,
"recombination_rate": args.recombination_rate,
"mutation_rate": args.mutation_rate,
"Ne": args.Ne,
"model": "smc_prime",
"random_seed": rng.randint(1, 2**30),
}
work.append((sim_args, not args.skip_exact))
random.shuffle(work)
progress = tqdm.tqdm(total=len(work), disable=not args.progress)
results = []
try:
with concurrent.futures.ProcessPoolExecutor(args.num_processes) as executor:
for result in executor.map(ancestor_properties_worker, work):
results.append(result)
progress.update()
except KeyboardInterrupt:
pass
progress.close()
df = pd.DataFrame(results)
dfg = df.groupby(df.length).mean(numeric_only=True)
print(dfg)
name_format = os.path.join(
args.destination_dir,
"anc-prop_n={}_L={}_mu={}_rho={}_{{}}".format(
args.sample_size, args.length, args.mutation_rate, args.recombination_rate
),
)
plt.plot(dfg.num_sites, dfg.estimated_anc_num, label="estimated ancestors")
if not args.skip_exact:
plt.plot(dfg.num_sites, dfg.exact_anc_num, label="exact ancestors")
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
# plt.ylabel("inferred # ancestors / exact # ancestors")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("num"))
plt.clf()
plt.plot(dfg.num_sites, dfg.estimated_anc_mean_len, label="estimated ancestors")
if not args.skip_exact:
plt.plot(dfg.num_sites, dfg.exact_anc_mean_len, label="exact ancestors")
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
# plt.ylabel("inferred # ancestors / exact # ancestors")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("mean_len"))
plt.clf()
plt.plot(
dfg.num_sites,
dfg.estimated_anc_mean_focal_distance,
label="estimated ancestors",
)
if not args.skip_exact:
plt.plot(
dfg.num_sites, dfg.exact_anc_mean_focal_distance, label="exact ancestors"
)
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
# plt.ylabel("inferred # ancestors / exact # ancestors")
plt.xlabel("Num sites")
plt.legend()
save_figure(name_format.format("mean_focal_distance"))
plt.clf()
def imputation_accuracy_worker(args):
simulation_args, missing_proportion = args
ts = msprime.simulate(**simulation_args)
np.random.seed(simulation_args["random_seed"])
G = ts.genotype_matrix()
missing = np.random.rand(ts.num_sites, ts.num_samples) < missing_proportion
G[missing] = tskit.MISSING_DATA
with tsinfer.SampleData(ts.sequence_length) as sample_data:
for var in ts.variants():
sample_data.add_site(
var.site.position, alleles=var.alleles, genotypes=G[var.site.id]
)
ts_inferred = tsinfer.infer(sample_data)
assert ts_inferred.num_sites == ts.num_sites
total_missing = np.sum(missing)
num_correct = 0
for v1, v2 in zip(ts.variants(), ts_inferred.variants()):
site_id = v1.site.id
a1 = np.array(v1.alleles)[v1.genotypes]
a2 = np.array(v2.alleles)[v2.genotypes]
original = a1[missing[site_id]]
inferred = a2[missing[site_id]]
num_correct += np.sum(original == inferred)
accuracy = 1
if total_missing > 0:
accuracy = num_correct / total_missing
results = {
"num_trees": ts.num_trees,
"num_sites": ts.num_sites,
"num_samples": ts.num_samples,
"missing_proportion": missing_proportion,
"accuracy": accuracy,
}
return results
def run_imputation_accuracy(args):
MB = 10**6
work = []
rng = random.Random()
if args.random_seed is not None:
rng.seed(args.random_seed)
for missing_proportion in np.linspace(0.01, 0.1, 10):
for _ in range(args.num_replicates):
sim_args = {
"sample_size": args.sample_size,
"length": args.length * MB,
"recombination_rate": args.recombination_rate,
"mutation_rate": args.mutation_rate,
"Ne": args.Ne,
"random_seed": rng.randint(1, 2**30),
}
work.append((sim_args, missing_proportion))
# imputation_accuracy_worker((sim_args, missing_proportion))
rng.shuffle(work)
progress = tqdm.tqdm(total=len(work), disable=not args.progress)
results = []
try:
with concurrent.futures.ProcessPoolExecutor(args.num_processes) as executor:
for result in executor.map(imputation_accuracy_worker, work):
results.append(result)
progress.update()
except KeyboardInterrupt:
pass
progress.close()
df = pd.DataFrame(results)
dfg = df.groupby(df.missing_proportion).mean()
print(dfg)
name_format = os.path.join(
args.destination_dir,
"imputation-accuracy_n={}_L={}_mu={}_rho={}_{{}}".format(
args.sample_size, args.length, args.mutation_rate, args.recombination_rate
),
)
sns.lineplot(x="missing_proportion", y="accuracy", data=df)
plt.title(
"n = {}, mut_rate={}, rec_rate={}, reps={}".format(
args.sample_size,
args.mutation_rate,
args.recombination_rate,
args.num_replicates,
)
)
plt.ylabel("Fraction of missing genotypes imputed correctly")
plt.xlabel("Fraction of genotypes missing")
save_figure(name_format.format("num"))
def running_mean(x, N):
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[N:] - cumsum[:-N]) / float(N)
def running_median(x, N):
idx = np.arange(N) + np.arange(len(x) - N + 1)[:, None]
b = [row[row > 0] for row in x[idx]]
return np.array(list(map(np.median, b)))
class MidpointNormalize(mp.colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
mp.colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
class NormalizeBandWidths(mp.colors.Normalize):
"""
normalise a range into 0..1 where ranges of integers are banded
into a single colour. The init parameter band_widths needs to be
a numpy vector of length the maximum integer encountered
"""
def __init__(self, vmin=None, vmax=None, band_widths=None, clip=False):
self.bands = np.cumsum(band_widths) / np.sum(band_widths)
self.x = np.arange(len(self.bands))
mp.colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
return np.ma.masked_array(np.interp(value, self.x, self.bands))
def sim_true_and_inferred_ancestors(args):
"""
Run a simulation under args and return the samples, plus the true and the inferred
ancestors
"""
MB = 10**6
rng = random.Random(args.random_seed)
np.random.seed(args.random_seed)
sim_args = {
"sample_size": args.sample_size,
"length": args.length * MB,
"recombination_rate": args.recombination_rate,
"mutation_rate": args.mutation_rate,
"Ne": args.Ne,
"model": "smc_prime",
"random_seed": rng.randint(1, 2**30),
}
ts = msprime.simulate(**sim_args)
sample_data = generate_samples(ts, args.error)
inferred_anc = tsinfer.generate_ancestors(sample_data, engine=args.engine)
true_anc = tsinfer.AncestorData(
sample_data.sites_position, sample_data.sequence_length
)
tsinfer.build_simulated_ancestors(sample_data, true_anc, ts)
true_anc.finalise()
return sample_data, true_anc, inferred_anc
def ancestor_data_by_pos(anc1, anc2):
"""
Return indexes into ancestor data, keyed by focal site position, returning only
those indexes where positions are the same for both ancestors. This is useful
e.g. for plotting length v length scatterplots.
"""
anc_by_focal_pos = []
for anc in (anc1, anc2):
position_to_index = {
anc.sites_position[:][site_index]: i
for i, sites in enumerate(anc.ancestors_focal_sites[:])
for site_index in sites
}
anc_by_focal_pos.append(position_to_index)
# NB with error we may not have exactly the same focal sites in exact & estimated
shared_indices = set.intersection(*[set(a.keys()) for a in anc_by_focal_pos])
return {
pos: np.array([anc_by_focal_pos[0][pos], anc_by_focal_pos[1][pos]], np.int64)
for pos in shared_indices
}
def run_ancestor_comparison(args):
sample_data, exact_anc, estimated_anc = sim_true_and_inferred_ancestors(args)
# Convert lengths to kb.
estimated_anc_length = estimated_anc.ancestors_length / 1000
exact_anc_length = exact_anc.ancestors_length / 1000
max_length = sample_data.sequence_length / 1000
try:
err = float(args.error)
except ValueError:
err = args.error.replace("/", "_")
if err.endswith(".csv"):
err = err[: -len(".csv")]
name_format = os.path.join(
args.destination_dir,
"anc-qual_n={}_Ne={}_L={}_mu={}_rho={}_err={}_{{}}".format(
args.sample_size,
args.Ne,
args.length,
args.mutation_rate,
args.recombination_rate,
err,
),
)
if args.store_data:
# TODO Are we using this option for anything?
filename = name_format.format("length.json")
# Don't store the longest (root) ancestor
data = {
"exact_ancestors": exact_anc_length[1:].tolist(),
"estimated_ancestors": estimated_anc_length[1:].tolist(),
}
with open(filename, "w") as f:
json.dump(data, f)
plt.hist(
[exact_anc_length[1:], estimated_anc_length[1:]], label=["Exact", "Estimated"]
)
plt.ylabel("Length (kb)")
plt.legend()
save_figure(name_format.format("length-dist"))
plt.clf()
# NB ancestors_time is not exactly the same as frequency, because frequency
# categories that are not represented in the data will be missed out. If we want a
# true frequency, we therefore need to get it directly from the samples
pos_to_ancestor = {}
estimated_anc.ancestors_focal_freq = np.zeros(estimated_anc.num_ancestors, np.int64)
ancestor_site_position = estimated_anc.sites_position
for a, focal_sites in enumerate(estimated_anc.ancestors_focal_sites[:]):
for focal_site in focal_sites:
pos_to_ancestor[ancestor_site_position[focal_site]] = a
for var in sample_data.variants(ancestor_site_position):
# for i, g in sample_data.genotypes(inference_sites=True):
# pos = sample_data.sites_position[:][i]
pos = var.site.position
freq = np.sum(var.genotypes)
if estimated_anc.ancestors_focal_freq[pos_to_ancestor[pos]]:
# check all focal sites in an ancestor have the same freq
assert freq == estimated_anc.ancestors_focal_freq[pos_to_ancestor[pos]]
estimated_anc.ancestors_focal_freq[pos_to_ancestor[pos]] = freq
print("mean estimated ancestor length", np.mean(estimated_anc_length))
# Get the number of ancestors that have the maximum length
max_len = np.max(estimated_anc_length)
num_max_len = np.sum(estimated_anc_length == max_len)
print("max_len = ", max_len)
print(
"fraction of ancestors with max length = ",
num_max_len / estimated_anc.num_ancestors,
)
plt.hist(estimated_anc_length[estimated_anc.ancestors_focal_freq == 2], bins=50)
plt.xlabel("doubleton ancestor length")
save_figure(name_format.format("doubleton-length-dist"))
plt.clf()
anc_indexes = ancestor_data_by_pos(exact_anc, estimated_anc)
# convert to a 2d numpy array for convenience
exact_v_estimated_indexes = np.array([v for v in anc_indexes.values()])
for colorscale in ("Frequency", "True_time"):
fig = plt.figure(figsize=(10, 10), dpi=100)
if args.length_scale == "log":
plt.yscale("log")
plt.xscale("log")
if colorscale != "Frequency":
cs = exact_anc.ancestors_time[:][exact_v_estimated_indexes[:, 0]]
else:
cs = estimated_anc.ancestors_focal_freq[exact_v_estimated_indexes[:, 1]]
plt.scatter(
exact_anc_length[exact_v_estimated_indexes[:, 0]],
estimated_anc_length[exact_v_estimated_indexes[:, 1]],
c=cs,
cmap="brg",
s=2,
norm=NormalizeBandWidths(band_widths=np.bincount(cs)),
)
plt.plot([1, max_length], [1, max_length], "-", color="grey", zorder=-1)
plt.xlim(1, max_length)
plt.ylim(1, max_length)
cbar = plt.colorbar()
cbar.set_label(colorscale, rotation=270)
plt.xlabel("True ancestor length per variant (kb)")
plt.ylabel("Inferred ancestor length per variant (kb)")
save_figure(name_format.format(f"length-scatter_{colorscale.lower()}"))
# plot exact ancestors ordered by time, and estimated ancestors in frequency bands
# one point per variable site, so these should be directly comparable
# the exact ancestors have ancestors_time from 1..n_ancestors, ordered by real time
# in the simulation, so that each time is unique for a set of site on one ancestor
for ancestors_are_estimated, anc in enumerate([exact_anc, estimated_anc]):
time = anc.ancestors_time[:] + (1 if ancestors_are_estimated else 0)
df = pd.DataFrame(
{
"start": anc.ancestors_start[:],
"end": anc.ancestors_end[:],
"l": anc.ancestors_length / 1000,
"time": time,
"nsites": [len(x) for x in anc.ancestors_focal_sites[:]],
}
)
df_all = pd.DataFrame(
{
"lengths_per_site": np.repeat(df.l.values, df.nsites.values),
"time": np.repeat(df.time.values, df.nsites.values),
"const": 1,
}
).sort_values(by=["time"])
sum_per_timeslice = df_all.groupby("time").sum().const.values
df_all["x_pos"] = range(df_all.shape[0])
df_all["mean_x_pos"] = np.repeat(
df_all.groupby("time").mean().x_pos.values, sum_per_timeslice
)
df_all["width"] = np.repeat(sum_per_timeslice, sum_per_timeslice)
mean_by_anc_time = (
df.iloc[df["nsites"].nonzero()].groupby("time", sort=True).mean()
)
median_by_anc_time = (
df.iloc[df["nsites"].nonzero()].groupby("time", sort=True).median()
)
sum_by_anc_time = (