pzweuj commited on
Commit
3dd81ff
·
verified ·
1 Parent(s): 4ce9a26

Upload mskcc_maf_to_vcf.py

Browse files
Files changed (1) hide show
  1. bin/mskcc_maf_to_vcf.py +261 -0
bin/mskcc_maf_to_vcf.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert MAF file to VCF format with deduplication.
4
+ This script converts cancerhotspots.v2.maf.gz to VCF format.
5
+ Duplicate positions are merged and tumor types are aggregated.
6
+ """
7
+
8
+ import gzip
9
+ import argparse
10
+ from collections import defaultdict
11
+
12
+
13
+ def parse_args():
14
+ parser = argparse.ArgumentParser(description='Convert MAF to VCF format with deduplication')
15
+ parser.add_argument('input_maf', help='Input MAF file (can be .gz compressed)')
16
+ parser.add_argument('output_vcf', help='Output VCF file')
17
+ return parser.parse_args()
18
+
19
+
20
+ def get_maf_columns(header_line):
21
+ """Parse MAF header to get column indices."""
22
+ columns = header_line.strip().split('\t')
23
+ col_map = {name: idx for idx, name in enumerate(columns)}
24
+ return col_map
25
+
26
+
27
+ def maf_to_vcf(maf_file, vcf_file):
28
+ """Convert MAF file to VCF format with deduplication."""
29
+
30
+ # Columns we need for VCF
31
+ required_cols = [
32
+ 'Chromosome', 'Start_Position', 'End_Position',
33
+ 'Reference_Allele', 'Tumor_Seq_Allele1', 'Tumor_Seq_Allele2'
34
+ ]
35
+
36
+ # Additional columns to include in INFO
37
+ info_cols = [
38
+ 'FILTER', 'TUMORTYPE', 'judgement',
39
+ 'oncotree_organtype',
40
+ 'Variant_Classification', 'Variant_Type',
41
+ 't_depth', 't_ref_count', 't_alt_count',
42
+ ]
43
+
44
+ # Dictionary to store deduplicated records
45
+ # Key: (chrom, pos, ref, alt) -> Value: dict with aggregated info
46
+ records_dict = {}
47
+
48
+ # Open input (handle gzipped or plain text)
49
+ if maf_file.endswith('.gz'):
50
+ maf_handle = gzip.open(maf_file, 'rt')
51
+ else:
52
+ maf_handle = open(maf_file, 'r')
53
+
54
+ first_line = True
55
+ total_records = 0
56
+ skipped_records = 0
57
+
58
+ for line in maf_handle:
59
+ line = line.strip()
60
+ if not line:
61
+ continue
62
+
63
+ # Skip comment lines
64
+ if line.startswith('#'):
65
+ continue
66
+
67
+ # First data line is the header
68
+ if first_line:
69
+ col_map = get_maf_columns(line)
70
+
71
+ # Verify required columns exist
72
+ missing_cols = [c for c in required_cols if c not in col_map]
73
+ if missing_cols:
74
+ raise ValueError(f"Missing required columns: {missing_cols}")
75
+
76
+ first_line = False
77
+ continue
78
+
79
+ # Process data line
80
+ fields = line.split('\t')
81
+
82
+ try:
83
+ chrom = fields[col_map['Chromosome']]
84
+ start = int(fields[col_map['Start_Position']])
85
+ end = int(fields[col_map['End_Position']])
86
+ ref = fields[col_map['Reference_Allele']]
87
+ alt1 = fields[col_map['Tumor_Seq_Allele1']]
88
+ alt2 = fields[col_map['Tumor_Seq_Allele2']]
89
+
90
+ # Skip invalid records
91
+ if not chrom or chrom == '.' or not ref or ref == '.':
92
+ skipped_records += 1
93
+ continue
94
+
95
+ # Determine ALT allele(s)
96
+ alts = []
97
+ if alt1 and alt1 != '.' and alt1 != ref:
98
+ alts.append(alt1)
99
+ if alt2 and alt2 != '.' and alt2 != ref and alt2 != alt1:
100
+ alts.append(alt2)
101
+
102
+ if not alts:
103
+ skipped_records += 1
104
+ continue
105
+
106
+ alt = alts[0] # Use first alt for deduplication
107
+
108
+ # Create key for deduplication
109
+ key = (chrom, start, ref, alt)
110
+
111
+ # Get TUMORTYPE for this record
112
+ tumortype = ''
113
+ if 'TUMORTYPE' in col_map:
114
+ tumortype = fields[col_map['TUMORTYPE']].strip()
115
+
116
+ if key not in records_dict:
117
+ # Initialize new record
118
+ records_dict[key] = {
119
+ 'chrom': chrom,
120
+ 'pos': start,
121
+ 'ref': ref,
122
+ 'alt': alt,
123
+ 'tumortype_counts': defaultdict(int),
124
+ 'FILTER': [],
125
+ 'judgement': set(),
126
+ 'oncotree_organtype': set(),
127
+ 'Variant_Classification': set(),
128
+ 'Variant_Type': set(),
129
+ 't_depth': [],
130
+ 't_ref_count': [],
131
+ 't_alt_count': [],
132
+ }
133
+
134
+ # Aggregate tumortype counts
135
+ if tumortype:
136
+ records_dict[key]['tumortype_counts'][tumortype] += 1
137
+
138
+ # Aggregate other fields (take first non-empty or collect unique)
139
+ for col in info_cols:
140
+ if col in col_map:
141
+ val = fields[col_map[col]]
142
+ if val and val != '.':
143
+ if col in ['FILTER']:
144
+ records_dict[key][col].append(val)
145
+ elif col in ['judgement', 'oncotree_organtype', 'Variant_Classification', 'Variant_Type']:
146
+ records_dict[key][col].add(val)
147
+ elif col in ['t_depth', 't_ref_count', 't_alt_count']:
148
+ try:
149
+ records_dict[key][col].append(int(val))
150
+ except ValueError:
151
+ pass
152
+
153
+ total_records += 1
154
+ if total_records % 500000 == 0:
155
+ print(f"Processed {total_records:,} records, {len(records_dict):,} unique positions...")
156
+
157
+ except (IndexError, ValueError) as e:
158
+ skipped_records += 1
159
+ continue
160
+
161
+ maf_handle.close()
162
+ print(f"\nParsing complete!")
163
+ print(f"Total input records: {total_records:,}")
164
+ print(f"Skipped records: {skipped_records:,}")
165
+ print(f"Unique positions: {len(records_dict):,}")
166
+
167
+ # Write VCF output
168
+ write_vcf(records_dict, vcf_file, col_map, info_cols)
169
+
170
+
171
+ def write_vcf(records_dict, vcf_file, col_map, info_cols):
172
+ """Write deduplicated records to VCF file."""
173
+
174
+ # Sort by chromosome and position
175
+ def sort_key(item):
176
+ chrom, pos, ref, alt = item[0]
177
+ # Handle chromosome names (1-22, X, Y, MT)
178
+ try:
179
+ chrom_num = int(chrom) if chrom not in ['X', 'Y', 'MT', 'M'] else (23 if chrom == 'X' else 24 if chrom == 'Y' else 25)
180
+ except ValueError:
181
+ chrom_num = 26
182
+ return (chrom_num, pos)
183
+
184
+ sorted_records = sorted(records_dict.items(), key=sort_key)
185
+
186
+ with open(vcf_file, 'w') as vcf_out:
187
+ # Build VCF header
188
+ vcf_header = build_vcf_header(info_cols)
189
+ vcf_out.write(vcf_header)
190
+
191
+ for key, data in sorted_records:
192
+ # Build TUMORTYPE summary string
193
+ tumortype_counts = data['tumortype_counts']
194
+ if tumortype_counts:
195
+ # Sort by count descending, then by name
196
+ sorted_types = sorted(tumortype_counts.items(), key=lambda x: (-x[1], x[0]))
197
+ tumortype_str = '|'.join([f"{t}:{c}" for t, c in sorted_types])
198
+ else:
199
+ tumortype_str = '.'
200
+
201
+ # Build INFO field
202
+ info_parts = [f"TUMORTYPE={tumortype_str}"]
203
+
204
+ # Add other fields
205
+ if data['FILTER']:
206
+ # Take the most common or first
207
+ info_parts.append(f"FILTER={data['FILTER'][0]}")
208
+ if data['judgement']:
209
+ info_parts.append(f"judgement={','.join(sorted(data['judgement']))}")
210
+ if data['oncotree_organtype']:
211
+ info_parts.append(f"oncotree_organtype={','.join(sorted(data['oncotree_organtype']))}")
212
+ if data['Variant_Classification']:
213
+ info_parts.append(f"Variant_Classification={','.join(sorted(data['Variant_Classification']))}")
214
+ if data['Variant_Type']:
215
+ info_parts.append(f"Variant_Type={','.join(sorted(data['Variant_Type']))}")
216
+
217
+ # Take median depth if available
218
+ if data['t_depth']:
219
+ median_depth = sorted(data['t_depth'])[len(data['t_depth']) // 2]
220
+ info_parts.append(f"t_depth={median_depth}")
221
+ if data['t_ref_count']:
222
+ median_ref = sorted(data['t_ref_count'])[len(data['t_ref_count']) // 2]
223
+ info_parts.append(f"t_ref_count={median_ref}")
224
+ if data['t_alt_count']:
225
+ median_alt = sorted(data['t_alt_count'])[len(data['t_alt_count']) // 2]
226
+ info_parts.append(f"t_alt_count={median_alt}")
227
+
228
+ info_str = ';'.join(info_parts)
229
+
230
+ # Build VCF record
231
+ vcf_record = f"{data['chrom']}\t{data['pos']}\t.\t{data['ref']}\t{data['alt']}\t.\tPASS\t{info_str}\n"
232
+ vcf_out.write(vcf_record)
233
+
234
+ print(f"VCF file written: {vcf_file}")
235
+
236
+
237
+ def build_vcf_header(info_cols):
238
+ """Build VCF header with appropriate metadata."""
239
+ header_lines = [
240
+ "##fileformat=VCFv4.2",
241
+ "##source=cancerhotspots_maf2vcf",
242
+ '##INFO=<ID=TUMORTYPE,Number=1,Type=String,Description="Tumor type counts: tumor_type:count|tumor_type:count">',
243
+ '##INFO=<ID=FILTER,Number=1,Type=String,Description="Filter status">',
244
+ '##INFO=<ID=judgement,Number=1,Type=String,Description="Hotspot judgement">',
245
+ '##INFO=<ID=oncotree_organtype,Number=1,Type=String,Description="Oncotree organ type">',
246
+ '##INFO=<ID=Variant_Classification,Number=1,Type=String,Description="Variant classification from MAF">',
247
+ '##INFO=<ID=Variant_Type,Number=1,Type=String,Description="Variant type (SNP, DEL, INS, etc.)">',
248
+ '##INFO=<ID=t_depth,Number=1,Type=Integer,Description="Tumor sequencing depth (median)">',
249
+ '##INFO=<ID=t_ref_count,Number=1,Type=Integer,Description="Tumor reference allele count (median)">',
250
+ '##INFO=<ID=t_alt_count,Number=1,Type=Integer,Description="Tumor alternate allele count (median)">',
251
+ "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO",
252
+ ]
253
+
254
+ return '\n'.join(header_lines) + '\n'
255
+
256
+
257
+ if __name__ == '__main__':
258
+ args = parse_args()
259
+ print(f"Converting {args.input_maf} to VCF format...")
260
+ print(f"Output: {args.output_vcf}")
261
+ maf_to_vcf(args.input_maf, args.output_vcf)