-
Notifications
You must be signed in to change notification settings - Fork 9
/
training_data.py
executable file
·4716 lines (3769 loc) · 158 KB
/
training_data.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
# training_data.py
#
# This file contains all the nitty-gritty of training data generation for neural networks.
# Reads input files, BAMs VCFs, BEDs, etc. and transforms them into tensors (or images).
# The generated data is of set dimension for processing by a particular neural net architecture.
# Supports division of training, testing and validation data.
# Provides basic queries for variants from vcfs and intervals from beds.
#
# December 2016
# Sam Friedman
# Python 2/3 friendly
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
# Imports
import os
import sys
import vcf
import math
import h5py
import plots
import errno
import pysam
import random
import defines
import operator
import arguments
import numpy as np
from random import shuffle
from Bio import Seq, SeqIO
from scipy.stats import norm
from collections import Counter, defaultdict
tensor_exts = ['.h5', '.hd5']
p_lut = np.zeros((256,))
not_p_lut = np.zeros((256,))
for i in range(256):
exponent = float(-i) / 10.0
p_lut[i] = 1.0 - (10.0**exponent)
not_p_lut[i] = (1.0 - p_lut[i]) / 3.0
def run_training_data():
'''Dispatch on args.mode command-line supplied recipe'''
args = arguments.parse_args()
# Writing tensor datasets for training
if 'write_tensors' == args.mode:
tensors_from_tensor_map(args)
elif 'write_tensors_2bit' == args.mode:
tensors_from_tensor_map_2channel(args, include_annotations=True)
elif 'write_tensors_no_annotations' == args.mode:
tensors_from_tensor_map(args, include_annotations=False)
elif 'write_tensors_gnomad_annotations_1d' == args.mode:
tensors_from_tensor_map_gnomad_annos(args)
elif 'write_tensors_gnomad_annotations_per_allele_1d' == args.mode:
tensors_from_tensor_map_gnomad_annos_per_allele(args, include_reads=False, include_reference=True)
elif 'write_depristo' == args.mode:
nist_samples_to_png(args)
elif 'write_calling_tensors' == args.mode:
calling_tensors_from_tensor_map(args)
elif 'write_pileup_filter_tensors' == args.mode:
tensors_from_tensor_map(args, pileup=True)
elif 'write_calling_tensors_1d' == args.mode:
calling_tensors_from_tensor_map(args, pileup=True)
elif 'write_dna_tensors' == args.mode:
write_dna_and_annotations(args)
elif 'write_bed_tensors' == args.mode:
write_dna_multisource_annotations(args)
elif 'write_bed_tensors_dna' == args.mode:
write_dna_multisource_annotations(args, include_annotations=False)
elif 'write_bed_tensors_annotations' == args.mode:
write_dna_multisource_annotations(args, include_dna=False)
elif 'write_bqsr_tensors' == args.mode:
bqsr_tensors_from_tensor_map(args, include_annotations=True)
elif 'write_tranches' == args.mode:
write_tranches(args)
# Inspections
elif 'inspect_tensors' == args.mode:
inspect_read_tensors(args)
elif 'inspect_dataset' == args.mode:
inspect_dataset(args)
elif 'inspect_gnomad' == args.mode:
inspect_gnomad_low_ac(args)
elif 'combine_vcfs' == args.mode:
combine_vcfs(args)
# Ooops
else:
raise ValueError('Unknown recipe mode:', args.mode)
def tensors_from_tensor_map(args,
annotation_sets=['best_practices', 'm2mix', 'm2combine'],
pileup=False,
reference_map='reference',
include_annotations=True):
'''Create tensors structured as tensor map of reads organized by labels in the data directory.
Defines true variants as those in the args.train_vcf, defines false variants as
those called in args.negative_vcf and in the args.bed_file high confidence intervals,
but not in args.train_vcf.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.negative_vcf: VCF file with annotation values from Haplotype caller or VQSR
args.train_vcf: VCF file with true variant (from NIST or Platinum genomes, etc.)
args.bed_file: High confidence intervals for the calls in args.train_vcf
args.window_size: Size of sequence window around variant (width of the tensor)
args.read_limit: Maximum number of reads to include (height of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
'''
print('Writing tensors with tensor type(s):', args.tensor_types, 'channel map.')
stats = Counter()
debug = False
samfile = pysam.AlignmentFile(args.bam_file, "rb")
bed_dict = bed_file_to_dict(args.bed_file)
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = vcf.Reader(open(args.negative_vcf, 'r'))
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
if args.chrom and not (args.start_pos and args.end_pos):
variants = vcf_reader.fetch(args.chrom)
elif args.chrom and args.start_pos and args.end_pos:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_idx, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[ ref_start : ref_end ]
skip_this = False
reference_seq = record.seq
if reference_map is not None:
reference_tensor = np.zeros( (args.window_size, len(defines.inputs)) )
for i,b in enumerate(reference_seq):
if not args.use_lowercase_dna and b.islower():
skip_this = True
break
b = b.upper()
if b in defines.inputs:
reference_tensor[i, defines.inputs[b]] = 1.0
elif b in defines.ambiguity_codes:
reference_tensor[i] = defines.ambiguity_codes[b]
else:
raise ValueError('Error! Unknown code:', b)
if skip_this:
stats['Skipped lowercase DNA'] += 1
continue
if args.label_sites:
cur_label_key = get_true_site_label(variant, bed_dict, vcf_ram, stats)
else:
cur_label_key = get_true_allele_label(allele, variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats, variant):
continue
if include_annotations:
annotation_data = {}
for a_set in annotation_sets:
annos = defines.annotations[a_set]
if all(map(lambda x: x not in variant.INFO and x not in variant.FORMAT and x != "QUAL", annos)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data[a_set] = get_annotation_data(args, variant, stats, allele_idx, annos)
read_tensors = {}
for tt in args.tensor_types:
args.tensor_map = tt
if 'read_tensor' == tt:
read_tensors[tt] = make_reference_and_reads_tensor(args, variant, samfile, record.seq, ref_start, stats)
elif 'paired_reads' == tt:
read_tensors[tt] = make_paired_read_tensor(args, variant, samfile, record.seq, ref_start, ref_end, stats)
elif 'reads_only' == tt:
args.tensor_map = 'read_tensor'
rt = make_reference_and_reads_tensor(args, variant, samfile, record.seq, ref_start, stats)
args.tensor_map = tt
read_tensors[tt] = rt[:len(defines.get_tensor_channel_map_from_args(args)), :, :]
elif 'reads_reference' == tt:
args.tensor_map = 'read_tensor'
rt = make_reference_and_reads_tensor(args, variant, samfile, record.seq, ref_start, stats)
args.tensor_map = tt
read_tensors[tt] = rt[:len(defines.get_tensor_channel_map_from_args(args)), :, :]
else:
raise ValueError("Unknown read tensor mapping."+tt)
tensor_path = get_path_to_train_valid_or_test(args, variant.CHROM)
tensor_prefix = plain_name(args.negative_vcf) +'_'+ plain_name(args.train_vcf) + '_allele_' + str(allele_idx) + '-' + cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + variant.CHROM + '_' + str(variant.POS) + '.hd5'
stats[cur_label_key] += 1
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
for rt in read_tensors:
if read_tensors[rt] is not None:
hf.create_dataset(rt, data=read_tensors[rt], compression='gzip')
if include_annotations:
for a_set in annotation_sets:
hf.create_dataset(a_set, data=annotation_data[a_set], compression='gzip')
if reference_map is not None:
hf.create_dataset(reference_map, data=reference_tensor, compression='gzip')
if pileup:
pileup_tensor = read_tensor_to_pileup(args, read_tensor)
hf.create_dataset('pileup_tensor', data=pileup_tensor, compression='gzip')
stats['count'] += 1
if stats['count']%500 == 0:
print('Wrote', stats['count'], 'tensors out of', args.samples, ' last variant:', str(variant))
if stats['count'] >= args.samples:
break
for s in stats.keys():
print(s, 'has:', stats[s])
if variant:
print('Generated tensors at:', args.data_dir, '\nLast variant:', str(variant), 'from vcf:', args.negative_vcf)
def calling_tensors_from_tensor_map(args, pileup=False):
'''Create tensors structured as tensor map of reads Labels are 1d segmentation (genotyping) of the reference.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.train_vcf: VCF file with true variant (from NIST or Platinum genomes, etc.)
args.bed_file: High confidence intervals for the calls in args.train_vcf
args.window_size: Size of sequence window around variant (width of the tensor)
args.read_limit: Maximum number of reads to include (height of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
pileup: Boolean whether the read tensors should be summed over each dimension to make them 1d
'''
print('Writing tensors for Variant Calling from tensor channel map:', args.tensor_map)
stats = Counter()
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
samfile = pysam.AlignmentFile(args.bam_file, "rb")
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
tensor_channel_map = defines.get_tensor_channel_map_from_args(args)
cur_pos = args.start_pos
contig = record_dict[args.chrom]
label_vector = np.zeros((args.window_size,))
while cur_pos < args.end_pos - args.window_size:
skip_this = False
label_vector[:] = defines.calling_labels['REFERENCE']
record = contig[cur_pos : cur_pos+args.window_size]
cur_labels = []
known_inserts = {}
variants = vcf_ram.fetch(args.chrom, cur_pos, cur_pos+args.window_size)
for variant in variants:
if len(variant.get_hets()) == 1:
cur_label_key = 'HET_'
elif len(variant.get_hom_alts()):
cur_label_key = 'HOM_'
else:
stats['variant not het or hom'] += 1
skip_this = True
break
if variant.is_snp:
cur_label_key += 'SNP'
alt_length = 1
v_start = (variant.POS-cur_pos) - 1
elif variant.is_deletion:
cur_label_key += 'DELETION'
alt_length = len(variant.REF) - min(map(len, variant.ALT))
v_start = (variant.POS-cur_pos)
elif variant.is_indel: # indel & !is_deletion -> insertion
cur_label_key += 'INSERTION'
alt_length = max(map(len, variant.ALT)) - len(variant.REF)
v_start = (variant.POS-cur_pos)
known_inserts[v_start] = alt_length
else:
stats['Not SNP or INDEL'] += 1
skip_this = True
break
cur_labels.append(cur_label_key)
v_end = min(args.window_size, v_start+alt_length)
label_vector[v_start:v_end] = defines.calling_labels[cur_label_key]
if len(cur_labels) == 0 and args.downsample_reference < 1.0:
dice = np.random.rand()
if dice > args.downsample_reference:
stats['Downsampled Reference'] += 1
skip_this = True
if args.downsample_snps < 1.0 and any(map(lambda x: 'SNP' in x, cur_labels)):
dice = np.random.rand()
if dice > args.downsample_snps:
stats['Downsampled SNPs'] += 1
skip_this = True
if args.downsample_homozygous < 1.0 and any(map(lambda x: x in ['HOM_INSERTION', 'HOM_DELETION'], cur_labels)):
dice = np.random.rand()
if dice > args.downsample_homozygous:
stats['Downsampled Homozygous'] += 1
skip_this = True
if len(cur_labels) == 0:
stats['Reference only tensor'] += 1
good_reads, insert_dict = get_good_reads_in_window(args, samfile, cur_pos, cur_pos+args.window_size)
else:
good_reads, insert_dict = get_good_reads_in_window(args, samfile, cur_pos, cur_pos+args.window_size, variant)
if len(good_reads) == 0:
stats['No reads aligned'] += 1
skip_this = True
if skip_this:
cur_pos += args.window_size
continue
for l in cur_labels:
stats[l] += 1
reference_seq = record.seq
for i in sorted(insert_dict.keys(), key=int, reverse=True):
if i < 0:
reference_seq = defines.indel_char*insert_dict[i] + reference_seq
else:
reference_seq = reference_seq[:i] + defines.indel_char*insert_dict[i] + reference_seq[i:]
if i not in known_inserts: # This does not properly handle complex multi-insertion sites
known_insert_offset = sum(v for k,v in known_inserts.items() if k < i)
if known_insert_offset+i < args.window_size:
label_vector = np.insert(label_vector, known_insert_offset+i, np.zeros((insert_dict[i],)))[:args.window_size]
read_tensor = good_reads_to_tensor(args, good_reads, cur_pos, insert_dict)
reference_sequence_into_tensor(args, reference_seq, read_tensor)
tensor_path = get_path_to_train_valid_or_test(args.data_dir, variant.CHROM)
tensor_prefix = 'calling_tensor_' + plain_name(args.bam_file) +'_'+ plain_name(args.train_vcf)
tensor_path += tensor_prefix + '-' + args.chrom + '_' + str(cur_pos) + '_' +str(cur_pos+args.window_size) + '.hd5'
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
if pileup:
pileup_tensor = read_tensor_to_pileup(args, read_tensor)
hf.create_dataset('pileup_tensor', data=pileup_tensor, compression='gzip')
else:
hf.create_dataset(args.tensor_map, data=read_tensor, compression='gzip')
hf.create_dataset('site_labels', data=label_vector, compression='gzip')
cur_pos += args.window_size
stats['count'] += 1
if stats['count']%400 == 0:
print('Wrote', stats['count'], 'calling tensors out of', args.samples)
for s in stats.keys():
print(s, 'has:', stats[s])
try:
print('Last variant was', variant)
except NameError as e:
print('Have not yet seen a variant...')
if stats['count'] >= args.samples:
break
if stats['count'] > 0:
print('Done generating tensors from vcf:', args.train_vcf, 'count is:', stats['count'])
for s in stats.keys():
print(s, 'has:', stats[s])
def tensors_from_tensor_map_gnomad_annos(args):
'''Create tensors structured as tensor map of reads organized by labels in the data directory.
Defines true variants as those in the args.train_vcf, defines false variants as
those filtered according to hard filters used to train gnomAD's Random forest model.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.negative_vcf: VCF file with annotation values from Haplotype caller or VQSR
args.train_vcf: VCF file with true variant (from NIST or Platinum genomes, etc.)
args.bed_file: High confidence intervals for the calls in args.train_vcf
args.window_size: Size of sequence window around variant (width of the tensor)
args.read_limit: Maximum number of reads to include (height of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
'''
print('Writing tensors from tensor channel map, with gnomAD annotations.')
stats = Counter()
debug = False
gnomads = gnomads_to_dict(args)
#bed_dict = bed_file_to_dict(args.bed_file)
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
#vcf_reader = vcf.Reader(open(args.negative_vcf, 'r'))
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
vcf_omni = vcf.Reader(open(defines.omni_vcf, 'r'))
vcf_mills = vcf.Reader(open(defines.mills_vcf, 'r'))
tensor_channel_map = defines.get_tensor_channel_map()
variants = gnomads[args.chrom].fetch(args.chrom, args.start_pos, args.end_pos)
for variant in variants:
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[variant.POS-idx_offset: variant.POS+idx_offset]
# annotation_variant = variant_in_vcf(variant, gnomads[variant.CHROM])
# if not annotation_variant:
# stats['Variants not in annotation_vcf'] += 1
# continue
# in_bed = in_bed_file(bed_dict, variant.CHROM, variant.POS)
#if variant_in_vcf(variant, vcf_ram) and in_bed:
if variant_in_vcf(variant, vcf_mills) or variant_in_vcf(variant, vcf_omni):
class_prefix = ''
elif is_rf_hard_filter_negative(args, variant, stats):
class_prefix = 'NOT_'
else:
stats['Unassigned truth status for variant'] += 1
continue
if variant.is_snp:
cur_label_key = class_prefix + 'SNP'
elif variant.is_indel:
cur_label_key = class_prefix + 'INDEL'
else:
stats['Not SNP or INDEL'] += 1
continue
if args.downsample_snps < 1.0 and cur_label_key == 'SNP':
dice = np.random.rand()
if dice > args.downsample_snps:
stats['Downsampled SNPs'] += 1
continue
if all(map(lambda x: x not in variant.INFO and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = get_annotation_data(args, variant, stats)
qual_and_dp_normalizer = 1000000.0
for i,a in enumerate(args.annotations):
if a == "DP" or a == "QUAL":
annotation_data[i] /= qual_and_dp_normalizer
dna_data = np.zeros( (args.window_size, len(defines.inputs)) )
for i,b in enumerate(record.seq):
if b in defines.inputs:
dna_data[i, defines.inputs[b]] = 1.0
elif b in defines.ambiguity_codes:
dna_data[i] = defines.ambiguity_codes[b]
else:
raise ValueError('Error! Unknown code:', b)
tensor_path = get_path_to_train_valid_or_test(args, variant.CHROM)
tensor_prefix = plain_name(defines.omni_vcf) + '-' + cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + variant.CHROM + '_' + str(variant.POS) + '.hd5'
stats[cur_label_key] += 1
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
hf.create_dataset(args.annotation_set, data=annotation_data)
hf.create_dataset(args.tensor_map, data=dna_data)
stats['count'] += 1
if stats['count']%400 == 0:
print('Wrote', stats['count'], 'tensors out of', args.samples, ' last variant:', str(variant))
if stats['count'] >= args.samples:
break
for s in stats.keys():
print(s, 'has:', stats[s])
print('Done generating gnomAD annotated tensors. Last variant:', str(variant), 'count is:', stats['count'])
print('Tensors saved at: ', args.data_dir)
def tensors_from_tensor_map_gnomad_annos_per_allele(args, include_reads=True, include_annotations=True, include_reference=False):
'''Create allele specific tensors structured as tensor map of reads organized by labels in the data directory.
Defines true variants as those in the args.train_vcf, defines false variants as
those called in args.negative_vcf and in the args.bed_file high confidence intervals,
but not in args.train_vcf.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.negative_vcf: VCF file with annotation values from Haplotype caller or VQSR
args.train_vcf: VCF file with true variant (from NIST or Platinum genomes, etc.)
args.bed_file: High confidence intervals for the calls in args.train_vcf
args.window_size: Size of sequence window around variant (width of the tensor)
args.read_limit: Maximum number of reads to include (height of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
'''
print('Writing allele specific tensors from tensor channel map with gnomAD annotations.')
stats = Counter()
debug = False
gnomads = gnomads_to_dict(args)
samfile = pysam.AlignmentFile(args.bam_file, "rb")
bed_dict = bed_file_to_dict(args.bed_file)
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = vcf.Reader(open(args.negative_vcf, 'r'))
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
tensor_channel_map = defines.get_tensor_channel_map()
if args.chrom:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_index, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[variant.POS-idx_offset: variant.POS+idx_offset]
cur_label_key = get_true_allele_label(allele, variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats):
continue
if include_annotations:
annotation_variant = variant_in_vcf(variant, gnomads[variant.CHROM])
if not annotation_variant:
stats['Variants not in annotation_vcf'] += 1
continue
if all(map(lambda x: x not in annotation_variant.INFO and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = np.zeros(( len(args.annotations), ))
qual_and_dp_normalizer = 1000000.0
as_normalizer = 100.0
for i,a in enumerate(args.annotations):
if a in ['DP_MEDIAN', 'DREF_MEDIAN', 'GQ_MEDIAN', 'AB_MEDIAN']:
if not math.isnan(annotation_variant.INFO[a][allele_index]):
annotation_data[i] = annotation_variant.INFO[a][allele_index]
elif a == "QUAL":
annotation_data[i] = float(annotation_variant.QUAL)
else:
annotation_data[i] = annotation_variant.INFO[a]
if a == "DP" or a == "QUAL":
annotation_data[i] /= qual_and_dp_normalizer
if a == "DP_MEDIAN" or a == "GQ_MEDIAN":
annotation_data[i] /= as_normalizer
if include_reference:
dna_data = np.zeros( (args.window_size, len(defines.inputs)) )
for i,b in enumerate(record.seq):
if b in defines.inputs:
dna_data[i, defines.inputs[b]] = 1.0
elif b in defines.ambiguity_codes:
dna_data[i] = defines.ambiguity_codes[b]
else:
raise ValueError('Error! Unknown code:', b)
if include_reads:
good_reads, insert_dict = get_good_reads(args, samfile, variant)
reference_seq = record.seq
for i in sorted(insert_dict.keys(), key=int, reverse=True):
reference_seq = reference_seq[:i] + defines.indel_char*insert_dict[i] + reference_seq[i:]
sequences, qualities, mapping_qualities, flags = good_reads_to_arrays(args, good_reads, ref_start, insert_dict)
if len(sequences) > 0:
ref_read_idx = defines.get_reference_and_read_channels(args)
if args.channels_last:
read_tensor = np.zeros( (args.read_limit, args.window_size, len(tensor_channel_map)) )
read_tensor[:,:,:ref_read_idx] = reads_to_tensor(args, sequences, qualities, reference_seq)
else:
read_tensor = np.zeros( (len(tensor_channel_map), args.read_limit, args.window_size) )
read_tensor[:ref_read_idx,:,:] = reads_to_tensor(args, sequences, qualities, reference_seq)
add_flags_to_read_tensor(args, read_tensor, tensor_channel_map, flags)
add_mq_to_read_tensor(args, read_tensor, tensor_channel_map, mapping_qualities)
tensor_path = get_path_to_train_valid_or_test(args.data_dir, variant.CHROM)
tensor_prefix = plain_name(args.negative_vcf) +'_'+ plain_name(args.train_vcf) +'_allele_'+ str(allele_index) + '-' + cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + variant.CHROM + '_' + str(variant.POS) + '.hd5'
stats[cur_label_key] += 1
stats['Allele index '+str(allele_index)] += 1
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
if include_reads:
hf.create_dataset(args.tensor_map, data=read_tensor)
if include_annotations:
hf.create_dataset(args.annotation_set, data=annotation_data)
if include_reference:
hf.create_dataset('reference', data=dna_data)
stats['count'] += 1
if stats['count']%400 == 0:
print('Wrote', stats['count'], 'tensors out of', args.samples, ' last variant:', str(variant))
if stats['count'] >= args.samples:
break
for s in stats.keys():
print(s, 'has:', stats[s])
print('Done generating gnomAD annotated tensors. Last variant:', str(variant), 'from vcf:', args.negative_vcf, 'count is:', stats['count'])
def tensors_from_tensor_map_2channel(args, include_annotations=True):
'''Create tensors structured as tensor map of reads organized by labels in the data directory.
Defines true variants as those in the args.train_vcf, defines false variants as
those called in args.negative_vcf and in the args.bed_file high confidence intervals,
but not in args.train_vcf.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.negative_vcf: VCF file with annotation values from Haplotype caller or VQSR
args.train_vcf: VCF file with true variant (from NIST or Platinum genomes, etc.)
args.bed_file: High confidence intervals for the calls in args.train_vcf
args.window_size: Size of sequence window around variant (width of the tensor)
args.read_limit: Maximum number of reads to include (height of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
'''
print('Writing 2 bit DNA tensors from tensor channel map.')
stats = Counter()
debug = False
args.input_symbols = defines.dna_2bit
samfile = pysam.AlignmentFile(args.bam_file, "rb")
bed_dict = bed_file_to_dict(args.bed_file)
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = vcf.Reader(open(args.negative_vcf, 'r'))
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
tensor_channel_map = defines.get_tensor_channel_map_from_args(args)
if args.chrom:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_idx, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[ ref_start : ref_end ]
cur_label_key = get_true_site_label(variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats):
continue
if include_annotations:
if all(map(lambda x: x not in variant.INFO and x not in variant.FORMAT and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = get_annotation_data(args, variant, stats)
good_reads, insert_dict = get_good_reads(args, samfile, variant)
reference_seq = record.seq
for i in sorted(insert_dict.keys(), key=int, reverse=True):
reference_seq = reference_seq[:i] + defines.indel_char*insert_dict[i] + reference_seq[i:]
sequences, qualities, mapping_qualities, flags = good_reads_to_arrays(args, good_reads, ref_start, insert_dict)
if len(sequences) > 0:
if args.channels_last:
read_tensor = np.zeros( (args.read_limit, args.window_size, len(tensor_channel_map)) )
read_tensor[:,:,:6] = reads_to_2bit_tensor(args, sequences, qualities, reference_seq)
else:
read_tensor = np.zeros( (len(tensor_channel_map), args.read_limit, args.window_size) )
read_tensor[:6,:,:] = reads_to_2bit_tensor(args, sequences, qualities, reference_seq)
add_flags_to_read_tensor(args, read_tensor, tensor_channel_map, flags)
add_mq_to_read_tensor(args, read_tensor, tensor_channel_map, mapping_qualities)
tensor_path = get_path_to_train_valid_or_test(args.data_dir, variant.CHROM)
tensor_prefix = plain_name(args.negative_vcf) +'_'+ plain_name(args.train_vcf) +'_allele_'+ str(allele_index) +'-'+ cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + variant.CHROM + '_' + str(variant.POS) + '.hd5'
stats[cur_label_key] += 1
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
hf.create_dataset(args.tensor_map, data=read_tensor)
if include_annotations:
hf.create_dataset(args.annotation_set, data=annotation_data)
if debug:
print('Reads:', len(good_reads), 'count:', stats['count'], 'Variant:', variant.CHROM, variant.POS, variant.REF, variant.ALT, '\n')
for i,s in enumerate(sequences):
print(s+' cigar:'+good_reads[i].cigarstring)
print(str(reference_seq)+'<- reference sequence\n\n')
stats['count'] += 1
if stats['count']%400 == 0:
print('Wrote', stats['count'], 'tensors out of', args.samples, ' last variant:', str(variant))
if stats['count'] >= args.samples:
break
for s in stats.keys():
print(s, 'has:', stats[s])
print('Done generating tensors. Last variant:', str(variant), 'from vcf:', args.negative_vcf, 'count is:', stats['count'])
def bqsr_tensors_from_tensor_map(args, include_annotations=False):
"""Create tensors structured as tensor map of read and reference organized by labels in the data directory.
Defines true bases as those not in args.db_snp, where read and reference agree.
False bases are sites thos not in args.db_snp where the read and the reference do NOT agree.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.train_vcf: VCF file with sites of known variation, from NIST, DBSNP etc.
args.bed_file: Intervals of interest
args.window_size: Size of sequence window around variant (width of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
"""
print('Writing BQSR tensors from tensor channel map.')
stats = Counter()
samfile = pysam.AlignmentFile(args.bam_file, "rb")
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
bed_dict = bed_file_to_dict(args.bed_file)
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
contig = record_dict[args.chrom]
tensor_channel_map = defines.bqsr_tensor_channel_map()
for read in samfile.fetch(args.chrom, args.start_pos, args.end_pos):
if read.is_reverse:
continue
read_group = read.get_tag('RG')
if 'artificial' in read_group.lower():
continue
if not read.is_proper_pair or not read.is_paired:
continue
if read.is_duplicate or read.is_secondary or read.is_supplementary or read.is_qcfail or read.is_unmapped:
continue
for ref_pos, read_idx in zip(read.get_reference_positions(), range(len(read.query_sequence))):
if contig[ref_pos] != read.query_sequence[read_idx]:
variants = vcf_ram.fetch(args.chrom, ref_pos-1, ref_pos+1)
in_vcf = False
for v in variants:
in_vcf |= any([a1 == read.query_sequence[read_idx] for a1 in v.ALT]) and ref_pos == v.POS
if in_vcf:
stats['Already in known variation VCF'] += 1
continue
cur_label_key = 'BAD_BASE'
else:
if args.downsample_snps < 1.0:
dice = np.random.rand()
if dice > args.downsample_snps:
continue
cur_label_key = 'GOOD_BASE'
stats[cur_label_key] += 1
ref_string = contig.seq[ref_pos-args.window_size:ref_pos]
read_string = read.query_sequence[max(0,read_idx-args.window_size) : read_idx]
read_qualities = read.query_alignment_qualities[max(0,read_idx-args.window_size) : read_idx].tolist()
if read_idx-args.window_size < 0:
read_string = defines.skip_char * (args.window_size-read_idx) + read_string
read_qualities = [0] * (args.window_size-read_idx) + read_qualities
read_tensor = np.zeros((args.window_size, len(tensor_channel_map)))
read_tensor[:, 0:len(args.input_symbols)] = base_string_to_tensor(args, read_string, read_qualities)
read_tensor[:, len(args.input_symbols):(2*len(args.input_symbols))] = base_string_to_tensor(args, ref_string)
if include_annotations:
max_mq = 60.0
max_read_pos = 151.0
annotation_data = np.zeros(( len(defines.bqsr_annotations), ))
for i,a in enumerate(defines.bqsr_annotations):
if a == "reverse":
annotation_data[i] = float(read.is_reverse)
elif a == 'first_in_pair':
annotation_data[i] = float(read.is_read1)
elif a == 'mapping_quality':
annotation_data[i] = float(read.mapping_quality) / max_mq
elif a == 'read_position':
annotation_data[i] = float(read_idx) / max_read_pos
tensor_path = get_path_to_train_valid_or_test(args, args.chrom)
tensor_prefix = plain_name(args.bam_file) +'_'+ plain_name(args.train_vcf) + '-' + cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + args.chrom + '_' + str(ref_pos) + '.hd5'
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
hf.create_dataset(args.tensor_map, data=read_tensor)
if include_annotations:
hf.create_dataset(args.annotation_set, data=annotation_data)
stats['count'] += 1
if stats['count']%400 == 0:
print('Wrote', stats['count'], 'tensors out of', args.samples)
if stats['count'] >= args.samples:
break
if stats['count'] >= args.samples:
break
for k in stats.keys():
print('%s has %d' %(k, stats[k]))
print('Done generating BQSR tensors. Wrote them to:', args.data_dir ,' Known variation vcf:', args.train_vcf)
def write_dna_and_annotations(args, include_dna=True, include_annotations=True):
debug = False
stats = Counter()
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = vcf.Reader(open(args.negative_vcf, 'r'))
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
bed_dict = bed_file_to_dict(args.bed_file)
idx_offset = (args.window_size//2)
if args.chrom:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_idx, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[variant.POS-idx_offset: variant.POS+idx_offset]
cur_label_key = get_true_label(allele, variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats):
continue
if include_annotations:
if all(map(lambda x: x not in variant.INFO and x not in variant.FORMAT and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = get_annotation_data(args, variant, stats)
if include_dna:
dna_data = np.zeros( (args.window_size, len(defines.inputs)) )
for i,b in enumerate(record.seq):
if b in defines.inputs:
dna_data[i, defines.inputs[b]] = 1.0
elif b in defines.ambiguity_codes:
dna_data[i] = defines.ambiguity_codes[b]
else:
raise ValueError('Error! Unknown code:', b)
tensor_path = get_path_to_train_valid_or_test(args.data_dir)
tensor_path += cur_label_key +'/'+ plain_name(args.negative_vcf) +'_'+ plain_name(args.train_vcf)
tensor_path += '_allele_' + str(allele_idx) +'-'+ variant.CHROM +'_'+ str(variant.POS) + '.hd5'
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
if debug:
print('Try to write tensor to:', tensor_path)
print('Sequence was:', record.seq)
print('DNA tensor is:', dna_data)
print('Annotation tensor is:', annotation_data)
with h5py.File(tensor_path, 'w') as hf:
if include_annotations:
hf.create_dataset(args.annotation_set, data=annotation_data, compression='gzip')
if include_dna:
hf.create_dataset(args.tensor_map, data=dna_data, compression='gzip')
stats[cur_label_key] += 1
stats['count'] += 1
if stats['count']%500==0:
print('Wrote', stats['count'], 'out of:', args.samples, 'Last variant:', variant)
if args.samples == stats['count']:
break
print('Done Writing. DNA:', include_dna,' and Annotations:',include_annotations, ' Wanted: ', args.samples)
for k in stats.keys():
print(k, ' has:', stats[k])
def write_dna_multisource_annotations(args, include_dna=True, include_annotations=True):
debug = False
stats = Counter()
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = vcf.Reader(open(args.negative_vcf, 'r'))
vcf_ram = vcf.Reader(open(args.train_vcf, 'r'))
bed_dict = bed_file_to_dict(args.bed_file)
idx_offset = (args.window_size//2)
channel_map = defines.get_tensor_channel_map_from_args(args)
# Get bed file dicts
bed_dicts = {}
for b in channel_map.keys():
if os.path.exists(b) and os.path.splitext(b)[1].lower() == '.bed':
bed_dicts[b] = bed_file_to_dict(b)
# Do we need to fetch a particular region of the genome?
if args.chrom:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_idx, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[variant.POS-idx_offset: variant.POS+idx_offset+(args.window_size%2)]
cur_label_key = get_true_label(allele, variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats):
continue
if include_annotations:
if all(map(lambda x: x not in annotation_variant.INFO and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = get_annotation_data(args, variant, stats)
if include_dna:
dna_data = np.zeros( (args.window_size, len(channel_map)) )
for i,b in enumerate(record.seq):
# Get the reference DNA for the first 4 channels
if b in channel_map:
dna_data[i, channel_map[b]] = 1.0
elif b in defines.ambiguity_codes:
dna_data[i] = defines.ambiguity_codes[b]
else:
raise ValueError('Error! Unknown code:', b)
# Add data to remaining channels from bed files
ref_i = variant.POS-idx_offset + i
for k in channel_map.keys():
if k in defines.inputs:
continue
if in_bed_file(bed_dicts[k], variant.CHROM, ref_i):
dna_data[i, channel_map[k]] = 1.0 # TODO: update this to read a value from the bed file
tensor_path = get_path_to_train_valid_or_test(args.data_dir)
tensor_prefix = plain_name(args.negative_vcf) +'_'+ plain_name(args.train_vcf) +'_allele_'+ str(allele_idx) +'_'+ cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + variant.CHROM + '_' + str(variant.POS) + '.hd5'
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
if debug:
print('Try to write tensor to:', tensor_path)
print('Sequence was:', record.seq)
if include_dna:
print('DNA tensor is:\n', dna_data)
print('DNA Column sums are:', np.sum(dna_data, axis=0))
if include_annotations: