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