-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathExmFilt.4.VCFtoTable.py
More file actions
276 lines (237 loc) · 15 KB
/
ExmFilt.4.VCFtoTable.py
File metadata and controls
276 lines (237 loc) · 15 KB
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
#!/usr/bin/env python
#$ -N CustFilt -cwd
################################################################################################################
##### USAGE ###
################################################################################################################
#### The purpose of this script is to tabulare a VCF file, one line for each variant allele, all of the interesting INFO fields in columns
#### -v/--vcf <required> The script requires an input vcf
#### -o/--out <required> The user should specify a base name for the output files.
#### -p/--pos ...
################################################################################################################
################################################################################################################
################################################################################################################
##### GET PARAMETERS ###
################################################################################################################
import os
from optparse import OptionParser
parser = OptionParser()
## Basic Input Files, required
parser.add_option("-v", "--vcf", dest="VCFfile",help="Input VCF file", metavar="VCFfile")
parser.add_option("-o", "--out", dest="OutputFileName",help="Base of names for output files", metavar="OutputFileName")
(options, args) = parser.parse_args()
################################################################################################################
##### ASSIGN FILTER VARIABLES ###
################################################################################################################
## Variant Quality Filters
BadSnpFilters=['QD_Bad_SNP','FS_Bad_SNP','FS_Mid_SNP;QD_Mid_SNP']
BadInDFilters=['LowQD_Indel']
MidSnpFilters=['FS_Mid_SNP','QD_Mid_SNP','VQSRTrancheSNP99.00to99.90','VQSRTrancheSNP99.90to100.00']
MidInDFilters=['FSBias_Indel','RPBias_Indel','VQSRTrancheINDEL99.00to99.90','VQSRTrancheINDEL99.90to100.00']
## Variant classes
MissenseClass=['nonsynonymousSNV','unknown']
NonFrameshiftClass=['nonframeshiftdeletion','nonframeshiftinsertion','nonframeshiftsubstitution']
FrameshiftClass=['frameshiftdeletion','frameshiftinsertion','frameshiftsubstitution']
InDelClass=NonFrameshiftClass+FrameshiftClass
NonsenseClass=['stopgain','stoploss']
SplicingClass=['splicing','exonic,splicing']
################################################################################################################
##### OPEN INPUT FILES AND OUTPUT FILES ###
################################################################################################################
##Assign input and output files
VCF=open(options.VCFfile,'r')
BaseName=str(options.OutputFileName)
TabOutputFilename=BaseName+'.tsv'
Output=open(TabOutputFilename,'w')
LogOutputFilename=BaseName+'.log'
Outlog=open(LogOutputFilename,'w')
##write log file
import datetime
TimeNow=str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
Outlog.write("Tabulate VCF: "+TimeNow+"\n")
Outlog.write("VCF: "+str(options.VCFfile)+"\n")
Outlog.write("OutputName: "+str(options.OutputFileName)+"\n")
Outlog.write("\n")
################################################################################################################
##### START FILTERING ###
################################################################################################################
OrigCount=0
for line in VCF:
if line.startswith('#CHROM'):
################################################################################################################
##### INITIALISE OUTPUT FILES ###
################################################################################################################
linelist=line.split("\t", 9)
SampleList=linelist[9].strip()
AllSamplesList=SampleList.split("\t")
##Start output tables
headerlist=['Chromosome','Position','ID','REF','ALT', 'AlleleNum', 'Gene','VariantFunction','VariantClass','AAchange','AlleleFrequency.ExAC','AlleleFrequency.1KG','AlleleFrequency.ESP','AlleleFrequency.VCF','SIFTprediction','PP2prediction','MAprediction','MTprediction','GERP++','CADDscore','MetaSVMprediction','SegmentalDuplication','PredictionSummary','VariantCallQuality','QUAL','MQ0','DP','FILTER']+[ i+" GT" for i in AllSamplesList]+[ i+" AD" for i in AllSamplesList]+[ i+" DP" for i in AllSamplesList]+[ i+" GQ" for i in AllSamplesList]+['AlternateAlleles', 'INFO']
Output.write("\t".join(headerlist)+"\n")
if '#' not in line:
################################################################################################################
##### PARSE LINE AND GET VARIANT INFO ###
################################################################################################################
line=line.strip()
linelist=line.split("\t")
OrigCount=OrigCount+1
##Get Alternate Alleles
AltAllsStr=linelist[4]
AltAlls=AltAllsStr.split(",")
AltNum=len(AltAlls)
QUAL=float(linelist[5])
VariantFilter=linelist[6]
FORMAT=linelist[8]
FORMAT=FORMAT.split(":")
## Get variant data from INFO Field
INFOstring=linelist[7]
INFOcolumnList=INFOstring.split(";")
INFOdict={}
for element in INFOcolumnList:
if '=' in element:
FieldName,FieldValue=element.split('=',1)
INFOdict[FieldName]=FieldValue
DPnumber=float(INFOdict.get('DP','.'))
MQ0number=float(INFOdict.get('MQ0','.'))
GeneName=INFOdict.get('GeneName','.')
VariantFunction=INFOdict.get('VarFunc','none')
SegDup=INFOdict.get('SegDup','none')
KGFreqList=str(INFOdict.get('1KGfreq','.'))
KGFreqList=KGFreqList.split(',')
ESPFreqList=str(INFOdict.get('ESPfreq','.'))
ESPFreqList=ESPFreqList.split(',')
ExACFreqList=str(INFOdict.get('ExACfreq','.'))
ExACFreqList=ExACFreqList.split(",")
VCFFreqList=str(INFOdict.get('AF',0))
VCFFreqList=VCFFreqList.split(",")
VariantClassList=INFOdict.get('VarClass','none')
VariantClassList=VariantClassList.split(',')
AAchangeList=INFOdict.get('AAChange','.')
AAchangeList=AAchangeList.split(',')
SIFTpredictionList=INFOdict.get('SIFTprd','.')
SIFTpredictionList=SIFTpredictionList.split(',')
PP2predictionList=INFOdict.get('PP2.hvar.prd','.')
PP2predictionList=PP2predictionList.split(',')
MApredictionList=INFOdict.get('MutAprd','.')
MApredictionList=MApredictionList.split(',')
MTpredictionList=INFOdict.get('MutTprd','.')
MTpredictionList=MTpredictionList.split(',')
GERPscoreList=str(INFOdict.get('GERP','.'))
GERPscoreList=GERPscoreList.split(',')
CADDscoreList=str(INFOdict.get('CADDphred','.'))
CADDscoreList=CADDscoreList.split(',')
MetaSVMpredictionList=INFOdict.get('MetaSVMprd','.')
MetaSVMpredictionList=MetaSVMpredictionList.split(',')
################################################################################################################
##### CHECK TO SEE IF GENOTYPES PASS, ITERATE ACROSS MULTIPLE ALT ALLELES IF NECESSARY ###
################################################################################################################
AltRng=range(0, AltNum)
for altnum in AltRng:
################################################################################################################
##### VARIANT SPECIFIC CLASS CHECK, FREQUENCY AND VARIANT CALLING QUALITY ###
################################################################################################################
##check variant class
cltnum=min(len(VariantClassList)-1, altnum)
VariantClass=str(VariantClassList[cltnum])
## Check if KG passes threshold
cltnum=min(len(KGFreqList)-1, altnum)
KGFreq=str(KGFreqList[cltnum])
## Check if ESP passes threshold
cltnum=min(len(ESPFreqList)-1, altnum)
ESPFreq=str(ESPFreqList[cltnum])
## Check if ExAC passes threshold
cltnum=min(len(ExACFreqList)-1, altnum)
ExACFreq=str(ExACFreqList[cltnum])
## Check if VCF passes threshold
cltnum=min(len(VCFFreqList)-1, altnum)
VCFFreq=str(VCFFreqList[cltnum])
## Check and annotate pathogenicity (discard missense predicted to be benign - need to adjust this in splicining regions)
cltnum=min(len(SIFTpredictionList)-1, altnum)
SIFTprediction=SIFTpredictionList[cltnum]
cltnum=min(len(PP2predictionList)-1, altnum)
PP2prediction=PP2predictionList[cltnum]
cltnum=min(len(MetaSVMpredictionList)-1, altnum)
MetaSVMprediction=MetaSVMpredictionList[cltnum]
cltnum=min(len(CADDscoreList)-1, altnum)
CADDscore=str(CADDscoreList[cltnum])
if CADDscore == ".":
CADDscoretest=float(0)
else:
CADDscoretest=float(CADDscore)
#Set Patho level
PathoLevel="Low"
if VariantClass in MissenseClass and SIFTprediction=="." and PP2prediction=="." and CADDscore=="." and MetaSVMprediction==".":
PathoLevel="Med"
if VariantClass in MissenseClass and (SIFTprediction=="D" or PP2prediction=="D" or PP2prediction=="P" or CADDscoretest>=15):
PathoLevel="Med"
if VariantClass in MissenseClass and (SIFTprediction=="D" and PP2prediction=="D"):
PathoLevel="High"
if VariantClass in MissenseClass and (CADDscoretest>=25):
PathoLevel="High"
if VariantClass in MissenseClass and MetaSVMprediction=="D":
PathoLevel="High"
if VariantFunction in SplicingClass:
PathoLevel="High"
if VariantClass in InDelClass or VariantClass in NonsenseClass:
PathoLevel="High"
##Set Filter Quality summary
FILTER='High'
if VariantClass in InDelClass and any( str(i) in VariantFilter for i in MidInDFilters):
FILTER='Medium'
if VariantClass not in InDelClass and any( str(i) in VariantFilter for i in MidSnpFilters):
FILTER='Medium'
if VariantClass in InDelClass and any( str(i) in VariantFilter for i in BadInDFilters):
FILTER='Low'
if VariantClass not in InDelClass and any( str(i) in VariantFilter for i in BadSnpFilters):
FILTER='Low'
################################################################################################################
##### OUTPUTS ###
################################################################################################################
## If all pass then output line
cltnum=min(len(AAchangeList)-1, altnum)
AAchange=AAchangeList[cltnum]
cltnum=min(len(MApredictionList)-1, altnum)
MAprediction=MApredictionList[cltnum]
cltnum=min(len(MTpredictionList)-1, altnum)
MTprediction=MTpredictionList[cltnum]
##output
ALT=str(AltAlls[altnum])
cltnum=min(len(GERPscoreList)-1, altnum)
GERPscore=str(GERPscoreList[cltnum])
SampleStrings=linelist[9:]
SampleStrings=[ i.split(':') for i in SampleStrings ]
GTind=FORMAT.index('GT')
AllSampleGT=[ "." for i in range(0,len(SampleStrings))]
for i in range(0,len(SampleStrings)):
AllSampleGT[i]=SampleStrings[i][GTind]
if "AD" in FORMAT:
## Define Allele Count
ADind=FORMAT.index('AD')
AllSampleAD=[ "." for i in range(0,len(SampleStrings))]
for i in range(0,len(SampleStrings)):
if AllSampleGT[i]!="./.":
AllSampleAD[i]=SampleStrings[i][ADind]
if "GQ" in FORMAT:
## Define Allele Count
GQind=FORMAT.index('GQ')
AllSampleGQ=[ "." for i in range(0,len(SampleStrings))]
for i in range(0,len(SampleStrings)):
if AllSampleGT[i]!="./.":
print AllSampleGT[i]
print SampleStrings[i]
print i
print linelist[0]+" "+linelist[1]
AllSampleGQ[i]=SampleStrings[i][GQind]
if "DP" in FORMAT:
## Define Allele Count
DPind=FORMAT.index('DP')
AllSampleDP=[ "." for i in range(0,len(SampleStrings))]
for i in range(0,len(SampleStrings)):
if AllSampleGT[i]!="./.":
AllSampleDP[i]=SampleStrings[i][DPind]
#headerlist=['Chromosome','Position','ID','REF','ALT','Gene','VariantFunction','VariantClass','AAchange','AlleleFrequency.ExAC','AlleleFrequency.1KG','AlleleFrequency.ESP','AlleleFrequency.VCF','SIFTprediction','PP2prediction','MAprediction','MTprediction','GERP++','CADDscore','MetaSVMprediction','SegmentalDuplication','PredictionSummary','VariantCallQuality','QUAL','MQ0','DP','FILTER']+[ i+" GT" for i in AllSamplesList]+[ i+" AD" for i in AllSamplesList]+['AlternateAlleles', 'INFO']
OutputList=linelist[0:4]+[ALT,altnum+1,GeneName,VariantFunction,VariantClass,AAchange,ExACFreq,KGFreq,ESPFreq,VCFFreq,SIFTprediction,PP2prediction,MAprediction,MTprediction,GERPscore,CADDscore,MetaSVMprediction,SegDup,PathoLevel,FILTER,QUAL,MQ0number,DPnumber,VariantFilter]+AllSampleGT+AllSampleAD+AllSampleDP+AllSampleGQ+[AltAllsStr,INFOstring]
OutputList= [ str(i) for i in OutputList ]
OutputString="\t".join(OutputList)
Output.write(OutputString+"\n")
Outlog.write("\t Number of variants in original VCF: "+str(OrigCount)+"\n")
Outlog.write("Tabulation Complete: "+TimeNow+"\n")
print "Tabulation Complete "+TimeNow