comparison VDM_Mapping.py @ 6:d1273c7210da draft

Uploaded
author gregory-minevich
date Sat, 22 Jun 2013 18:17:26 -0400
parents
children
comparison
equal deleted inserted replaced
5:5e942106136c 6:d1273c7210da
1 #!/usr/bin/python
2
3 import re
4 import sys
5 import optparse
6 import csv
7 import re
8 import pprint
9 from decimal import *
10 from rpy import *
11
12 def main():
13 csv.field_size_limit(1000000000)
14
15 parser = optparse.OptionParser()
16 parser.add_option('-v', '--sample_vcf', dest = 'sample_vcf', action = 'store', type = 'string', default = None, help = "Sample VCF from GATK Unified Genotyper")
17 parser.add_option('-l', '--loess_span', dest = 'loess_span', action = 'store', type = 'float', default = .01, help = "Loess span")
18 parser.add_option('-d', '--d_yaxis', dest = 'd_yaxis', action = 'store', type = 'float', default = .7, help = "y-axis upper limit for dot plot")
19 parser.add_option('-y', '--h_yaxis', dest = 'h_yaxis', action = 'store', type = 'int', default = 5, help = "y-axis upper limit for histogram plot")
20 parser.add_option('-c', '--points_color', dest = 'points_color', action = 'store', type = 'string', default = "gray27", help = "Color for data points")
21 parser.add_option('-k', '--loess_color', dest = 'loess_color', action = 'store', type = 'string', default = "green2", help = "Color for loess regression line")
22 parser.add_option('-z', '--standardize', dest = 'standardize', default= 'true', help = "Standardize X-axis")
23 parser.add_option('-b', '--break_file', dest = 'break_file', action = 'store', type = 'string', default = 'C.elegans', help = "File defining the breaks per chromosome")
24 parser.add_option('-x', '--bin_size', dest = 'bin_size', action = 'store', type = 'int', default = 1000000, help = "Size of histogram bins, default is 1mb")
25 parser.add_option('-n', '--normalize_bins', dest = 'normalize_bins', default= 'true', help = "Normalize histograms")
26
27 parser.add_option('-o', '--output', dest = 'output', action = 'store', type = 'string', default = None, help = "Output file name")
28 parser.add_option('-s', '--location_plot_output', dest = 'location_plot_output', action = 'store', type = 'string', default = "SNP_Mapping_Plot.pdf", help = "Output file name of SNP plots by chromosomal location")
29
30 (options, args) = parser.parse_args()
31
32 vcf_info = parse_vcf(sample_vcf = options.sample_vcf)
33
34 output_vcf_info(output = options.output, vcf_info = vcf_info)
35
36 #output plot with all ratios
37 rounded_bin_size = int(round((float(options.bin_size) / 1000000), 1) * 1000000)
38
39 normalized_histogram_bins_per_mb = calculate_normalized_histogram_bins_per_xbase(vcf_info = vcf_info, xbase = rounded_bin_size, normalize_bins = options.normalize_bins)
40 normalized_histogram_bins_per_5kb = calculate_normalized_histogram_bins_per_xbase(vcf_info = vcf_info, xbase = (rounded_bin_size / 2), normalize_bins = options.normalize_bins)
41
42 break_dict = parse_breaks(break_file = options.break_file)
43
44 output_scatter_plots_by_location(location_plot_output = options.location_plot_output, vcf_info = vcf_info, loess_span=options.loess_span, d_yaxis=options.d_yaxis, h_yaxis=options.h_yaxis, points_color=options.points_color, loess_color=options.loess_color, standardize =options.standardize, normalized_hist_per_mb = normalized_histogram_bins_per_mb, normalized_hist_per_5kb = normalized_histogram_bins_per_5kb, breaks = break_dict, rounded_bin_size = rounded_bin_size)
45
46
47 def skip_headers(reader = None, i_file = None):
48 # count headers
49 comment = 0
50 while reader.next()[0].startswith('#'):
51 comment = comment + 1
52
53 # skip headers
54 i_file.seek(0)
55 for i in range(0, comment):
56 reader.next()
57
58 def parse_breaks(break_file = None):
59 if break_file == 'C.elegans':
60 break_dict = { 'I' : 16 , 'II' : 16, 'III' : 14, 'IV' : 18, 'V' : 21, 'X' : 18 }
61 return break_dict
62 elif break_file == 'Arabadopsis':
63 break_dict = { '1' : 31 , '2' : 20, '3' : 24, '4' : 19, '5' : 27 }
64 return break_dict
65 else:
66 i_file = open(break_file, 'rU')
67 break_dict = {}
68 reader = csv.reader(i_file, delimiter = '\t')
69 for row in reader:
70 chromosome = row[0].upper()
71 chromosome = re.sub("chr", "", chromosome, flags = re.IGNORECASE)
72 chromosome = re.sub("CHROMOSOME_", "", chromosome, flags = re.IGNORECASE)
73 break_count = row[1]
74 break_dict[chromosome] = int(break_count)
75 return break_dict
76
77
78 def location_comparer(location_1, location_2):
79 chr_loc_1 = location_1.split(':')[0]
80 pos_loc_1 = int(location_1.split(':')[1])
81
82 chr_loc_2 = location_2.split(':')[0]
83 pos_loc_2 = int(location_2.split(':')[1])
84
85 if chr_loc_1 == chr_loc_2:
86 if pos_loc_1 < pos_loc_2:
87 return -1
88 elif pos_loc_1 == pos_loc_1:
89 return 0
90 elif pos_loc_1 > pos_loc_2:
91 return 1
92 elif chr_loc_1 < chr_loc_2:
93 return -1
94 elif chr_loc_1 > chr_loc_2:
95 return 1
96
97 def output_vcf_info(output = None, vcf_info = None):
98 o_file = open(output, 'wb')
99 writer = csv.writer(o_file, delimiter = '\t')
100
101 writer.writerow(["#Chr\t", "Pos\t", "Alt Count\t", "Ref Count\t", "Read Depth\t", "Ratio\t"])
102
103 location_sorted_vcf_info_keys = sorted(vcf_info.keys(), cmp=location_comparer)
104
105 for location in location_sorted_vcf_info_keys:
106 alt_allele_count, ref_allele_count, read_depth, ratio = vcf_info[location]
107
108 location_info = location.split(':')
109 chromosome = location_info[0]
110 position = location_info[1]
111
112 writer.writerow([chromosome, position, alt_allele_count, ref_allele_count, read_depth, ratio])
113
114 o_file.close()
115
116 def output_scatter_plots_by_location(location_plot_output = None, vcf_info = None, loess_span="", d_yaxis="", h_yaxis="", points_color="", loess_color="", standardize=None, normalized_hist_per_mb = None, normalized_hist_per_5kb = None, breaks = None, rounded_bin_size = 1000000):
117 positions = {}
118 current_chr = ""
119 prev_chr = ""
120
121 x_label = "Location (Mb)"
122 filtered_label = ''
123
124 location_sorted_vcf_info_keys = sorted(vcf_info.keys(), cmp=location_comparer)
125
126 break_unit = Decimal(rounded_bin_size) / Decimal(1000000)
127 max_breaks = max(breaks.values())
128
129 try:
130 r.pdf(location_plot_output, 8, 8)
131
132 for location in location_sorted_vcf_info_keys:
133 current_chr = location.split(':')[0]
134 position = location.split(':')[1]
135
136 alt_allele_count, ref_allele_count, read_depth, ratio = vcf_info[location]
137
138 if prev_chr != current_chr:
139 if prev_chr != "":
140 hist_dict_mb = get_hist_dict_by_chr(normalized_hist_per_xbase = normalized_hist_per_mb, chr = prev_chr)
141 hist_dict_5kb = get_hist_dict_by_chr(normalized_hist_per_xbase = normalized_hist_per_5kb, chr = prev_chr)
142
143 plot_data(chr_dict = positions, hist_dict_mb = hist_dict_mb, hist_dict_5kb = hist_dict_5kb, chr = prev_chr + filtered_label, x_label = "Location (Mb)", divide_position = True, draw_secondary_grid_lines = True, loess_span=loess_span, d_yaxis=d_yaxis, h_yaxis=h_yaxis, points_color=points_color, loess_color=loess_color, breaks = breaks[prev_chr], standardize=standardize, max_breaks = max_breaks, break_unit = break_unit)
144
145 prev_chr = current_chr
146 positions = {}
147
148 positions[position] = ratio
149
150 hist_dict_mb = get_hist_dict_by_chr(normalized_hist_per_xbase = normalized_hist_per_mb, chr = current_chr)
151 hist_dict_5kb = get_hist_dict_by_chr(normalized_hist_per_xbase = normalized_hist_per_5kb, chr = current_chr)
152
153 plot_data(chr_dict = positions, hist_dict_mb = hist_dict_mb, hist_dict_5kb = hist_dict_5kb, chr = current_chr + filtered_label, x_label = "Location (Mb)", divide_position = True, draw_secondary_grid_lines = True, loess_span=loess_span, d_yaxis=d_yaxis, h_yaxis=h_yaxis, points_color=points_color, loess_color=loess_color, breaks = breaks[current_chr], standardize=standardize, max_breaks = max_breaks, break_unit = break_unit)
154
155 r.dev_off()
156
157 except Exception as inst:
158 print inst
159 print "There was an error creating the location plot pdf... Please try again"
160
161 def get_hist_dict_by_chr(normalized_hist_per_xbase = None, chr = ''):
162 hist_dict = {}
163
164 for location in normalized_hist_per_xbase:
165 chromosome = location.split(':')[0]
166 if chromosome == chr:
167 position = int(location.split(':')[1])
168 hist_dict[position] = normalized_hist_per_xbase[location]
169
170 max_location = max(hist_dict.keys(), key=int)
171 for i in range(1, max_location):
172 if i not in hist_dict:
173 hist_dict[i] = 0
174
175 return hist_dict
176
177 def plot_data(chr_dict = None, hist_dict_mb = None, hist_dict_5kb = None, chr = "", x_label = "", divide_position = False, draw_secondary_grid_lines = False, loess_span=None, d_yaxis=None, h_yaxis=None, points_color="", loess_color="", breaks = None, standardize= None, max_breaks = 1, break_unit = 1):
178 ratios = "c("
179 positions = "c("
180
181 for position in chr_dict:
182 ratio = chr_dict[position]
183 if divide_position:
184 position = float(position) / 1000000.0
185 positions = positions + str(position) + ", "
186 ratios = ratios + str(ratio) + ", "
187
188 if len(ratios) == 2:
189 ratios = ratios + ")"
190 else:
191 ratios = ratios[0:len(ratios) - 2] + ")"
192
193 if len(positions) == 2:
194 positions = positions + ")"
195 else:
196 positions = positions[0:len(positions) - 2] + ")"
197
198 r("x <- " + positions)
199 r("y <- " + ratios)
200
201 hist_mb_values = "c("
202 for position in sorted(hist_dict_mb):
203 hist_mb_values = hist_mb_values + str(hist_dict_mb[position]) + ", "
204
205 if len(hist_mb_values) == 2:
206 hist_mb_values = hist_mb_values + ")"
207 else:
208 hist_mb_values = hist_mb_values[0:len(hist_mb_values) - 2] + ")"
209
210 hist_5kb_values = "c("
211 for position in sorted(hist_dict_5kb):
212 hist_5kb_values = hist_5kb_values + str(hist_dict_5kb[position]) + ", "
213
214 if len(hist_5kb_values) == 2:
215 hist_5kb_values = hist_5kb_values + ")"
216 else:
217 hist_5kb_values = hist_5kb_values[0:len(hist_5kb_values) - 2] + ")"
218
219 r("xz <- " + hist_mb_values)
220 r("yz <- " + hist_5kb_values)
221
222
223 max_break_str = str(max_breaks)
224 break_unit_str = str(Decimal(break_unit))
225 half_break_unit_str = str(Decimal(break_unit) / Decimal(2))
226 break_penta_unit_str = str(Decimal(break_unit) * Decimal(5))
227
228 if (standardize=='true'):
229 r("plot(x, y, ,cex=0.60, xlim=c(0," + max_break_str + "), main='LG " + chr + " (Variant Discovery Mapping)', xlab= '" + x_label + "', ylim = c(0, %f " %d_yaxis + "), ylab='Ratios of variant reads/total reads (at variant positions)', pch=10, col='"+ points_color +"')")
230 r("lines(loess.smooth(x, y, span = %f "%loess_span + "), lwd=5, col='"+ loess_color +"')")
231 r("axis(1, at=seq(0, " + max_break_str + ", by=" + break_unit_str + "), labels=FALSE, tcl=-0.5)")
232 r("axis(1, at=seq(0, " + max_break_str + ", by=" + half_break_unit_str + "), labels=FALSE, tcl=-0.25)")
233 r("axis(2, at=seq(floor(min(y)), 1, by=0.1), labels=FALSE, tcl=-0.2)")
234 elif (standardize=='false'):
235 r("plot(x, y, cex=0.60, main='LG " + chr + " (Variant Discovery Mapping)', xlab= '" + x_label + "', ylim = c(0, %f " %d_yaxis + "), ylab='Ratios of variant reads/total reads (at variant positions)', pch=10, col='"+ points_color +"')")
236 r("lines(loess.smooth(x, y, span = %f "%loess_span + "), lwd=5, col='"+ loess_color +"')")
237 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by= " + break_unit_str + "), labels=FALSE, tcl=-0.5)")
238 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by= " + half_break_unit_str + "), labels=FALSE, tcl=-0.25)")
239 r("axis(2, at=seq(floor(min(y)), 1, by=0.1), labels=FALSE, tcl=-0.2)")
240
241 if draw_secondary_grid_lines:
242 r("abline(h = seq(floor(min(y)), 1, by=0.1), v = seq(floor(min(x)), length(x), by= 1), col='gray')")
243 else:
244 r("grid(lty = 1, col = 'gray')")
245
246 if (standardize=='true'):
247 r("barplot(xz, xlim=c(0, " + max_break_str + "), ylim = c(0, " + str(h_yaxis) + "), yaxp=c(0, " + str(h_yaxis) + ", 1), space = 0, col='darkgray', width = " + break_unit_str + ", xlab='Location (Mb)', ylab='Normalized frequency of pure parental alleles ', main='LG " + chr + " (Variant Discovery Mapping)')")
248 r("barplot(yz, space = 0, add=TRUE, width = " + half_break_unit_str + ", col='green2')")
249 r("axis(1, hadj = 1, at=seq(0, " + max_break_str + ", by= " + break_unit_str + "), labels=FALSE, tcl=-0.5)")
250 r("axis(1, at=seq(0, " + max_break_str + ", by= " + break_penta_unit_str + "), labels=TRUE, tcl=-0.5)")
251 r("axis(1, at=seq(0, " + max_break_str + ", by= " + half_break_unit_str + "), labels=FALSE, tcl=-0.25)")
252 elif (standardize=='false'):
253 r("barplot(xz, ylim = c(0, " + str(h_yaxis) + "), yaxp=c(0, " + str(h_yaxis) + ", 1), space = 0, col='darkgray', width = 1, xlab='Location (Mb)', ylab='Normalized frequency of pure parental alleles ', main='LG " + chr + " (Variant Discovery Mapping)')")
254 r("barplot(yz, space = 0, add=TRUE, width = 0.5, col='green2')")
255 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by= " + break_unit_str + "), labels=FALSE, tcl=-0.5)")
256 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by= " + break_penta_unit_str + "), labels=TRUE, tcl=-0.5)")
257 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by= " + half_break_unit_str + "), labels=FALSE, tcl=-0.25)")
258
259
260
261 def calculate_normalized_histogram_bins_per_xbase(vcf_info = None, xbase = 1000000, normalize_bins = None):
262 normalized_histogram_bins_per_xbase = {}
263
264 ref_snp_count_per_xbase = get_ref_snp_count_per_xbase(vcf_info = vcf_info, xbase = xbase)
265 mean_one_ratio_snp_count_per_chromosome = get_mean_one_ratio_snp_count_per_chromosome(vcf_info = vcf_info, xbase = xbase)
266 one_ratio_snp_count_per_xbase = get_one_ratio_snp_count_per_xbase(vcf_info = vcf_info, xbase = xbase)
267
268 for location in ref_snp_count_per_xbase:
269 chromosome = location.split(':')[0]
270 mean_one_ratio_snp_count = mean_one_ratio_snp_count_per_chromosome[chromosome]
271 ref_snp_count = ref_snp_count_per_xbase[location]
272
273 one_ratio_snp_count = 0
274 if location in one_ratio_snp_count_per_xbase:
275 one_ratio_snp_count = one_ratio_snp_count_per_xbase[location]
276
277 if normalize_bins == 'true':
278 if one_ratio_snp_count == 0:
279 normalized_histogram_bins_per_xbase[location] = 0
280 elif one_ratio_snp_count == ref_snp_count:
281 normalized_histogram_bins_per_xbase[location] = (Decimal(one_ratio_snp_count**2) * Decimal(mean_one_ratio_snp_count))
282 else:
283 normalized_histogram_bins_per_xbase[location] = (Decimal(one_ratio_snp_count**2) / (Decimal(ref_snp_count)-Decimal(one_ratio_snp_count))) * Decimal(mean_one_ratio_snp_count)
284 else:
285 normalized_histogram_bins_per_xbase[location] = one_ratio_snp_count
286
287 return normalized_histogram_bins_per_xbase
288
289
290 def get_ref_snp_count_per_xbase(vcf_info = None, xbase = 1000000):
291 ref_snps_per_xbase = {}
292
293 for location in vcf_info:
294 location_info = location.split(':')
295
296 chromosome = location_info[0].upper()
297 chromosome = re.sub("chr", "", chromosome, flags = re.IGNORECASE)
298 chromosome = re.sub("CHROMOSOME_", "", chromosome, flags = re.IGNORECASE)
299
300 position = location_info[1]
301 xbase_position = (int(position) / xbase) + 1
302
303 location = chromosome + ":" + str(xbase_position)
304 if location in ref_snps_per_xbase:
305 ref_snps_per_xbase[location] = ref_snps_per_xbase[location] + 1
306 else:
307 ref_snps_per_xbase[location] = 1
308
309 return ref_snps_per_xbase
310
311
312
313 def get_mean_one_ratio_snp_count_per_chromosome(vcf_info, xbase = 1000000):
314 sample_snp_count_per_xbase = {}
315
316 for location in vcf_info:
317 alt_allele_count, ref_allele_count, read_depth, ratio = vcf_info[location]
318
319 location_info = location.split(':')
320 chromosome = location_info[0]
321 position = location_info[1]
322 xbase_position = (int(position) / xbase) + 1
323 xbase_location = chromosome + ":" + str(xbase_position)
324
325 if ratio == 1:
326 if xbase_location in sample_snp_count_per_xbase:
327 sample_snp_count_per_xbase[xbase_location] = sample_snp_count_per_xbase[xbase_location] + 1
328 else:
329 sample_snp_count_per_xbase[xbase_location] = 1
330
331 elif ratio != 1 and xbase_location not in sample_snp_count_per_xbase:
332 sample_snp_count_per_xbase[xbase_location] = 0
333
334 mean_one_ratio_snp_count_per_chromosome = {}
335 for location in sample_snp_count_per_xbase:
336 chromosome = location.split(':')[0]
337 sample_count = sample_snp_count_per_xbase[location]
338 if chromosome in mean_one_ratio_snp_count_per_chromosome:
339 mean_one_ratio_snp_count_per_chromosome[chromosome].append(sample_count)
340 else:
341 mean_one_ratio_snp_count_per_chromosome[chromosome] = [sample_count]
342
343 for chromosome in mean_one_ratio_snp_count_per_chromosome:
344 summa = sum(mean_one_ratio_snp_count_per_chromosome[chromosome])
345 count = len(mean_one_ratio_snp_count_per_chromosome[chromosome])
346
347 mean_one_ratio_snp_count_per_chromosome[chromosome] = Decimal(summa) / Decimal(count)
348
349 return mean_one_ratio_snp_count_per_chromosome
350
351
352 def get_one_ratio_snp_count_per_xbase(vcf_info = None, xbase = 1000000):
353 one_ratio_snp_count_per_xbase = {}
354
355 for location in vcf_info:
356 alt_allele_count, ref_allele_count, read_depth, ratio = vcf_info[location]
357
358 location_info = location.split(':')
359 chromosome = location_info[0]
360 position = location_info[1]
361 xbase_position = (int(position) / xbase) + 1
362 xbase_location = chromosome + ":" + str(xbase_position)
363
364 if ratio == 1:
365 if xbase_location in one_ratio_snp_count_per_xbase:
366 one_ratio_snp_count_per_xbase[xbase_location] = one_ratio_snp_count_per_xbase[xbase_location] + 1
367 else:
368 one_ratio_snp_count_per_xbase[xbase_location] = 1
369
370 elif ratio != 1 and xbase_location not in one_ratio_snp_count_per_xbase:
371 one_ratio_snp_count_per_xbase[xbase_location] = 0
372
373 return one_ratio_snp_count_per_xbase
374
375
376 def parse_vcf(sample_vcf = None):
377 i_file = open(sample_vcf, 'rU')
378 reader = csv.reader(i_file, delimiter = '\t', quoting = csv.QUOTE_NONE)
379
380 skip_headers(reader = reader, i_file = i_file)
381 vcf_info = {}
382
383 for row in reader:
384 chromosome = row[0].upper()
385 chromosome = re.sub("chr", "", chromosome, flags = re.IGNORECASE)
386 chromosome = re.sub("CHROMOSOME_", "", chromosome, flags = re.IGNORECASE)
387
388 if chromosome != 'MTDNA':
389 position = row[1]
390 #ref_allele = row[2]
391 #read_depth = row[3]
392 #read_bases = row[4]
393
394 vcf_format_info = row[8].split(":")
395 vcf_allele_freq_data = row[9]
396
397 read_depth_data_index = vcf_format_info.index("DP")
398 read_depth = vcf_allele_freq_data.split(":")[read_depth_data_index]
399
400 ref_and_alt_counts_data_index = vcf_format_info.index("AD")
401 ref_and_alt_counts = vcf_allele_freq_data.split(":")[ref_and_alt_counts_data_index]
402 ref_allele_count = ref_and_alt_counts.split(",")[0]
403 alt_allele_count = ref_and_alt_counts.split(",")[1]
404
405 location = chromosome + ":" + position
406
407 if Decimal(read_depth!=0):
408 getcontext().prec = 6
409 ratio = Decimal(alt_allele_count) / Decimal(read_depth)
410
411 vcf_info[location] = (alt_allele_count, ref_allele_count, read_depth, ratio)
412
413 #debug line
414 #print chromosome, position, read_depth, ref_allele_count, alt_allele_count, ratio, id
415
416 i_file.close()
417
418 return vcf_info
419
420 def parse_read_bases(read_bases = None, alt_allele = None):
421 read_bases = re.sub('\$', '', read_bases)
422 read_bases = re.sub('\^[^\s]', '', read_bases)
423
424 ref_allele_matches = re.findall("\.|\,", read_bases)
425 ref_allele_count = len(ref_allele_matches)
426
427 alt_allele_matches = re.findall(alt_allele, read_bases, flags = re.IGNORECASE)
428 alt_allele_count = len(alt_allele_matches)
429
430 #debug line
431 #print read_bases, alt_allele, alt_allele_count, ref_allele_count
432
433 return ref_allele_count, alt_allele_count
434
435 if __name__ == "__main__":
436 main()