Mercurial > repos > in_silico > cravat_vcf_convert
comparison cravat_convert/cravat_convert.py @ 12:2774c8433c4f draft
Uploaded
author | in_silico |
---|---|
date | Tue, 12 Jun 2018 12:07:09 -0400 |
parents | b968ba302ba6 |
children |
comparison
equal
deleted
inserted
replaced
11:338d106513fd | 12:2774c8433c4f |
---|---|
1 ''' | |
2 Convert a VCF format file to Cravat format file | |
3 ''' | |
4 | |
5 import os | |
6 import argparse | |
7 from vcf_converter import CravatConverter | |
8 | |
9 # File read/write configuration variables | |
10 vcf_sep = '\t' | |
11 cr_sep = '\t' | |
12 cr_newline = '\n' | |
13 | |
14 # VCF Headers mapped to their index position in a row of VCF values | |
15 vcf_mapping = { | |
16 'CHROM': 0, | |
17 'POS': 1, | |
18 'ID': 2, | |
19 'REF': 3, | |
20 'ALT': 4, | |
21 'QUAL': 5, | |
22 'FILTER': 6, | |
23 'INFO': 7, | |
24 'FORMAT': 8, | |
25 'NA00001': 9, | |
26 'NA00002': 10, | |
27 'NA00003': 11 | |
28 } | |
29 | |
30 | |
31 def get_args(): | |
32 parser = argparse.ArgumentParser() | |
33 parser.add_argument('--input', | |
34 '-i', | |
35 required = True, | |
36 help='Input path to a VCF file for conversion',) | |
37 parser.add_argument('--output', | |
38 '-o', | |
39 default = os.path.join(os.getcwd(), "cravat_converted.txt"), | |
40 help = 'Output path to write the cravat file to') | |
41 return parser.parse_args() | |
42 | |
43 | |
44 def convert(in_path, out_path=None): | |
45 if not out_path: | |
46 base, _ = os.path.split(in_path) | |
47 out_path = os.path.join(base, "cravat_converted.txt") | |
48 | |
49 with open(in_path, 'r') as in_file, \ | |
50 open(out_path, 'w') as out_file: | |
51 | |
52 # cr_count will be used to generate the 'TR' field of the cravat rows (first header) | |
53 cr_count = 0 | |
54 # VCF lines are always assumed to be '+' strand, as VCF doesn't specify that attribute | |
55 strand = '+' | |
56 # VCF converter. Adjusts position, reference, and alternate for Cravat formatting. | |
57 converter = CravatConverter() | |
58 | |
59 for line in in_file: | |
60 if line.startswith("#"): | |
61 continue | |
62 line = line.strip().split(vcf_sep) | |
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 convert(cli_args.input, cli_args.output) |