comparison SNP_Mapping.py @ 3:9cec8343aa5f

Uploaded
author gregory-minevich
date Tue, 20 Mar 2012 10:44:38 -0400
parents 30fa4d84e84c
children 7d6bccd5f88c
comparison
equal deleted inserted replaced
2:2f85060670a5 3:9cec8343aa5f
1 #!/usr/bin/python
2
3 import re
4 import sys
5 import optparse
6 import csv
7 import re
8 from decimal import *
9 from rpy import *
10
11 def main():
12 csv.field_size_limit(1000000000)
13
14 parser = optparse.OptionParser()
15 parser.add_option('-p', '--sample_pileup', dest = 'sample_pileup', action = 'store', type = 'string', default = None, help = "Sample pileup from mpileup")
16 parser.add_option('-v', '--haw_vcf', dest = 'haw_vcf', action = 'store', type = 'string', default = None, help = "vcf file of Hawaiian SNPs")
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 = 500, help = "y-axis upper limit for dot 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 = "red", help = "Color for loess regression line")
22 parser.add_option('-z', '--standardize', dest = 'standardize', default= 'false', help = "Standardize X-axis")
23
24 parser.add_option('-o', '--output', dest = 'output', action = 'store', type = 'string', default = None, help = "Output file name")
25 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")
26
27 #For plotting with map units on the X-axis instead of physical distance
28 #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")
29 (options, args) = parser.parse_args()
30
31 haw_snps = build_haw_snp_dictionary(haw_vcf = options.haw_vcf)
32 pileup_info = parse_pileup(sample_pileup = options.sample_pileup, haw_snps = haw_snps)
33 output_pileup_info(output = options.output, pileup_info = pileup_info)
34
35 #output plot with all ratios
36 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)
37
38 #For plotting with map units on the X-axis instead of physical distance)
39 #output_scatter_plots_by_mapping_units(mpu_plot_output = options.mpu_plot_output, pileup_info = pileup_info)
40
41 def skip_headers(reader = None, i_file = None):
42 # count headers
43 comment = 0
44 while reader.next()[0].startswith('#'):
45 comment = comment + 1
46
47 # skip headers
48 i_file.seek(0)
49 for i in range(0, comment):
50 reader.next()
51
52 def location_comparer(location_1, location_2):
53 chr_loc_1 = location_1.split(':')[0]
54 pos_loc_1 = int(location_1.split(':')[1])
55
56 chr_loc_2 = location_2.split(':')[0]
57 pos_loc_2 = int(location_2.split(':')[1])
58
59 if chr_loc_1 == chr_loc_2:
60 if pos_loc_1 < pos_loc_2:
61 return -1
62 elif pos_loc_1 == pos_loc_1:
63 return 0
64 elif pos_loc_1 > pos_loc_2:
65 return 1
66 elif chr_loc_1 < chr_loc_2:
67 return -1
68 elif chr_loc_1 > chr_loc_2:
69 return 1
70
71 def output_pileup_info(output = None, pileup_info = None):
72 o_file = open(output, 'wb')
73 writer = csv.writer(o_file, delimiter = '\t')
74
75 writer.writerow(["#Chr\t", "Pos\t", "ID\t", "Alt Count\t", "Ref Count\t", "Read Depth\t", "Ratio\t", "Mapping Unit"])
76
77 location_sorted_pileup_info_keys = sorted(pileup_info.keys(), cmp=location_comparer)
78
79 for location in location_sorted_pileup_info_keys:
80 alt_allele_count, ref_allele_count, read_depth, ratio, haw_snp_id, mapping_unit = pileup_info[location]
81
82 location_info = location.split(':')
83 chromosome = location_info[0]
84 position = location_info[1]
85
86 writer.writerow([chromosome, position, haw_snp_id, alt_allele_count, ref_allele_count, read_depth, ratio, mapping_unit])
87
88 o_file.close()
89
90 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):
91 i = {}
92 ii = {}
93 iii = {}
94 iv = {}
95 v = {}
96 x = {}
97
98 breaks = { 'I' : 16 , 'II' : 16, 'III' : 14, 'IV' : 18, 'V' : 21, 'X' : 18 }
99
100 for location in pileup_info:
101 chromosome = location.split(':')[0]
102 position = location.split(':')[1]
103
104 alt_allele_count, ref_allele_count, read_depth, ratio, haw_snp_id, mapping_unit = pileup_info[location]
105
106 if chromosome == "I":
107 i[position] = ratio
108 elif chromosome == "II":
109 ii[position] = ratio
110 elif chromosome == "III":
111 iii[position] = ratio
112 elif chromosome == "IV":
113 iv[position] = ratio
114 elif chromosome == "V":
115 v[position] = ratio
116 elif chromosome == "X":
117 x[position] = ratio
118
119 x_label = "Location (Mb)"
120 filtered_label = ''
121
122
123 try:
124 r.pdf(location_plot_output, 8, 8)
125 if i:
126 plot_data(chr_dict = i, chr = "I" + 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["I"], standardize=standardize)
127 if ii:
128 plot_data(chr_dict = ii, chr = "II" + 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["II"], standardize=standardize)
129 if iii:
130 plot_data(chr_dict = iii, chr = "III" + 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["III"], standardize=standardize)
131 if iv:
132 plot_data(chr_dict = iv, chr = "IV" + 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["IV"], standardize=standardize)
133 if v:
134 plot_data(chr_dict = v, chr = "V" + 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["V"], standardize=standardize)
135 if x:
136 plot_data(chr_dict = x, chr = "X" + 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["X"], standardize=standardize)
137
138 r.dev_off()
139 except Exception as inst:
140 print inst
141 print "There was an error creating the location plot pdf... Please try again"
142
143 def output_scatter_plots_by_mapping_units(mpu_plot_output = None, pileup_info = None):
144 i = {}
145 ii = {}
146 iii = {}
147 iv = {}
148 v = {}
149 x = {}
150
151 for location in pileup_info:
152 chromosome = location.split(':')[0]
153 position = location.split(':')[1]
154
155 alt_allele_count, ref_allele_count, read_depth, ratio, haw_snp_id, mapping_unit = pileup_info[location]
156
157 if chromosome == "I":
158 i[mapping_unit] = ratio
159 elif chromosome == "II":
160 ii[mapping_unit] = ratio
161 elif chromosome == "III":
162 iii[mapping_unit] = ratio
163 elif chromosome == "IV":
164 iv[mapping_unit] = ratio
165 elif chromosome == "V":
166 v[mapping_unit] = ratio
167 elif chromosome == "X":
168 x[mapping_unit] = ratio
169
170 x_label = "Map Units"
171
172 try:
173 r.pdf(mpu_plot_output, 8, 8)
174 plot_data(chr_dict = i, chr = "I", x_label = "Map Units")
175 plot_data(chr_dict = ii, chr = "II", x_label = "Map Units")
176 plot_data(chr_dict = iii, chr = "III", x_label = "Map Units")
177 plot_data(chr_dict = iv, chr = "IV", x_label = "Map Units")
178 plot_data(chr_dict = v, chr = "V", x_label = "Map Units")
179 plot_data(chr_dict = x, chr = "X", x_label = "Map Units")
180 r.dev_off()
181 except Exception as inst:
182 print inst
183 print "There was an error creating the map unit plot pdf... Please try again"
184
185
186 def plot_data(chr_dict = 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):
187 ratios = "c("
188 positions = "c("
189 z_ratios = "c("
190 z_positions = "c("
191
192 for position in chr_dict:
193 ratio = chr_dict[position]
194 if divide_position:
195 position = float(position) / 1000000.0
196 positions = positions + str(position) + ", "
197 ratios = ratios + str(ratio) + ", "
198 if ratio == 0:
199 if divide_position:
200 z_position = float(position) / 1000000.0
201 z_positions = z_positions + str(position) + ", "
202 z_ratios = z_ratios + str(ratio) + ", "
203
204
205 if len(ratios) == 2:
206 ratios = ratios + ")"
207 else:
208 ratios = ratios[0:len(ratios) - 2] + ")"
209
210 if len(z_ratios) == 2:
211 z_ratios = z_ratios + ")"
212 else:
213 z_ratios = z_ratios[0:len(z_ratios) - 2] + ")"
214
215
216 if len(positions) == 2:
217 positions = positions + ")"
218 else:
219 positions = positions[0:len(positions) - 2] + ")"
220
221 if len(z_positions) == 2:
222 z_positions = z_positions + ")"
223 else:
224 z_positions = z_positions[0:len(z_positions) - 2] + ")"
225
226 r("x <- " + positions)
227 r("y <- " + ratios)
228
229 r("xz <- " + z_positions)
230 r("yz <- " + z_ratios)
231
232 if (standardize=='true'):
233 r("plot(x, y, cex=0.60, xlim=c(0,21), main='LG " + chr + "', xlab= '" + x_label + "', ylim = c(0, %f " %d_yaxis + "), ylab='HA Ratio [Hawaiian Reads / Total Read Depth]', pch=18, col='"+ points_color +"')")
234 r("lines(loess.smooth(x, y, span = %f "%loess_span + "), lwd=5, col='"+ loess_color +"')")
235 r("axis(1, at=seq(0, 21, by=1), labels=FALSE, tcl=-0.5)")
236 r("axis(1, at=seq(0, 21, by=0.5), labels=FALSE, tcl=-0.25)")
237 r("axis(2, at=seq(floor(min(y)), 1, by=0.1), labels=FALSE, tcl=-0.2)")
238 elif (standardize=='false'):
239 r("plot(x, y, cex=0.60, main='LG " + chr + "', xlab= '" + x_label + "', ylim = c(0, %f " %d_yaxis + "), ylab='HA Ratio [Hawaiian Reads / Total Read Depth]', pch=18, col='"+ points_color +"')")
240 r("lines(loess.smooth(x, y, span = %f "%loess_span + "), lwd=5, col='"+ loess_color +"')")
241 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by=1), labels=FALSE, tcl=-0.5)")
242 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by=0.5), labels=FALSE, tcl=-0.25)")
243 r("axis(2, at=seq(floor(min(y)), 1, by=0.1), labels=FALSE, tcl=-0.2)")
244
245
246 if draw_secondary_grid_lines:
247 r("abline(h = seq(floor(min(y)), 1, by=0.1), v = seq(floor(min(x)), length(x), by= 1), col='gray')")
248 else:
249 r("grid(lty = 1, col = 'gray')")
250
251 if (standardize=='true'):
252 r("hist(xz, col='darkgray', xlim=c(0,21), xlab='Location (Mb)', ylab='Frequency SNP Positions Where HA Ratio=0 ', ylim=c(0, %f " %h_yaxis + "), breaks = seq(0, as.integer( ' " + str(breaks) + " '), by=1), main='LG " + chr + "')")
253 r("hist(xz, add=TRUE, col=rgb(1, 0, 0, 1), xlim=c(0,21), xlab='Location (Mb)', ylab='Frequency SNP Positions Where HA Ratio=0 ', ylim=c(0, %f " %h_yaxis + "), breaks = seq(0, as.integer( ' " + str(breaks) + " '), by=.5), main='Chr " + chr + "')")
254 r("axis(1, at=seq(0, 21, by=1), labels=FALSE, tcl=-0.5)")
255 r("axis(1, at=seq(0, 21, by=0.5), labels=FALSE, tcl=-0.25)")
256 elif (standardize=='false'):
257 r("hist(xz, col='darkgray', xlab='Location (Mb)', ylab='Frequency SNP Positions Where HA Ratio=0 ', ylim=c(0, %f " %h_yaxis + "), breaks = seq(0, as.integer( ' " + str(breaks) + " '), by=1), main='LG " + chr + "')")
258 r("hist(xz, add=TRUE, col=rgb(1, 0, 0, 1), xlab='Location (Mb)', ylab='Frequency SNP Positions Where HA Ratio=0 ', ylim=c(0, %f " %h_yaxis + "), breaks = seq(0, as.integer( ' " + str(breaks) + " '), by=.5), main='Chr " + chr + "')")
259 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by=1), labels=FALSE, tcl=-0.5)")
260 r("axis(1, at=seq(0, as.integer( ' " + str(breaks) + " '), by=0.5), labels=FALSE, tcl=-0.25)")
261
262
263 def build_haw_snp_dictionary(haw_vcf = None):
264 haw_snps = {}
265
266 i_file = open(haw_vcf, 'rU')
267 reader = csv.reader(i_file, delimiter = '\t')
268
269 skip_headers(reader = reader, i_file = i_file)
270
271 for row in reader:
272 #print row
273 chromosome = row[0].upper()
274 chromosome = re.sub("chr", "", chromosome, flags = re.IGNORECASE)
275 chromosome = re.sub("CHROMOSOME_", "", chromosome, flags = re.IGNORECASE)
276
277 position = row[1]
278 haw_snp_id = row[2]
279 ref_allele = row[3]
280 alt_allele = row[4]
281 info = row[7]
282
283 mapping_unit = info.replace("MPU=", "")
284
285 location = chromosome + ":" + position
286 haw_snps[location] = (alt_allele, haw_snp_id, mapping_unit)
287
288 i_file.close()
289
290 return haw_snps
291
292 def parse_pileup(sample_pileup = None, haw_snps = None):
293 i_file = open(sample_pileup, 'rU')
294 reader = csv.reader(i_file, delimiter = '\t', quoting = csv.QUOTE_NONE)
295
296 pileup_info = {}
297
298 for row in reader:
299 chromosome = row[0].upper()
300 chromosome = re.sub("chr", "", chromosome, flags = re.IGNORECASE)
301 chromosome = re.sub("CHROMOSOME_", "", chromosome, flags = re.IGNORECASE)
302
303 position = row[1]
304 ref_allele = row[2]
305 read_depth = row[3]
306 read_bases = row[4]
307
308 location = chromosome + ":" + position
309 if location in haw_snps:
310 alt_allele, haw_snp_id, mapping_unit = haw_snps[location]
311 ref_allele_count, alt_allele_count = parse_read_bases(read_bases = read_bases, alt_allele = alt_allele)
312
313 getcontext().prec = 6
314 ratio = Decimal(alt_allele_count) / Decimal(read_depth)
315
316 pileup_info[location] = (alt_allele_count, ref_allele_count, read_depth, ratio, haw_snp_id, mapping_unit)
317
318 #debug line
319 #print chromosome, position, read_depth, ref_allele_count, alt_allele_count, ratio, id
320
321 i_file.close()
322
323 return pileup_info
324
325 def parse_read_bases(read_bases = None, alt_allele = None):
326 read_bases = re.sub('\$', '', read_bases)
327 read_bases = re.sub('\^[^\s]', '', read_bases)
328
329 ref_allele_matches = re.findall("\.|\,", read_bases)
330 ref_allele_count = len(ref_allele_matches)
331
332 alt_allele_matches = re.findall(alt_allele, read_bases, flags = re.IGNORECASE)
333 alt_allele_count = len(alt_allele_matches)
334
335 #debug line
336 #print read_bases, alt_allele, alt_allele_count, ref_allele_count
337
338 return ref_allele_count, alt_allele_count
339
340 if __name__ == "__main__":
341 main()