0
|
1 import matplotlib
|
|
2 matplotlib.use('Agg')
|
|
3 import matplotlib.pyplot as plt
|
|
4
|
|
5 from matplotlib import rcParams
|
|
6 from matplotlib import colors
|
|
7 from matplotlib import cm
|
|
8
|
|
9 from matplotlib.patches import Rectangle
|
|
10
|
|
11 from vhom import RegionRunner
|
|
12
|
|
13 from argparse import ArgumentParser
|
|
14 from matplotlib.backends.backend_pdf import PdfPages
|
|
15
|
|
16 import os
|
|
17 import shutil
|
|
18
|
|
19 import sys
|
|
20
|
|
21 import colorsys
|
|
22
|
43
|
23 from numpy import arange
|
|
24
|
|
25 import copy
|
|
26
|
0
|
27
|
|
28
|
|
29
|
|
30 rcParams['figure.figsize'] = (6, 6)
|
|
31 rcParams['figure.dpi'] = 100
|
|
32 rcParams['axes.facecolor'] = 'white'
|
|
33 rcParams['font.size'] = 10
|
|
34 rcParams['patch.edgecolor'] = 'white'
|
|
35 rcParams['patch.linewidth']=0.5
|
|
36 rcParams['patch.facecolor'] = 'black'
|
17
|
37 rcParams['font.family'] = 'StixGeneral'
|
0
|
38
|
43
|
39
|
|
40 def rgb_color_variants(stat_dict):
|
|
41
|
|
42 n_samples=0
|
|
43 sample_names=[]
|
|
44
|
|
45 for fam,obj in stat_dict.iteritems():
|
|
46 if len(obj.samples)>n_samples:
|
|
47 n_samples=len(obj.samples)
|
|
48 for sample in obj.samples.iterkeys():
|
|
49 if sample not in sample_names:
|
|
50 sample_names.append(sample)
|
0
|
51
|
|
52
|
43
|
53 assert n_samples == len(sample_names) #iterate over samples -> color_map
|
0
|
54 rgbs={}
|
43
|
55 i=1
|
|
56 for sample in sample_names:
|
|
57 rgbs[sample]={}
|
|
58 h=1.*(i/n_samples)
|
|
59 h=float(h)/2.
|
|
60 l=[0.1,0.4,0.7]
|
|
61 rgbs[sample]["pathogen"]=colorsys.hls_to_rgb(h,l[0],1.0)
|
|
62 rgbs[sample]["ambiguous"]=colorsys.hls_to_rgb(h,l[1],1.0)
|
|
63 rgbs[sample]["human"]=colorsys.hls_to_rgb(h,l[2],1.0)
|
|
64
|
|
65 i+=1
|
0
|
66 return rgbs
|
43
|
67 def convert_color_map(color_map):
|
|
68 deep = copy.deepcopy(color_map)
|
|
69 for sample in deep:
|
|
70 for state in deep[sample]:
|
|
71 deep[sample][state] = colors.rgb2hex(deep[sample][state])
|
|
72 return deep
|
0
|
73
|
43
|
74 def means(start,stop):
|
|
75 list = arange(start,stop)
|
|
76 return (float(sum(list))/float(len(list)))
|
0
|
77
|
|
78
|
|
79 def remove_border(axes=None, top=False, right=False, left=True, bottom=True):
|
|
80 """
|
|
81 Minimize chartjunk by stripping out unnecesasry plot borders and axis ticks
|
|
82
|
|
83 The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn
|
|
84 """
|
|
85 ax = axes or plt.gca()
|
|
86 ax.spines['top'].set_visible(top)
|
|
87 ax.spines['right'].set_visible(right)
|
|
88 ax.spines['left'].set_visible(left)
|
|
89 ax.spines['bottom'].set_visible(bottom)
|
|
90
|
|
91 #turn off all ticks
|
|
92 ax.yaxis.set_ticks_position('none')
|
|
93 ax.xaxis.set_ticks_position('none')
|
|
94
|
|
95 #now re-enable visibles
|
|
96 if top:
|
|
97 ax.xaxis.tick_top()
|
|
98 if bottom:
|
|
99 ax.xaxis.tick_bottom()
|
|
100 if left:
|
|
101 ax.yaxis.tick_left()
|
|
102 if right:
|
|
103 ax.yaxis.tick_right()
|
|
104
|
|
105
|
|
106 def generateHTML(stat_dict,file,directory):
|
|
107 rval=["<html><head><title>Homologous groups and regions derived from hit files </title></head><body><p/>\n"]
|
43
|
108 #rval.append('<link rel="stylesheet" type="text/css" href="/static/style/base.css">')
|
0
|
109 rval.append("<a href='plot.pdf'>Download Plot</a>")
|
43
|
110 rval.append("<div id='graph' class='graph'></div>")
|
0
|
111 curr_dir = os.path.dirname(os.path.realpath(__file__))
|
|
112 shutil.copy(os.path.join(curr_dir,"jquery-1.10.2.min.js"),directory)
|
13
|
113 shutil.copy(os.path.join(curr_dir,"jqBarGraph.2.1.js"),directory)
|
0
|
114 rval.append("<script type='text/javascript' src='jquery-1.10.2.min.js'></script>")
|
13
|
115 rval.append("<script type='text/javascript' src='jqBarGraph.2.1.js'></script>")
|
43
|
116 rval.append('<script>')
|
|
117 rval.append("$('#graph').jqBarGraph({")
|
|
118 rval.append("data: %s,"%stat_dict)
|
|
119
|
|
120 color_map=convert_color_map(rgb_color_variants(stat_dict))
|
|
121
|
|
122 rval.append("colors: %s," %color_map)
|
|
123 rval.append("legend: true,")
|
|
124 rval.append("tab: 'reads',")
|
|
125 rval.append("title: '<H3>Visualisation of Data</H3>',")
|
|
126 rval.append("width: %d"%((len(stat_dict)*50)+150))
|
|
127 rval.append("});")
|
13
|
128
|
0
|
129 rval.append("</script>")
|
|
130
|
|
131 rval.append( '</body></html>' )
|
|
132 with open(file,'w') as file:
|
|
133 file.write("\n".join( rval ))
|
|
134
|
|
135 def customeLegend(color_map):
|
|
136 legend_map=[[],[]]
|
43
|
137 for sample in color_map:
|
|
138 legend_map[0].append(Rectangle((0,0),0,0,visible=False))
|
|
139 legend_map[1].append(sample)
|
|
140 for label in color_map[sample]:
|
|
141 box=Rectangle((0,0),1,1,color=color_map[sample][label],fill=True)
|
|
142 legend_map[0].append(box)
|
|
143 legend_map[1].append(label)
|
|
144 plt.figlegend(legend_map[0],legend_map[1],loc=9,ncol=len(color_map),prop={'size':8})
|
0
|
145
|
|
146
|
|
147
|
|
148
|
|
149 def generatePyPlot(stat_dict,output_file):
|
|
150 pp = PdfPages(output_file)
|
43
|
151
|
|
152 color_map=rgb_color_variants(stat_dict)
|
|
153 n_samples=len(color_map)
|
|
154 for plot in ["reads","bp"]:
|
|
155 fig=plt.figure()
|
|
156 i=0
|
|
157 for f,fam in stat_dict.iteritems():
|
|
158 j=0
|
|
159 for s,sample in fam.samples.iteritems():
|
|
160 values = []
|
|
161 color = []
|
|
162 for r,region in sample.regions.iteritems():
|
|
163 values.append(int(getattr(region,plot)))
|
|
164 color.append(color_map[s][region.state])
|
|
165 if(len(values)>1):
|
|
166 b = values[:-1]
|
|
167 b.insert(0,0);
|
|
168 for u in range(1,len(b)):
|
|
169 b[u]+=b[u-1]
|
|
170 plt.bar([i+j]*len(values),values,bottom=b,width=0.8,color=color)
|
|
171 else:
|
|
172 plt.bar([i+j]*len(values),values,width=0.8,color=color)
|
0
|
173
|
43
|
174 j+=1
|
|
175 i+= 1+n_samples
|
|
176 pos=[means(x,x+n_samples)+0.4 for x in arange(0,i+n_samples,1+n_samples)]
|
|
177 plt.xticks(pos, stat_dict.keys(), rotation='vertical')
|
|
178 if(plot=="reads"):
|
0
|
179 plt.ylabel("Cumulative reads assigned to family")
|
43
|
180 if(plot=="bp"):
|
0
|
181 plt.ylabel("Cumulative basepairs assigned to family")
|
43
|
182 plt.xlabel("")
|
|
183 fig.subplots_adjust(bottom=0.25,wspace=0.5,top=0.8)
|
|
184 remove_border()
|
0
|
185
|
|
186 customeLegend(color_map)
|
|
187 pp.savefig(fig)
|
|
188 pp.close()
|
|
189
|
|
190
|
|
191
|
43
|
192 def parseStatFile(filename, directory):
|
0
|
193
|
|
194 with open(filename,'r') as file:
|
|
195 values=[ map(str,line.split('\t')) for line in file ]
|
|
196
|
43
|
197 family_dict={}
|
0
|
198 for line in values[1:]:
|
43
|
199 fam_type,fam,region,sample,state,reads,length,bp,coverage=line
|
|
200 if fam not in family_dict:
|
|
201 family= Family(fam,fam_type,directory=directory)
|
|
202 family_dict[fam]=family
|
|
203 family_dict[fam].add(sample,region,state,reads,bp,length)
|
|
204
|
|
205 return family_dict
|
|
206
|
|
207 class Family:
|
|
208
|
|
209 def __init__(self,name,typ,directory=None,samples=None):
|
|
210 self.name=name
|
|
211 if samples!=None:
|
|
212 self.samples=samples
|
|
213 else:
|
|
214 self.samples={}
|
|
215 self.directory=directory
|
|
216 self.typ=typ
|
|
217 if self.directory:
|
|
218 self.files=self.__getFiles(directory)
|
|
219 else:
|
|
220 self.files=None
|
|
221
|
|
222 def add(self,sample,region,state,reads,bp,length):
|
|
223 if sample not in self.samples:
|
|
224 s = Sample(sample)
|
|
225 self.samples[sample]=s
|
|
226
|
|
227 return self.samples[sample].add(region,state,reads,bp,self.files[region],length)
|
0
|
228
|
|
229
|
43
|
230 def __getFiles(self,directory):
|
|
231 dlist = os.listdir(os.path.join(directory,self.typ+"_"+self.name))
|
|
232 dict={}
|
|
233 for file in dlist:
|
|
234 try:
|
|
235 wc,region,suf = file.split("_")
|
|
236 except ValueError:
|
|
237 continue
|
|
238 if region not in dict:
|
|
239 dict[region]={}
|
|
240 dict[region][suf]=file #bit redundant?! just save TRUE or FALSE?
|
|
241 return dict
|
|
242
|
|
243 def __str__(self):
|
|
244 return "{'type':'%s', 'samples':%s}"%(self.typ,str(self.samples))
|
|
245
|
|
246 def __repr__(self):
|
|
247 return "{'type':'%s', 'samples':%s}"%(self.typ,str(self.samples))
|
|
248
|
|
249 class Sample:
|
|
250
|
|
251 def __init__(self,name,regions=None):
|
|
252 self.name=name
|
|
253 if regions!=None:
|
|
254 self.regions=regions
|
|
255 else:
|
|
256 self.regions={}
|
|
257 def add(self,region,state,reads,bp,files,length):
|
|
258 if region not in self.regions:
|
|
259 r = Region(region,state,reads,bp,files,length)
|
|
260 self.regions[region]=r
|
|
261 return True
|
|
262 else:
|
|
263 return False
|
|
264
|
|
265 def __str__(self):
|
|
266 return str(self.regions)
|
|
267
|
|
268 def __repr__(self):
|
|
269 return str(self.regions)
|
|
270
|
|
271
|
|
272 class Region:
|
|
273
|
|
274 def __init__(self,id,state,reads,bp,files,length):
|
|
275 self.id=id
|
|
276 self.state=state
|
|
277 self.reads=reads
|
|
278 self.bp=bp
|
|
279 self.files=files
|
|
280 self.length=length
|
|
281
|
|
282 def __str__(self):
|
|
283 return "{'state':'%s', 'reads':%s, 'bp':%s, 'files':%s, 'length':%s}" %(self.state,self.reads,self.bp,self.files,self.length)
|
|
284
|
|
285 def __repr__(self):
|
|
286 return "{'state':'%s', 'reads':%s, 'bp':%s, 'files':%s, 'length':%s}" %(self.state,self.reads,self.bp,self.files,self.length)
|
|
287
|
0
|
288
|
|
289 if __name__ == "__main__":
|
|
290
|
|
291
|
|
292 parser = ArgumentParser()
|
|
293
|
|
294 a = parser.add_argument
|
|
295 a("--html_file",dest="html_file")
|
|
296 a("--directory",dest="directory")
|
|
297 a("--stats",dest="stat_file")
|
|
298
|
|
299 (options,args)= parser.parse_known_args()
|
|
300
|
|
301 args.insert(0,"dummy")
|
|
302 try:
|
43
|
303 sys.exit(1)#RegionRunner.run(argv=args)
|
0
|
304 except SystemExit:
|
43
|
305 stat_dict=parseStatFile(options.stat_file,options.directory)
|
|
306
|
0
|
307 generatePyPlot(stat_dict,os.path.join(options.directory,"plot.pdf"))
|
|
308 generateHTML(stat_dict,options.html_file,options.directory)
|
|
309
|
|
310
|
|
311
|
|
312
|
|
313 |