-
Notifications
You must be signed in to change notification settings - Fork 0
/
CNV_c2c.py
328 lines (253 loc) · 8.85 KB
/
CNV_c2c.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
#!/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
#from subprocess import call
import subprocess
"""
Script for parsing a small CNV vcf and outputting stats of regions covered by BED
"""
epi = ('\
\n\
File parser, allowing comparing of variants from BED files\n\
\n\
')
# Describe what the script does
parser = argparse.ArgumentParser(description='This script parses a VCF file and extracts regions from a BED file', epilog= epi, formatter_class=argparse.RawTextHelpFormatter)
# Get inputs
parser.add_argument('-i', '--input', default=None, dest='bed', action='store', required=True, help="BED file to compare")
parser.add_argument('-r', '--ref', default=None, dest='ref', action='store', required=True, help="BED file ref")
# 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.bed)==True:
print("Cannot find input file ",args.bed)
sys.exit(1)
print ("BED file: ",args.bed)
print ("REF files: ", args.ref)
bed= open(args.bed, 'r')
res = {}
for line in bed:
elem = line.split("\t")
elem3=elem[3].split("\n")
#print(elem[0],elem[1],elem[2],elem[3])
lis=elem[0],elem[1],elem[2]
res[str(elem3[0])]={}
res[str(elem3[0])][lis]='1'
#people[3]['married'] = 'No'
#quit()
# For each VCF file, do bedtools intersect
for vcf in args.vcf:
#print (vcf, ["bedtools", "intersect","-b",args.bed,"-a",vcf,"-wo"])
proc = subprocess.Popen(["bedtools", "intersect","-b",args.bed,"-a",vcf,"-wo"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
#print ("OUT:", out)
out = out.split("\n")
# For each line in the output
for el in out:
# remove empty lines
if not (re.match('\w+', el)):
print ("Match: ", el,":")
next
# Process working lines
else:
ele=el.split("\t")
print("ELE2: ",el , ':')
quit()
for X in w:
ele2= ele[2].split(":") # Canvas:LOH:chr3:10001-4130170
cn=ele[4]
qual=ele[5]
call=ele[6]
info=ele[7]
format=ele[9].split(":")
# ele[10],ele[11],ele[12],ele[13]
#print(ele2[1],ele2[2],ele2[3],ele[13])
[sstart,send]=ele2[3].split("-")
for key in res[ele[13]]:
#print (key)
[chr,start,end]=key
nstart = max(sstart,start)
nend= min(send,end)
#print(nstart,nend)
# Remove start/end from the overlap
# Pick the data to summarise
# Create summary number
# Create summary picture
quit()
# 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[1].keys():
cn=r.samples[1]['CN']
if 'MCC' in r.samples[1].keys():
cn=r.samples[1]['MCC']
if 'RC' in r.samples[1].keys():
rc=r.samples[1]['RC']
for key in r.filter.keys():
filter=key
print (chr,pos,end,varID,score,strand,filter,svtype,rc,cn,mcc,sep='\t')
else:
print("Unknown",chr, pos, end, varID, score, strand, sep='\t')
"""
# 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)