22
|
1 import matplotlib
|
|
2 matplotlib.use('Agg')
|
0
|
3 import matplotlib.pyplot as plt
|
|
4
|
|
5 from matplotlib import rcParams
|
|
6 from matplotlib import colors
|
|
7 from matplotlib import cm
|
|
8
|
19
|
9 from vhom import RegionRunner
|
|
10
|
0
|
11 from argparse import ArgumentParser
|
|
12 from matplotlib.backends.backend_pdf import PdfPages
|
|
13
|
|
14 import os
|
|
15
|
20
|
16 import sys
|
|
17
|
0
|
18 import colorsys
|
|
19
|
|
20
|
|
21
|
|
22
|
|
23 rcParams['figure.figsize'] = (6, 6)
|
|
24 rcParams['figure.dpi'] = 100
|
|
25 rcParams['axes.facecolor'] = 'white'
|
|
26 rcParams['font.size'] = 10
|
|
27 rcParams['patch.edgecolor'] = 'white'
|
|
28 rcParams['patch.linewidth']=0.5
|
|
29 rcParams['patch.facecolor'] = 'black'
|
|
30 rcParams['font.family'] = 'StixGeneral'
|
|
31
|
|
32
|
|
33 def color_variants(r,g,b):
|
|
34 h,l2,s= colorsys.rgb_to_hls(r,g,b)
|
|
35 l=[l2-0.4,l2-0.1,l2+0.2]
|
|
36 hexs=[]
|
|
37 for i in l:
|
|
38 hexs.append(colors.rgb2hex(colorsys.hls_to_rgb(h,i,s)))
|
|
39 return hexs
|
|
40
|
|
41 def rgb_color_variants(r,g,b):
|
|
42 h,l2,s= colorsys.rgb_to_hls(r,g,b)
|
|
43 l=[l2-0.4,l2-0.1,l2+0.2]
|
|
44 rgbs={}
|
|
45 rgbs["pathogen"]=colorsys.hls_to_rgb(h,l[0],s)
|
|
46 rgbs["ambiguous"]=colorsys.hls_to_rgb(h,l[1],s)
|
|
47 rgbs["human"]=colorsys.hls_to_rgb(h,l[2],s)
|
|
48 return rgbs
|
|
49
|
|
50
|
|
51
|
|
52
|
|
53 def remove_border(axes=None, top=False, right=False, left=True, bottom=True):
|
|
54 """
|
|
55 Minimize chartjunk by stripping out unnecesasry plot borders and axis ticks
|
|
56
|
|
57 The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn
|
|
58 """
|
|
59 ax = axes or plt.gca()
|
|
60 ax.spines['top'].set_visible(top)
|
|
61 ax.spines['right'].set_visible(right)
|
|
62 ax.spines['left'].set_visible(left)
|
|
63 ax.spines['bottom'].set_visible(bottom)
|
|
64
|
|
65 #turn off all ticks
|
|
66 ax.yaxis.set_ticks_position('none')
|
|
67 ax.xaxis.set_ticks_position('none')
|
|
68
|
|
69 #now re-enable visibles
|
|
70 if top:
|
|
71 ax.xaxis.tick_top()
|
|
72 if bottom:
|
|
73 ax.xaxis.tick_bottom()
|
|
74 if left:
|
|
75 ax.yaxis.tick_left()
|
|
76 if right:
|
|
77 ax.yaxis.tick_right()
|
|
78
|
|
79
|
|
80 def generateHTML(stat_dict,file,directory):
|
|
81 rval=["<html><head><title>Homologous groups and regions derived from hit files </title></head><body><p/>\n"]
|
|
82 rval.append("<a href='plot.pdf'>Download Plot</a>")
|
|
83 n_samples=0
|
|
84 for sample in stat_dict.iterkeys():
|
|
85 n_samples+=1
|
|
86 rval.append("<div id=%s_graph></div><p/>"%(sample))
|
|
87 rval.append("<script src='jquery-1.10.2.min.js'></script>")
|
|
88 rval.append("<script src='jqBarGraph.2.1.js'></script>")
|
|
89 rval.append('<script>')
|
|
90 i=0
|
|
91 for sample in stat_dict.iterkeys():
|
|
92 i+=1
|
|
93 rval.append("%s_array = new Array(" %sample)
|
|
94 for family in stat_dict[sample].iterkeys():
|
|
95 values=[]
|
|
96 for region,data in stat_dict[sample][family].iteritems():
|
|
97 values.append([int(data[0][1]),int(data[0][2]), data[0][0], data[0][3],int(data[0][4]),int(region)])
|
|
98 rval.append(str([values,family])+",")
|
|
99 rval[-1]=rval[-1][:-1]
|
|
100 rval.append(");")
|
|
101 rval.append("%s_files=%s;"%(sample,str(getFiles(directory))))
|
|
102 rval.append("$('#%s_graph').jqBarGraph({"%sample)
|
|
103 rval.append("sample: '%s',"%sample)
|
|
104 rval.append("data: %s_array,"%sample)
|
|
105 rval.append("files: %s_files,"%sample)
|
|
106 r,g,b,a=cm.hsv(1.*i/n_samples)
|
|
107 rval.append("colors: %s," %color_variants(r,g,b))
|
|
108 rval.append("legend: true,")
|
|
109 rval.append("tab: 'reads',")
|
|
110 rval.append("title: '<H3>Visualisation of Sample %s</H3>',"%sample)
|
|
111 rval.append("width: %d"%((len(stat_dict[sample])*50)+150))
|
|
112 rval.append("});")
|
|
113 # rval.append("jQuery.get('test.py', function(data) {")
|
|
114 # rval.append("alert(data)")
|
|
115 # rval.append("})")
|
|
116 rval.append("</script>")
|
|
117
|
|
118 rval.append( '</body></html>' )
|
|
119 with open(file,'w') as file:
|
|
120 file.write("\n".join( rval ))
|
|
121
|
|
122 def generatePyPlot(stat_dict,output_file):
|
|
123 pp = PdfPages(output_file)
|
|
124 fig = plt.figure()
|
|
125
|
|
126 n_samples=len(stat_dict)
|
|
127 dict={}
|
|
128 position={}
|
|
129 dict_label={}
|
|
130 for sample in stat_dict.iterkeys():
|
|
131 dict[sample]=[{},{}]
|
|
132 position[sample]={}
|
|
133 dict_label[sample]={}
|
|
134 j=0
|
|
135 for family in stat_dict[sample].iterkeys():
|
|
136
|
|
137 i=0
|
|
138 for region,values in stat_dict[sample][family].iteritems():
|
|
139
|
|
140 if i not in dict[sample][0]:
|
|
141 dict[sample][0][i]=[]
|
|
142 dict[sample][1][i]=[]
|
|
143 position[sample][i]=[]
|
|
144 dict_label[sample][i]=[]
|
|
145 dict[sample][0][i].append(int(values[0][1]))
|
|
146 dict[sample][1][i].append(int(values[0][2]))
|
|
147 position[sample][i].append(j)
|
|
148 dict_label[sample][i].append(values[0][0])
|
|
149 i+=1
|
|
150 j+=1
|
|
151
|
|
152 i=0
|
|
153 for sample in dict.iterkeys():
|
|
154 fig = plt.figure()
|
|
155 fig.subplots_adjust(bottom=0.25,hspace=0.5)
|
|
156 r,g,b,a=cm.hsv(1.*i/n_samples)
|
|
157 color_map=rgb_color_variants(r,g,b)
|
|
158 for sub in [0,1]:
|
|
159 plt.subplot(1,2,sub+1)
|
|
160 bottom={}
|
|
161 for level,values in dict[sample][sub].iteritems():
|
|
162 colors=[color_map[r] for r in dict_label[sample][level]]
|
|
163 if level==0:
|
|
164 print level, values, position[sample][level],bottom
|
|
165 plt.bar(position[sample][level],values,bottom=0, width=0.8 ,color=colors)
|
|
166 else:
|
|
167 lastvalues=[]
|
|
168 for oldpos in range(len(values)):
|
|
169 lastvalues.append(bottom[position[sample][level][oldpos]])
|
|
170 print level, values, position[sample][level], lastvalues
|
|
171 plt.bar(position[sample][level],values, width=0.8,bottom=lastvalues ,color=colors)
|
|
172 for pos in range(len(values)):
|
|
173 if position[sample][level][pos] not in bottom:
|
|
174 bottom[position[sample][level][pos]]=0
|
|
175 else:
|
|
176 bottom[position[sample][level][pos]]+=values[pos]
|
|
177 pos=[x+0.4 for x in range(len(stat_dict[sample]))]
|
|
178 plt.xticks(pos, stat_dict[sample].keys(), rotation='vertical')
|
|
179 if(sub==0):
|
|
180 plt.ylabel("Reads")
|
|
181 else:
|
|
182 plt.ylabel("Basepairs")
|
|
183 plt.xlabel("")
|
|
184 fig.subplots_adjust(bottom=0.25,wspace=0.5)
|
|
185 remove_border()
|
|
186 plt.suptitle(sample)
|
|
187 pp.savefig(fig)
|
|
188 i+=1
|
|
189 pp.close()
|
|
190
|
|
191
|
|
192
|
|
193 def parseStatFile(filename):
|
|
194
|
|
195 with open(filename,'r') as file:
|
|
196 values=[ map(str,line.split('\t')) for line in file ]
|
|
197
|
|
198 dict={}
|
|
199 for line in values[1:]:
|
|
200 if line[3] not in dict:
|
|
201 dict[line[3]]={}
|
|
202 dict[line[3]][line[1]]={}
|
|
203 dict[line[3]][line[1]][line[2]]=[[line[4],line[5],line[7],line[0],line[6]]]
|
|
204 else:
|
|
205 if line[1] not in dict[line[3]]:
|
|
206 dict[line[3]][line[1]]={}
|
|
207 dict[line[3]][line[1]][line[2]]=[[line[4],line[5],line[7],line[0],line[6]]]
|
|
208 else:
|
|
209 if line[2] not in dict[line[3]][line[1]]:
|
|
210 dict[line[3]][line[1]][line[2]]=[[line[4],line[5],line[7],line[0],line[6]]]
|
|
211 else:
|
|
212 dict[line[3]][line[1]][line[2]].append([line[4],line[5],line[7],line[0],line[6]])
|
|
213 # for key in dict.iterkeys():
|
|
214 # for family_key,values in dict[key].iteritems():
|
|
215 # for line in values:
|
|
216 # print key,family_key,line
|
|
217 return dict
|
|
218 def getFiles(directory):
|
|
219 rval={}
|
|
220 dlist = os.listdir(directory)
|
|
221 for dire in dlist:
|
|
222 if(os.path.isdir(os.path.join(directory,dire))):
|
|
223 rval[dire]={}
|
|
224 flist = os.listdir(os.path.join(directory,dire))
|
|
225 for file in flist:
|
|
226 split=file.split("_")
|
|
227 region=split[1]
|
|
228 if region not in rval[dire]:
|
|
229 rval[dire][region]=[file]
|
|
230 else:
|
|
231 rval[dire][region].append(file)
|
|
232
|
|
233 return rval
|
|
234
|
|
235
|
|
236
|
|
237 if __name__ == "__main__":
|
|
238
|
|
239
|
|
240 parser = ArgumentParser()
|
|
241
|
|
242 a = parser.add_argument
|
|
243 a("--html_file",dest="html_file")
|
|
244 a("--directory",dest="directory")
|
|
245 a("--stats",dest="stat_file")
|
|
246
|
|
247 (options,args)= parser.parse_known_args()
|
|
248
|
18
|
249 args.insert(0,"dummy")
|
|
250 try:
|
|
251 RegionRunner.run(argv=args)
|
21
|
252 except SystemExit:
|
|
253 stat_dict=parseStatFile(options.stat_file)
|
|
254 generatePyPlot(stat_dict,os.path.join(options.directory,"plot.pdf"))
|
|
255 generateHTML(stat_dict,options.html_file,options.directory)
|
0
|
256
|
|
257
|
|
258
|
|
259
|
|
260 |