-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcf_stats_tools.py
1971 lines (1765 loc) · 74.3 KB
/
vcf_stats_tools.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
#!/usr/bin/env python3
import argparse
import collections
import copy
import logging
import os
import os.path
import re
import subprocess as sp
import sys
__version__ = 0.1
def parse_params(args):
""""""
opts = collections.defaultdict(dict)
opts.update({
'pdf_plots': 1,
'use_sample_names': 0,
'verbose': 1,
'make_pdf': 1,
'make_plots': 1,
'merge': 0,
'args': ' '.join(os.path.basename(arg) for arg in sys.argv),
'img_width': 11 / 2.54,
'img_height': 10 / 2.54,
'id2col': ['orange', 'red', 'darkgreen'],
'tex': {
'slide3v': {'height1': '7cm', 'height2': '7cm', 'height3': '4.5cm'},
'slide3h': {'width1': '15cm', 'width2': '10cm', 'width3': '8cm'}},
# for file version sanity check
'sections': [
{
'id': 'ID',
'header': 'Definition of sets',
'exp': '# ID\t[2]id\t[3]tab-separated file names'
},
{
'id': 'SN',
'header': 'SN, mysummary numbers',
'exp': '# SN\t[2]id\t[3]key\t[4]value'
},
{
'id': 'TSTV',
'header': '# TSTV, transition/transversions:',
'exp': '# TSTV\t[2]id\t[3]ts\t[4]tv\t[5]ts/tv\t[6]ts (1st ALT)\t[7]tv (1st ALT)\t[8]ts/tv (1st ALT)'
},
{
'id': 'SiS',
'header': 'Sis, Singleton stats',
'exp':
'# SiS\t[2]id\t[3]allele count\t[4]number of SNPs\t[5]number of transitions\t'
'[6]number of transversions\t[7]number of indels\t[8]repeat-consistent\t'
'[9]repeat-inconsistent\t[10]not applicable'
},
{
'id': 'AF',
'header': 'AF, Stats by non-reference allele frequency',
'exp':
'# AF\t[2]id\t[3]allele frequency\t[4]number of SNPs\t[5]number of transitions\t'
'[6]number of transversions\t[7]number of indels\t[8]repeat-consistent\t[9]repeat-inconsistent'
'\t[10]not applicable'
},
{
'id': 'IDD',
'header': 'IDD, InDel distribution',
'exp': '# IDD\t[2]id\t[3]length (deletions negative)\t[4]count'
},
{
'id': 'ST',
'header': 'ST, Substitution types',
'exp': '# ST\t[2]id\t[3]type\t[4]count'
},
{
'id': 'GCsAF',
'header': 'GCsAF, Genotype concordance by non-reference allele frequency (SNPs)',
'exp':
'# GCsAF\t[2]id\t[3]allele frequency\t[4]RR Hom matches\t[5]RA Het matches\t[6]AA Hom matches\t'
'[7]RR Hom mismatches\t[8]RA Het mismatches\t[9]AA Hom mismatches\t[10]dosage r-squared\t'
'[11]number of genotypes'
},
{
'id': 'GCiAF',
'header': 'GCiAF, Genotype concordance by non-reference allele frequency (indels)',
'exp':
'# GCiAF\t[2]id\t[3]allele frequency\t[4]RR Hom matches\t[5]RA Het matches\t'
'[6]AA Hom matches\t[7]RR Hom mismatches\t[8]RA Het mismatches\t[9]AA Hom mismatches\t'
'[10]dosage r-squared\t[11]number of genotypes'
},
{
'id': 'NRDs',
'header': 'Non-Reference Discordance (NRD), SNPs',
'exp':
'# NRDs\t[2]id\t[3]NRD\t[4]Ref/Ref discordance\t[5]Ref/Alt discordance\t[6]Alt/Alt discordance'
},
{
'id': 'NRDi',
'header': 'Non-Reference Discordance (NRD), indels',
'exp':
'# NRDi\t[2]id\t[3]NRD\t[4]Ref/Ref discordance\t[5]Ref/Alt discordance\t[6]Alt/Alt discordance'
},
{
'id': 'GCsS',
'header': 'GCsS, Genotype concordance by sample (SNPs)',
'exp':
'# GCsS\t[2]id\t[3]sample\t[4]non-reference discordance rate\t[5]RR Hom matches\t['
'6]RA Het matches\t[7]AA Hom matches\t[8]RR Hom mismatches\t[9]RA Het mismatches\t'
'[10]AA Hom mismatches\t[11]dosage r-squared'
},
{
'id': 'GCiS',
'header': 'GCiS, Genotype concordance by sample (indels)',
'exp':
'# GCiS\t[2]id\t[3]sample\t[4]non-reference discordance rate\t[5]RR Hom matches\t'
'[6]RA Het matches\t[7]AA Hom matches\t[8]RR Hom mismatches\t[9]RA Het mismatches\t'
'[10]AA Hom mismatches\t[11]dosage r-squared'
},
{
'id': 'PSC',
'header': 'PSC, Per-sample counts',
'exp':
'# PSC\t[2]id\t[3]sample\t[4]nRefHom\t[5]nNonRefHom\t[6]nHets\t[7]nTransitions\t'
'[8]nTransversions\t[9]nIndels\t[10]average depth\t[11]nSingletons'
},
{
'id': 'PSI',
'header': 'PSI, Per-sample Indels',
'exp':
'# PSI\t[2]id\t[3]sample\t[4]in-frame\t[5]out-frame\t[6]not applicable\t'
'[7]out/(in+out) ratio\t[8]nHets\t[9]nAA'
},
{
'id': 'DP',
'header': 'DP, Depth distribution',
'exp':
'# DP\t[2]id\t[3]bin\t[4]number of genotypes\t[5]fraction of genotypes (%)\t'
'[6]number of sites\t[7]fraction of sites (%)'
},
{
'id': 'FS',
'header': 'FS, Indel frameshifts',
'exp':
'# FS\t[2]id\t[3]in-frame\t[4]out-frame\t[5]not applicable\t[6]out/(in+out) ratio\t'
'[7]in-frame (1st ALT)\t[8]out-frame (1st ALT)\t[9]not applicable (1st ALT)\t'
'[10]out/(in+out) ratio (1st ALT)'
},
{
'id': 'ICS',
'header': 'ICS, Indel context mysummary',
'exp':
'# ICS\t[2]id\t[3]repeat-consistent\t[4]repeat-inconsistent\t[5]not applicable\t'
'[6]c/(c+i) ratio'
},
{
'id': 'ICL',
'header': 'ICL, Indel context by length',
'exp':
'# ICL\t[2]id\t[3]length of repeat element\t[4]repeat-consistent deletions)\t'
'[5]repeat-inconsistent deletions\t[6]consistent insertions\t[7]inconsistent insertions\t'
'[8]c/(c+i) ratio'
},
{
'id': 'QUAL',
'header': 'QUAL, Stats by quality',
'exp':
'# QUAL\t[2]id\t[3]Quality\t[4]number of SNPs\t[5]number of transitions (1st ALT)\t'
'[6]number of transversions (1st ALT)\t[7]number of indels'
},
{
'id': 'HWE',
'header': 'HWE',
'exp':
'# HWE\t[2]id\t[3]1st ALT allele frequency\t[4]Number of observations\t[5]25th percentile\t'
'[6]median\t[7]75th percentile'}],
'SN_keys': [
'number of samples:',
'number of records:',
'number of no-ALTs:',
'number of SNPs:',
'number of MNPs:',
'number of indels:',
'number of others:',
'number of multiallelic sites:',
'number of multiallelic SNP sites:']})
for sec in opts['sections']:
opts['exp'][sec['id']] = sec['exp']
opts['id2sec'][sec['id']] = sec
if args.no_PDF:
opts['make_pdf'] = 0
if args.rasterize:
opts['rasterize'] = 1
opts['pdf_plots'] = 0
if args.merge:
opts['make_plots'] = 0
opts['make_pdf'] = 0
opts['merge'] = 1
if args.sample_names:
opts['use_sample_names'] = 1
if args.title:
opts['titles'] = args.title
if args.main_title:
opts['main_title'] = args.main_title
if args.prefix:
opts['prefix'] = args.prefix
else:
opts['prefix'] = '.'
opts['vcfstats'] = args.stats_files
opts['dir'] = opts['prefix']
opts['logfile'] = 'plot-vcfstats.log'
if not os.path.isdir(opts['dir']):
os.mkdir(opts['dir'])
return opts
def parse_vcfstats(opts):
""""""
for i in range(len(opts['vcfstats'])):
parse_vcfstats1(opts, i)
# Check sanity
if 0 not in opts['dat']['ID']:
error("Sanity check failed: no stats found by vcfstats??")
# Set titles
file2title = {}
title2file = {}
if 'titles' in opts:
for i in range(len(opts['titles'])):
if i not in opts['dat']['ID']:
continue
file2title[opts['dat']['ID'][i][0][0]] = opts['titles'][i]
title2file[opts['titles'][i]] = opts['dat']['ID'][i][0][0]
for i_d in file_ids(opts):
if len(opts['dat']['ID'][i_d][0]) > 1:
continue
file = opts['dat']['ID'][i_d][0][0]
if file not in file2title: # create short title
bname = file
bname = re.sub('^.*/', '', bname)
bname = re.sub('\.vcf\.gz$', '', bname, flags=re.IGNORECASE)
if len(bname) > 5:
bname = bname[0:5]
i = 0
title = bname
while title in title2file:
title = bname + chr(66 + i)
i += 1
file2title[file] = title
title2file[title] = file
for i_d in file_ids(opts):
titles = []
for file in opts['dat']['ID'][i_d][0]:
if file in file2title:
titles.append(file2title[file])
opts['title'][i_d] = ' + '.join(titles)
# mapping from file names to list of IDs
for i_d in file_ids(opts):
for file in opts['dat']['ID'][i_d][0]:
if 'file2ids' not in opts:
opts['file2ids'] = {}
if file not in opts['file2ids']:
opts['file2ids'][file] = []
opts['file2ids'][file].append(i_d)
# check sanity of the file merge: were the correct files merged?
if 'coalesced_files' in opts and opts['verbose']:
logging.info('The vcfstats outputs have been merged as follows:')
printed = {}
for i_d in opts['coalesced_files']:
for i in range(len(opts['coalesced_files'][i_d])):
for j in range(len(opts['coalesced_files'][i_d][i])):
if opts['dat']['ID'][i_d][i][j]:
continue
logging.info('\t' + opts['dat']['ID'][i_d][i][j])
for file in opts['coalesced_files'][i_d][i][j]:
n = opts['coalesced_files'][i_d][i][j][file]
logging.info('\t\t' + file + ('\t..\t' + n + 'x') if n > 1 else '')
printed[opts['dat']['ID'][i_d][i][j]] = 1
def parse_vcfstats1(opts, i):
""""""
file = opts['vcfstats'][i]
logging.info('Parsing bcftools stats output: {}'.format(file.name))
header = next(file)
if not re.search(r'^# This file was produced by \S*', header):
error('Sanity check failed: was this file generated by bcftools stats?')
dat = collections.defaultdict(dict)
def_line_regex = re.compile('^#\s+(\S+)\t')
for line in file:
line = line.strip()
def_line = re.search(def_line_regex, line)
if def_line:
opts['def_line'][def_line.group(1)] = line
continue
if line.startswith('#'):
continue
items = line.split('\t')
for idx, item in enumerate(items):
try:
item = int(item)
except ValueError:
try:
item = float(item)
except ValueError:
pass
items[idx] = item
if items[0] == 'SN':
dat[items[1]][items[2]] = int(items[3])
continue
if items[1] not in dat[items[0]]:
dat[items[0]][items[1]] = []
dat[items[0]][items[1]].append(items[2:])
for a in dat:
if a not in opts['dat']: # First vcfstats file
opts['dat'][a] = dat[a]
continue
for b in dat[a]: # Merging multiple vcfstats files. Honestly, this is quite hacky.
if b not in opts['dat'][a]: # copy all, first occurrence
opts['dat'][a][b] = dat[a][b]
continue
if a == 'ID':
merge_id(opts, opts['dat'][a], dat[a], b)
elif not isinstance(dat[a][b], list): # SN, mysummary numbers, do not mysum sample counts
if b != 'number of samples:':
opts['dat'][a][b] += dat[a][b]
elif a == 'NRDs':
add_to_avg(opts['dat'][a][b], dat[a][b], i)
elif a == 'NRDi':
add_to_avg(opts['dat'][a][b], dat[a][b], i)
elif a == 'DP':
merge_dp(opts['dat'][a][b], dat[a][b])
elif a == 'GCsS':
merge_GCsS(opts['dat'][a][b], dat[a][b], i)
elif a == 'GCiS':
merge_GCsS(opts['dat'][a][b], dat[a][b], i)
elif a == 'GCsAF':
merge_GCsAF(opts['dat'][a][b], dat[a][b])
elif a == 'GCiAF':
merge_GCsAF(opts['dat'][a][b], dat[a][b])
elif a == 'ST':
add_to_values(opts['dat'][a][b], dat[a][b], cmp_str)
elif a == 'PSC':
merge_PSC(opts['dat'][a][b], dat[a][b], i)
elif a == 'PSI':
merge_PSI(opts['dat'][a][b], dat[a][b])
elif a == 'IDD':
add_to_values(opts['dat'][a][b], dat[a][b], cmp_num)
elif a == 'FS':
merge_FS(opts['dat'][a][b], dat[a][b])
elif a == 'ICS':
merge_ICS(opts['dat'][a][b], dat[a][b])
elif a == 'ICL':
merge_ICL(opts['dat'][a][b], dat[a][b])
elif a == 'TSTV':
merge_TSTV(opts['dat'][a][b], dat[a][b])
elif a == 'DBG':
continue
else:
add_to_values(opts['dat'][a][b], dat[a][b], cmp_num_op)
def merge_id(opts, dst, src, i_d):
""""""
for i in range(len(src[i_d])):
for j in range(len(src[i_d][i])):
gname = rglob(dst[i_d][i][j], src[i_d][i][j])
dst[i_d][i][j] = gname
if i_d not in opts['coalesced_files']:
opts['coalesced_files'][i_d] = []
if i + 1 > len(opts['coalesced_files'][i_d]):
opts['coalesced_files'][i_d].append([])
if j + 1 > len(opts['coalesced_files'][i_d][i]):
opts['coalesced_files'][i_d][i].append({src[i_d][i][j]: 0})
opts['coalesced_files'][i_d][i][j][src[i_d][i][j]] += 1
def merge_dp(a, b):
""""""
add_to_values(a, b, cmp_num_op)
# recalculate fraction of GTs and fraction of sites, cannot be simply mysummed
gsum = 0 # genotype mysum
ssum = 0 # site mysum
for i in range(len(a)):
gsum += a[i][1]
if len(a[i]) > 3:
ssum += a[i][3]
else:
# older stats files will not have last 2 columns for (number of sites, fraction of sites), so fill in as zero
a[i].extend((0, 0))
for i in range(len(a)):
a[i][2] = a[i][1] * 100 / gsum if gsum else 0
a[i][4] = a[i][3] * 100 / ssum if ssum else 0
def merge_GCsS(a, b, n):
"""average the non-ref discordance rate"""
for i in range(len(a)):
a[i][1] *= n
add_to_sample_values(a, b)
for i in range(len(a)):
a[i][1] /= n + 1
def merge_GCsAF(a, b):
"""recalculate r2"""
for i in range(len(a)):
a[i][7] *= a[i][8]
for i in range(len(b)):
a[i][7] *= a[i][8]
add_to_values(a, b, cmp_num_op)
for i in range(len(a)):
a[i][7] /= a[i][8]
def merge_PSC(a, b, n):
""""""
for i in range(len(a)):
a[i][7] *= n
add_to_sample_values(a, b)
for i in range(len(a)):
a[i][7] /= n + 1
def merge_PSI(a, b):
""""""
add_to_sample_values(a, b)
for i in range(len(b)):
a[i][4] = float('{:.2f}'.format(a[i][2] / (a[i][1] + a[i][2]) if a[i][1] + a[i][2] else 0))
def merge_FS(a, b):
""""""
for i in range(len(a)):
for j in range(3):
a[i][j] += b[i][j]
a[i][3] = float('{:.2f}'.format(a[i][1] / (a[i][0] + a[i][1]) if a[i][0] + a[i][1] else 0))
for j in range(4, 7):
a[i][j] += b[i][j]
a[i][7] = float('{:.2f}'.format(a[i][5] / (a[i][4] + a[i][5]) if a[i][4] + a[i][5] else 0))
def merge_ICS(a, b):
""""""
for i in range(len(a)):
for j in range(3):
a[i][j] += b[i][j]
a[i][3] = '{:.4f}'.format(a[i][0] / (a[i][0] + a[i][1]) if a[i][0] + a[i][1] else 0)
def merge_ICL(a, b):
""""""
for i in range(len(a)):
for j in range(1, 5):
a[i][j] += b[i][j]
a[i][5] = '{:.4f}'.format((a[i][1] + a[i][3]) / (a[i][1] + a[i][2] + a[i][3] + a[i][4]) if a[i][2] + a[i][4] else 0)
def merge_TSTV(a, b):
""""""
for i in range(len(a)):
for j in range(2):
a[i][j] += b[i][j]
a[i][2] = float('{:.2f}'.format(a[i][0] / a[i][1] if a[i][1] else 0))
for j in range(3, 5):
a[i][j] += b[i][j]
a[i][5] = float('{:.2f}'.format(a[i][3] / a[i][4] if a[i][4] else 0))
def add_to_avg(dst, src, n):
""""""
for i in range(len(src)):
if isinstance(dst[i], list):
for j in range(len(dst[i])):
dst[i][j] = (n * dst[i][j] + src[i][j]) / (n + 1)
else:
dst[i] = (n * dst[i] + src[i]) / (n + 1)
def rglob(a, b):
""""""
if a == b:
return a
a = re.sub(r'\\*', '', a)
la = len(a)
lb = len(b)
i = 0
while (i < la) & (i < lb) & (a[i] == b[i]):
i += 1
la -= 1
lb -= 1
while (la > i) & (lb > i) & (a[la] == b[lb]):
la -= 1
lb -= 1
la = 1 if la == i and lb == i else la - i
a = a[:i] + '*' + a[i + la:]
return a
def add_to_values(dst, src, cmp):
""""""
i_d = 0
i_s = 0
while i_s < len(src):
while i_d < len(dst) and cmp(src[i_s][0], dst[i_d][0]) > 0:
i_d += 1
if i_d < len(dst) and not cmp(src[i_s][0], dst[i_d][0]):
for j in range(1, len(src[i_s])):
dst[i_d][j] += src[i_s][j]
else:
dst.insert(i_d, src[i_s])
i_s += 1
def cmp_num_op(a, b):
"""numeric compare with operators
Cases like <3, >500 make it complicated
"""
xa = '='
xb = '='
a = str(a)
b = str(b)
char_start = re.compile('^(\D+)(.*)')
a_match = re.search(char_start, a)
if a_match:
xa = a_match.group(1)
a = a_match.group(2)
b_match = re.search(char_start, b)
if b_match:
xb = b_match.group(1)
b = b_match.group(2)
if a == b:
return (xa > xb) - (xa < xb)
try:
a = int(a)
except ValueError:
try:
a = float(a)
except ValueError:
pass
try:
b = int(b)
except ValueError:
try:
b = float(b)
except ValueError:
pass
return (a > b) - (a < b)
def cmp_str(a, b):
""""""
return (a > b) - (a < b)
def cmp_num(a, b):
""""""
return (a > b) - (a < b)
def add_to_sample_values(dst, src):
""""""
id2i = {}
for i in range(len(dst)):
id2i[dst[i][0]] = i
for i in range(len(src)):
if src[i][0] not in id2i:
error('Whoops, no such dst sample: {}'.format(src[i][0]))
di = id2i[src[i][0]]
for j in range(len(src[i])):
dst[di][j] += src[i][j]
def file_ids(opts):
i_d = 0
out = []
while 'ID' in opts['dat'] and i_d in opts['dat']['ID']:
out.append(i_d)
i_d += 1
return out
def merge_vcfstats(opts):
""""""
fh = open('merge.chk', 'w') if not opts['merge'] else sys.stdout
fh.write('# This file was produced by plot-vcfstats, the command line was:\n'
'# ' + opts['args'] + '\n#\n')
for sec in opts['sections']:
sid = sec['id']
if sid not in opts['dat']:
continue
fh.write('# ' + sec['header'] + '\n' + sec['exp'] + '\n')
for i_d in sorted(opts['dat'][sid]):
for rec in opts['dat'][sid][i_d]:
fh.write('{}\t{}\t{}\n'.format(sid, i_d, '\t'.join(str(r) for r in rec)))
if sid == 'ID':
fh.write('# ' + opts['id2sec']['SN']['header'] + '\n' + opts['id2sec']['SN']['exp'] + '\n')
# output mysummary numbers here
for i_d in opts['dat']:
if i_d in opts['dat']:
continue
for key in opts['SN_keys']:
if key not in opts['dat'][i_d]:
continue
fh.write('SN\t' + 'id' + '\t' + key + '\t' + opts['dat'][i_d][key] + '\n')
fh.close()
def init_plots(opts):
""""""
opts['plt_file'] = 'plot.py'
titles = '# Title abbreviations:\n'
for i_d in file_ids(opts):
titles += '# \t {} .. {} .. {}\n'.format(i_d, opts['title'][i_d], opts['dat']['ID'][i_d][0][0])
titles += '#'
fh = open(opts['plt_file'], 'w')
tprint(fh, '''
# This file was produced by plot-vcfstats, the command line was:
# {args}
#
# Edit as necessary and recreate the plots by running
# python {plt_file}
#
{titles}
# Set to 1 to plot in PDF instead of PNG
pdf_plots = {pdf_plots}
# Use logarithimic X axis for allele frequency plots
af_xlog = 0
# Plots to generate, set to 0 to disable
plot_venn_snps = 1
plot_venn_indels = 1
plot_tstv_by_sample = 1
plot_hethom_by_sample = 1
plot_snps_by_sample = 1
plot_indels_by_sample = 1
plot_singletons_by_sample = 1
plot_depth_by_sample = 1
plot_SNP_count_by_af = 1
plot_Indel_count_by_af = 1
plot_SNP_overlap_by_af = 1
plot_Indel_overlap_by_af = 1
plot_dp_dist = 1
plot_hwe = 1
plot_concordance_by_af = 1
plot_r2_by_af = 1
plot_discordance_by_sample = 1
plot_tstv_by_af = 1
plot_indel_dist = 1
plot_tstv_by_qual = 1
plot_substitutions = 1
# Set to 1 to use sample names for xticks instead of numeric sequential IDs
# and adjust margins and font properties if necessary
sample_names = {use_sample_names}
sample_margins = {{'right':0.98, 'left':0.07, 'bottom':0.2}}
sample_font = {{'rotation':45, 'ha':'right', 'fontsize':8}}
if sample_names==0: sample_margins=(); sample_font=();
#-------------------------------------------------
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import csv
csv.register_dialect('tab', delimiter='\\t', quoting=csv.QUOTE_NONE)
import numpy
def smooth(x,window_len=11,window='hanning'):
\\tif x.ndim != 1: raise ValueError("The function 'smooth' only accepts 1 dimension arrays.")
\\tif x.size < window_len: return x
\\tif window_len<3: return x
\\tif not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
\\ts = numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
\\tif window == 'flat': # moving average
\\t\\tw = numpy.ones(window_len,'d')
\\telse:
\\t\\tw = eval('numpy.'+window+'(window_len)')
\\ty = numpy.convolve(w/w.sum(),s,mode='valid')
\\treturn y[(window_len/2-1):-(window_len/2)]
'''.format(
args=opts['args'], plt_file=opts['plt_file'], titles=titles, pdf_plots=opts['pdf_plots'],
use_sample_names=opts['use_sample_names']))
opts['plt_fh'] = fh
def plot_venn_bars(opts):
""""""
ids = file_ids(opts)
if len(ids) != 3:
return
snps = []
indels = []
tstv = []
snp_titles = []
indel_titles = []
for i_d in range(3):
snps.append(get_value(opts, i_d, 'number of SNPs:'))
indels.append(get_value(opts, i_d, 'number of indels:'))
tstv.append(float('{:.2f}'.format(get_values(opts, i_d, 'TSTV', 0, 5))))
snp_titles.append('{}\\nts/tv {}\\n'.format(opts['title'][i_d], tstv[i_d]) + bignum(snps[i_d]))
fs = get_values(opts, i_d, 'FS')
fss = 'frm{}\\n'.format(fs[0][3]) if len(fs) else ''
indel_titles.append('{}\\n{}'.format(opts['title'][i_d], fss) + bignum(indels[i_d]))
fh = opts['plt_fh']
tprint(fh, '''
if plot_venn_snps:
\\tfig = plt.figure(figsize=({img_width},{img_height}))
\\tax1 = fig.add_subplot(111)
\\tax1.bar([1,2,3],[{snps_0},{snps_2},{snps_1}],align='center',color='{id2col_0}',width=0.3)
\\tax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
\\tax1.set_xlim(0.5,3.5)
\\tplt.xticks([1,2,3],('{snp_titles_0}','{snp_titles_2}','{snp_titles_1}'))
\\tplt.title('Number of SNPs')
\\tplt.subplots_adjust(right=0.95,bottom=0.15)
\\tplt.savefig('venn_bars.snps.png')
\\tif pdf_plots: plt.savefig('venn_bars.snps.pdf')
\\tplt.close()
if plot_venn_indels:
\\tfig = plt.figure(figsize=({img_width},{img_height}))
\\tax1 = fig.add_subplot(111)
\\tax1.bar([1,2,3],[{indels_0},{indels_2},{indels_1}],align='center',color='{id2col_1}',width=0.3)
\\tax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
\\tax1.set_xlim(0.5,3.5)
\\tplt.xticks([1,2,3],('{indel_titles_0}','{indel_titles_2}','{indel_titles_1}'))
\\tplt.title('Number of indels')
\\tplt.subplots_adjust(right=0.95,bottom=0.15)
\\tplt.savefig('venn_bars.indels.png')
\\tif pdf_plots: plt.savefig('venn_bars.indels.pdf')
\\tplt.close()
'''.format(img_width=opts['img_width'], img_height=opts['img_height'], snps_0=snps[0], snps_1=snps[1],
snps_2=snps[2], id2col_0=opts['id2col'][0], snp_titles_0=snp_titles[0], snp_titles_1=snp_titles[1],
snp_titles_2=snp_titles[2], indels_0=indels[0], indels_1=indels[1], indels_2=indels[2],
id2col_1=opts['id2col'][1], indel_titles_0=indel_titles[0], indel_titles_1=indel_titles[1],
indel_titles_2=indel_titles[2]))
def plot_counts_by_AF(opts):
""""""
plot_counts_by_AF_col(opts, 1, 'SNP')
plot_counts_by_AF_col(opts, 4, 'Indel')
def plot_counts_by_AF_col(opts, col, title):
""""""
fh = opts['plt_fh']
img = 'counts_by_af.' + title.lower() + 's'
tfh = open('{}.dat'.format(img), 'w')
tfh.write('# [1]id\t[2]Nonref Allele Frequency\t[3]Number of sites\n')
for i_d in file_ids(opts):
tmp = get_values(opts, i_d, 'AF')
vals = rebin_values(tmp, 1, 0)
for val in vals:
if not val[col]:
continue
tfh.write('{}\t{}\t{}\n'.format(i_d, val[0], val[col]))
tfh.close()
tprint(fh, '''
dat = {{}}
with open('{img}.dat', 'r') as f:
\\treader = csv.reader(f, 'tab')
\\tfor row in reader:
\\t\\tif row[0][0] == '#': continue
\\t\\tid = int(row[0])
\\t\\tif id not in dat: dat[id] = []
\\t\\tdat[id].append([float(row[1]),float(row[2])])
if plot_{title}_count_by_af:
\\tfig = plt.figure(figsize=(2*{img_width},{img_height}*0.7))
\\tax1 = fig.add_subplot(111)
\\tax1.set_ylabel('Number of sites')
\\tax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
\\tax1.set_yscale('log')
\\tif af_xlog: ax1.set_xscale('log')
\\tax1.set_xlabel('Non-reference allele frequency')
\\tax1.set_xlim(-0.05,1.05)
\\thas_data = 0
'''.format(img=img, title=title, img_width=opts['img_width'], img_height=opts['img_height']))
for i_d in file_ids(opts):
tprint(fh, '''
\\tif {id} in dat and len(dat[{id}])>2:
\\t\\tax1.plot([row[0] for row in dat[{id}]], [row[1] for row in dat[{id}]], '-o',markersize=3, color='{id2col}',mec='{id2col}',label='{title}')
\\t\\thas_data = 1
'''.format(id=i_d, id2col=opts['id2col'][i_d], title=opts['title'][i_d]))
tprint(fh, '''
\\tif has_data:
\\t\\tax1.legend(numpoints=1,markerscale=1,loc='best',prop={{'size':10}},frameon=False)
\\t\\tplt.title('{title} count by AF')
\\t\\tplt.subplots_adjust(bottom=0.2,left=0.1,right=0.95)
\\t\\tplt.savefig('{img}.png')
\\t\\tif pdf_plots: plt.savefig('{img}.pdf')
\\t\\tplt.close()
'''.format(title=title, img=img))
def plot_overlap_by_AF(opts):
""""""
plot_overlap_by_AF_col(opts, 1, 'SNP')
plot_overlap_by_AF_col(opts, 4, 'Indel')
def plot_overlap_by_AF_col(opts, col, title):
""""""
ids = file_ids(opts)
if len(ids) != 3:
return
ia = ib = iab = 0
for i in range(len(ids)):
if len(opts['dat']['ID'][ids[i]][0]) > 1:
iab = i
continue
if not ia:
ia = i
continue
ib = i
fh = opts['plt_fh']
img = 'overlap_by_af' + title.lower() + 's'
vals_a = get_values(opts, ia, 'AF')
vals_ab = get_values(opts, iab, 'AF')
afs = {}
af_a = {}
af_ab = {}
for val in vals_a:
afs[val[0]] = val[col]
af_a[val[0]] = val[col]
for val in vals_ab:
afs[val[0]] = val[col]
af_ab[val[0]] = val[col]
tfh = open('{}.dat'.format(img), 'w')
tfh.write('# [1]Allele frequency\t[2]Fraction of sites from {title_1} also in {title_2}\t[3]Number of sites\n'.format(
title_1=opts['title'][ids[ia]], title_2=opts['title'][ids[ib]]))
for af in sorted(afs):
a = af_a[af] if af_a[af] else 0
ab = af_ab[af] if af_ab[af] else 0
yval = ab * 100 / (a + ab) if (a + ab) else 0
tfh.write('{}\t{}\t{}\n'.format(af, yval, a + ab))
tfh.close()
tprint(fh, '''
dat = []
with open('{img}.dat', 'r') as f:
\\treader = csv.reader(f, 'tab')
\\tfor row in reader:
\\t\\tif row[0][0] != '#': dat.append(row)
if plot_{title}_overlap_by_af and len(dat)>1:
\\tfig = plt.figure(figsize=(2*{img_width},{img_height}*0.7))
\\tax1 = fig.add_subplot(111)
\\tax1.plot([row[0] for row in dat], [row[1] for row in dat],'-o',markersize=3, color='{id2col_1}',mec='{id2col_1}')
\\tax1.set_ylabel('Fraction found in {title_ib} [%]')
\\tax1.set_xscale('log')
\\tax1.set_xlabel('Non-reference allele frequency in {title_ia}')
\\tax1.set_xlim(0,1.01)
\\tplt.title('{title} overlap by AF')
\\tplt.subplots_adjust(bottom=0.2,left=0.1,right=0.95)
\\tplt.savefig('{img}.png')
\\tif pdf_plots: plt.savefig('{img}.pdf')
\\tplt.close()
'''.format(img=img, title=title, img_width=opts['img_width'], img_height=opts['img_height'],
id2col_1=opts['id2col'][1], title_ia=opts['title'][ia], title_ib=opts['title'][ib]))
def plot_concordance_by_AF(opts):
""""""
vals = get_values(opts, 2, 'GCsAF')
if not vals:
return
# create a local copy and prepare r2 for rebinning
vals = copy.deepcopy(vals)
for i in range(len(vals)):
vals[i][7] *= vals[i][8]
vals = rebin_values(vals, 0.01, 0)
fh = opts['plt_fh']
img = 'gts_by_af'
img2 = 'r2_by_af'
tfh = open('{}.dat'.format(img), 'w')
tfh.write('# [1]Allele Frequency\t[2]RR concordance\t[3]RA concordance\t[4]AA concordance\t[5]nRR\t[6]nRA\t[7]nAA\t[8]R^2\t[9]Number of genotypes\n')
for i in range(len(vals)):
tfh.write('{:f}\t{:f}\t{:f}\t{:f}\t{:d}\t{:d}\t{:d}\t{:f}\t{:d}\n'.format(
vals[i][0],
vals[i][1] / (vals[i][1] + vals[i][4]) if vals[i][1] + vals[i][4] else 1,
vals[i][2] / (vals[i][2] + vals[i][5]) if vals[i][2] + vals[i][5] else 1,
vals[i][3] / (vals[i][3] + vals[i][6]) if vals[i][3] + vals[i][6] else 1,
vals[i][1] + vals[i][4],
vals[i][2] + vals[i][5],
vals[i][3] + vals[i][6],
vals[i][7] / vals[i][8] if vals[i][8] else 1,
vals[i][8]))
tfh.close()
tprint(fh, '''
dat = []
with open('{img}.dat', 'r') as f:
\\treader = csv.reader(f, 'tab')
\\tfor row in reader:
\\t\\tif row[0][0] != '#': dat.append(row)
if plot_concordance_by_af and len(dat)>1:
\\tfig = plt.figure(figsize=({img_width}*1.2,{img_height}))
\\tax1 = fig.add_subplot(111)
\\tax1.plot([row[0] for row in dat], [row[1] for row in dat],'.',color='{id2col_1}',label='Hom RR')
\\tax1.plot([row[0] for row in dat], [row[2] for row in dat],'.',color='{id2col_0}',label='Het RA')
\\tax1.plot([row[0] for row in dat], [row[3] for row in dat],'.',color='k',label='Hom AA')
\\tax1.set_xlabel('Non-ref allele frequency')
\\tax1.set_ylabel('Concordance')
\\tleg = ax1.legend(title='Concordance:',numpoints=1,markerscale=2,loc='best',prop={{'size':9}})
\\tleg.draw_frame(False)
\\tplt.setp(leg.get_title(),fontsize=9)
\\tax2 = ax1.twinx()
\\tax2.plot([row[0] for row in dat], [row[4] for row in dat],color='{id2col_1}')
\\tax2.plot([row[0] for row in dat], [row[5] for row in dat],color='{id2col_0}')
\\tax2.plot([row[0] for row in dat], [row[6] for row in dat],color='k')
\\tax2.set_ylabel('Number of genotypes')
\\tax2.set_yscale('log')
\\tif af_xlog: ax1.set_xscale('log')
\\tif af_xlog: ax2.set_xscale('log')
\\tplt.subplots_adjust(left=0.15,right=0.83,bottom=0.11)
\\tplt.savefig('{img}.png')
\\tif pdf_plots: plt.savefig('{img}.pdf')
\\tplt.close()
if plot_r2_by_af and len(dat)>1:
\\tfig = plt.figure(figsize=({img_width}*1.3,{img_height}))
\\tax1 = fig.add_subplot(111)
\\tax2 = ax1.twinx()
\\tax1.set_zorder(ax2.get_zorder()+1)
\\tax1.patch.set_visible(False)
\\tax2.plot([row[0] for row in dat], [row[8] for row in dat], '-o', color='r',mec='r',markersize=3)
\\tax1.plot([row[0] for row in dat], [row[7] for row in dat], '-^', color='k',markersize=3)
\\tfor tl in ax2.get_yticklabels(): tl.set_color('r')
\\tax2.set_ylabel('Number of genotypes', color='r')
\\tax2.set_yscale('log')
\\tif af_xlog: ax1.set_xscale('log')
\\tif af_xlog: ax2.set_xscale('log')
\\tax1.set_ylabel('Aggregate allelic R\$^2\$', color='k')
\\tax1.set_xlabel('Non-ref allele frequency')
\\tplt.subplots_adjust(left=0.19,right=0.83,bottom=0.11)
\\tplt.savefig('{img2}.png')
\\tif pdf_plots: plt.savefig('{img2}.pdf')
\\tplt.close()
'''.format(img=img, img2=img2, img_width=opts['img_width'], img_height=opts['img_height'],
id2col_0=opts['id2col'][0], id2col_1=opts['id2col'][1]))
def plot_concordance_by_sample(opts):
""""""
vals = get_values(opts, 2, 'GCsS')
if not vals:
return
fh = opts['plot_fh']
img = 'gts_by_sample'
tfh = open('{}.dat'.format(img), 'w')
tfh.write('# [1]Sample ID\t[2]Discordance\t[3]Sample Name\n')
for i in range(len(vals)):
tfh.write('{:d}\t{:f}\t{:s}\n'.format(i, vals[i][1], vals[i][0]))
tfh.close()
tprint(fh, '''
dat = []
with open('{img}.dat', 'r') as f:
\\treader = csv.reader(f, 'tab')
\\tfor row in reader:
\\t\\tif row[0][0] != '#': dat.append(row)
if plot_discordance_by_sample:
\\tfig = plt.figure(figsize=(2*{img_width},{img_height}*0.7))
\\tax1 = fig.add_subplot(111)
\\tax1.plot([row[0] for row in dat], [row[1] for row in dat],'.',color='orange')
\\tax1.set_ylabel('Non-ref discordance')
\\tax1.set_ylim(0,)
\\tif sample_names:
\\t\\t plt.xticks([int(row[0]) for row in dat],[row[2] for row in dat],**sample_font)
\\t\\t plt.subplots_adjust(**sample_margins)
\\telse:
\\t\\t plt.subplots_adjust(right=0.98,left=0.07,bottom=0.17)