comparison cravat_convert/cravat_convert.py @ 27:a7e641d146f5 draft

Uploaded
author in_silico
date Wed, 18 Jul 2018 10:25:44 -0400
parents
children
comparison
equal deleted inserted replaced
26:326aadaa3dd9 27:a7e641d146f5
1 import os
2 import argparse
3 from vcf_converter import CravatConverter
4 from __future__ import print_function
5
6 def get_vcf_mapping():
7 """ : VCF Headers mapped to their index position in a row of VCF values.
8 : These are only the mandatory columns, per the VCF spec.
9 """
10 return {
11 'CHROM': 0,
12 'POS': 1,
13 'ID': 2,
14 'REF': 3,
15 'ALT': 4,
16 'QUAL': 5,
17 'FILTER': 6,
18 'INFO': 7
19 }
20
21
22 def get_args():
23 parser = argparse.ArgumentParser()
24 parser.add_argument('--input',
25 '-i',
26 required = True,
27 help='Input path to a VCF file for conversion',)
28 parser.add_argument('--output',
29 '-o',
30 default = None,
31 help = 'Output path to write the cravat file to')
32 return parser.parse_args()
33
34
35 def convert(in_path, out_path=None, cr_sep='\t', cr_newline='\n'):
36 """ : Convert a VCF file to a Cravat file.
37 : Arguments:
38 : in_path: <str> path to input vcf file
39 : out_path: <str> path to output cravat file. Will defualt to cravat_converted.txt in the input directory.
40 : cr_sep: <str> the value delimiter for the output cravat file. Default value of '\\t'.
41 : out_newline: <str> the newline delimiter in the output cravat file. Default of '\\n'
42 """
43 if not out_path:
44 base, _ = os.path.split(in_path)
45 out_path = os.path.join(base, "cravat_converted.txt")
46
47 with open(in_path, 'r') as in_file, \
48 open(out_path, 'w') as out_file:
49
50 # cr_count will be used to generate the 'TR' field of the cravat rows (first header)
51 cr_count = 0
52 # VCF lines are always assumed to be '+' strand, as VCF doesn't specify that attribute
53 strand = '+'
54 # VCF converter. Adjusts position, reference, and alternate for Cravat formatting.
55 converter = CravatConverter()
56 # A dictionary of mandatory vcf headers mapped to their row indices
57 vcf_mapping = get_vcf_mapping()
58
59 for line in in_file:
60 if line.startswith("#"):
61 continue
62 line = line.strip().split()
63 # row is dict of VCF headers mapped to corresponding values of this line
64 row = { header: line[index] for header, index in vcf_mapping.items() }
65 for alt in row["ALT"].split(","):
66 new_pos, new_ref, new_alt = converter.extract_vcf_variant(strand, row["POS"], row["REF"], alt)
67 new_pos, new_ref, new_alt = str(new_pos), str(new_ref), str(new_alt)
68 cr_line = cr_sep.join([
69 'TR' + str(cr_count), row['CHROM'], new_pos, strand, new_ref, new_alt, row['ID']
70 ])
71 out_file.write(cr_line + cr_newline)
72 cr_count += 1
73
74
75 if __name__ == "__main__":
76 cli_args = get_args()
77 if cli_args.output == None:
78 base, _ = os.path.split(cli_args.input)
79 cli_args.output = os.path.join(base, "cravat_converted.txt")
80 convert(in_path = cli_args.input, out_path = cli_args.output)