-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBED_from_VCF_SV.py
245 lines (199 loc) · 7.08 KB
/
BED_from_VCF_SV.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
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
import sys
import os.path
import argparse
import csv
import pysam
import re
"""
Script for parsing a small SV vcf and outputting BED
"""
epi = ('\
\n\
File parser, allowing counting of SV variaint from VCF files\n\
\n\
')
# Describe what the script does
parser = argparse.ArgumentParser(description='This script parses a VCF file and converts it to a BED file', epilog= epi, formatter_class=argparse.RawTextHelpFormatter)
# Get inputs
parser.add_argument('-i', '--input', default=None, dest='vcf', action='store', required=True, help="VCF file")
# Check for no input
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
# Check if input files exist
if not os.path.isfile(args.vcf)==True:
print("Cannot find input file ",args.vcf)
sys.exit(1)
# read the input file
myvcf = pysam.VariantFile(args.vcf, "r")
# create an object of new bed file and open in to write data.
output=args.vcf+".bed"
out = open(output, 'w')
for r in myvcf:
#### FILTER OUT #####
# Shared called total
# Filter out sites which
chr = r.chrom
pos = r.pos
id = str(r.id)
varID=':'.join([id.split(":")[0],id.split(":")[1]])
#altb = r.ref
#altb = r.alts
score = r.qual
filter = r.filter
info = r.info
format = r.format
samples = r.samples
end = r.stop # r.info["END"]
strand='.'
svtype='NA'
if 'SVTYPE' in r.info.keys():
svtype = r.info.get('SVTYPE', "")
#for key in r.info.keys():
# data = r.info.get(key, "")
# print (key,data)
# svtype=r.info['SVTYPE']
# FORMAT
#['PR', 'SR', 'RC', 'BC', 'CN', 'MCC']
# Split out Manta calls
if re.match(r'Manta', varID):
pass
#print("Manta",chr, pos, end, varID, score, strand, sep='\t')
#print (list((r.header.filters)))
#print(list((r.header.formats)))
elif re.match(r'Canvas', varID):
# Extract relevant information
cn='NA'
mcc='NA'
filter='NA'
rc='NA'
if 'CN' in r.samples[0].keys():
cn=r.samples[0]['CN']
if 'MCC' in r.samples[0].keys():
mcc=r.samples[0]['MCC']
if 'RC' in r.samples[0].keys():
rc=r.samples[0]['RC']
for key in r.filter.keys():
filter=key
print (chr,pos,end,varID,score,strand,filter,svtype,rc,cn,mcc,sep='\t', file=out)
else:
print("Unknown",chr, pos, end, varID, score, strand, sep='\t')
out.close()
"""
# open up file
with open(args.vcf, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter ='\t')
for row in reader:
tsvout =""
# pass header
if row[0].startswith("#"):
pass
# CANVAS
# only count canvas if Gain or Loss
elif "Canvas" in row[2] and "REF" not in row[2]:
# add to tsv file
varID= row[2].split(":")
end = row[7].split('END=')[-1]
# if fist line do not add line break
if len(tsvout) < 1:
# sample chr start end QUAL Filter tool change
tsvout += sample + "\t"+ row[0] + "\t"+ row[1]+ "\t"+ end +"\t"+ row[5]+"\t"+ row[6] +\
"\t"+ varID[0]+ "\t"+ varID[1]
else:
tsvout += "\n"+ sample + "\t"+ row[0] + "\t"+ row[1]+ "\t"+ end +"\t"+ row[5]+"\t"+ row[6] + \
"\t" + varID[0]+ "\t"+ varID[1]
# add to tallies
if "PASS" in row:
canvasT += 1
if "LOSS" in row[2]:
canvasLoss += 1
elif "GAIN" in row[2]:
canvasGain += 1
print(tsvout)
# MANTA
# tally up Manta outputs
elif "Manta" in row[2]:
# find SV type
varID = row[2].split(":")
QUAL = "."
vcffilter = "."
end = "."
# identify translocations
if "MantaBND" in row[2]:
# No Ends in BND cases as they are translocations - add N/A to end field for the TSV
end = "."
QUAL = "."
vcffilter = row[6]
# add to tallys
if "PASS" in row:
MantaT += 1
MantaBND += 1
# identify Dels - can be problematic
elif "MantaDEL" in row[2]:
# some Dels columns out of sync with no ref or QUAL field so need to find end value from appropated field
if len(row) ==11:
end = row[7].split(';')[0]
QUAL = row[5]
vcffilter = row[6]
elif len(row) < 11:
#check which column end and Filter criteria are in
if "END=" in row[5]:
end = row[5].split(';')[0]
QUAL = "."
vcffilter = row[4]
elif "END=" in row[6]:
end = row[6].split(';')[0]
QUAL = "."
vcffilter = row[4]
else:
pass
else:
pass
end = "".join(i for i in end if i.isdigit())
# add to tallys
if "PASS" in row:
MantaT += 1
MantaDEL += 1
# Finds invs
elif "MantaINV" in row[2]:
end = row[7].split(';')[0]
end = "".join(i for i in end if i.isdigit())
QUAL = row[5]
vcffilter = row[6]
# add to tallys
if "PASS" in row:
MantaT += 1
MantaINV += 1
# find DUPs
elif "MantaDUP" in row[2]:
end = row[7].split(';')[0]
end = "".join(i for i in end if i.isdigit())
QUAL = row[5]
vcffilter = row[6]
# add to tallys
if "PASS" in row:
MantaT += 1
MantaDUP += 1
# write to tsv. If first record do not add the \n
if len(tsvout) < 1:
# sample chr start end QUAL Filter tool change
tsvout += sample + "\t" + row[0] + "\t" + row[1] + "\t" + end + "\t" + QUAL + "\t" + vcffilter + \
"\tManta\t" + varID[0]
else:
tsvout += "\n" + sample + "\t" + row[0] + "\t" + row[1] + "\t" + end + "\t" + QUAL + "\t" + vcffilter + \
"\tManta\t" + varID[0]
print(tsvout)
else:
pass
tally_out = open(output, 'w')
tally_out.write("Sample\tcanvas_Total\tcanvas_Gain\tcanvas_Loss\tManta_Total\tManta_BND\tManta_DEL\tManta_INV\tMantaDUP\n")
tally_out.write(str(sample) + "\t" + str(canvasT)+ "\t" + str(canvasGain) + "\t" + str(canvasLoss)+ "\t" +
str(MantaT) + "\t" + str(MantaBND)+ "\t" + str(MantaDEL)+ "\t" +str(MantaINV) +"\t" + str(MantaDUP) + "\n")
tally_out.close()
"""
out.close()
exit(0)