-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfilter_long_indels.py
110 lines (77 loc) · 2.9 KB
/
filter_long_indels.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
#!/usr/bin/env python
#title :filter_long_indels.py
#author :Fernanda Martins Rodrigues (@fernanda);
#date :20191908
"""
This script takes as input a VCF file and filters indels which ref and/or alt alleles are more than 100bp long.
This step is good to remove misscalls from pindel.
This script outputs a file with the suffix '.noLongIndels.vcf'
Usage:
python filter_long_indels.py [-h] -i <input VCF file> -O <output directory>
Arguments:
-i, --inputVCF: input VCF file; gzip compressed
-O, --outputDirectory: directory to write output files to
-h, --help: prints usage documentation
"""
import sys
import argparse
import getopt
import gzip
import os
def argument_parser():
# create parser
parser = argparse.ArgumentParser(description=__doc__)
# add arguments
parser.add_argument("-i", "--inputVCF", required=True, help="input VCF file; gzip compressed")
parser.add_argument("-O", "--outputDirectory", default=os.getcwd(), help="directory to write output files to")
args = vars(parser.parse_args())
inputVCF = args["inputVCF"]
outputDirectory = args["outputDirectory"]
if outputDirectory[-1] != '/':
outputDirectory = outputDirectory + '/'
if not os.path.exists(outputDirectory):
os.makedirs(outputDirectory)
return inputVCF, outputDirectory
###############
## MAIN CODE ##
###############
def main():
vcfFile, outDir = argument_parser()
try:
vcfF = gzip.open(vcfFile,"rt")
except IOError:
print("VCF file does not exist!")
outFile_suffix = ".noLongIndels.vcf"
inputFile_basename = vcfFile.split('/')[-1]
outFile = outDir+inputFile_basename.replace(".vcf.gz",outFile_suffix)
outF = open(outFile, "w")
all_var = 0 # will count total number of variants in input file
nonpass_var = 0
pass_var = 0
# Start parsing input VCF file
for line in vcfF:
line=line.strip()
# print the info lines to output file
if line.startswith('#'):
outF.write(line + "\n")
else:
var = line.split("\t")
all_var += 1
ref = str(var[3]) # get reference allele
alt = str(var[4]) # get alternative allele
### if ref and/or alternative allele are bigger than 100 bp, variant will be filtered out.
if len(ref) > 100:
nonpass_var +=1
elif len(alt) > 100:
nonpass_var += 1
else:
pass_var += 1
outF.write(line + "\n")
# Filter summary:
print("Number of total variants:", all_var)
print("Number of variants failing indel filter:", nonpass_var)
print("Number of variants passing indel filter:", pass_var)
outF.close()
if __name__ == "__main__":
main()
## END ##################################