comparison home/ubuntu/lefse_to_export/plot_res.py @ 1:db64b6287cd6 draft

Modified datatypes
author george-weingart
date Wed, 20 Aug 2014 16:56:51 -0400
parents
children
comparison
equal deleted inserted replaced
0:e7cd19afda2e 1:db64b6287cd6
1 #!/usr/bin/env python
2
3 import os,sys
4 import matplotlib
5 matplotlib.use('Agg')
6 from pylab import *
7
8 from lefse import *
9 import argparse
10
11 colors = ['r','g','b','m','c','y','k','w']
12
13 def read_params(args):
14 parser = argparse.ArgumentParser(description='Plot results')
15 parser.add_argument('input_file', metavar='INPUT_FILE', type=str, help="tab delimited input file")
16 parser.add_argument('output_file', metavar='OUTPUT_FILE', type=str, help="the file for the output image")
17 parser.add_argument('--feature_font_size', dest="feature_font_size", type=int, default=7, help="the file for the output image")
18 parser.add_argument('--format', dest="format", choices=["png","svg","pdf"], default='png', type=str, help="the format for the output file")
19 parser.add_argument('--dpi',dest="dpi", type=int, default=72)
20 parser.add_argument('--title',dest="title", type=str, default="")
21 parser.add_argument('--title_font_size',dest="title_font_size", type=str, default="12")
22 parser.add_argument('--class_legend_font_size',dest="class_legend_font_size", type=str, default="10")
23 parser.add_argument('--width',dest="width", type=float, default=7.0 )
24 parser.add_argument('--height',dest="height", type=float, default=4.0, help="only for vertical histograms")
25 parser.add_argument('--left_space',dest="ls", type=float, default=0.2 )
26 parser.add_argument('--right_space',dest="rs", type=float, default=0.1 )
27 parser.add_argument('--orientation',dest="orientation", type=str, choices=["h","v"], default="h" )
28 parser.add_argument('--autoscale',dest="autoscale", type=int, choices=[0,1], default=1 )
29 parser.add_argument('--background_color',dest="back_color", type=str, choices=["k","w"], default="w", help="set the color of the background")
30 parser.add_argument('--subclades', dest="n_scl", type=int, default=1, help="number of label levels to be dislayed (starting from the leaves, -1 means all the levels, 1 is default )")
31 parser.add_argument('--max_feature_len', dest="max_feature_len", type=int, default=60, help="Maximum length of feature strings (def 60)")
32 parser.add_argument('--all_feats', dest="all_feats", type=str, default="")
33 args = parser.parse_args()
34 return vars(args)
35
36 def read_data(input_file,output_file):
37 with open(input_file, 'r') as inp:
38 rows = [line.strip().split()[:-1] for line in inp.readlines() if len(line.strip().split())>3]
39 classes = list(set([v[2] for v in rows if len(v)>2]))
40 if len(classes) < 1:
41 print "No differentially abundant features found in "+input_file
42 os.system("touch "+output_file)
43 sys.exit()
44 data = {}
45 data['rows'] = rows
46 data['cls'] = classes
47 return data
48
49 def plot_histo_hor(path,params,data,bcl):
50 cls2 = []
51 if params['all_feats'] != "":
52 cls2 = sorted(params['all_feats'].split(":"))
53 cls = sorted(data['cls'])
54 if bcl: data['rows'].sort(key=lambda ab: fabs(float(ab[3]))*(cls.index(ab[2])*2-1))
55 else:
56 mmax = max([fabs(float(a)) for a in zip(*data['rows'])[3]])
57 data['rows'].sort(key=lambda ab: fabs(float(ab[3]))/mmax+(cls.index(ab[2])+1))
58 pos = arange(len(data['rows']))
59 head = 0.75
60 tail = 0.5
61 ht = head + tail
62 ints = max(len(pos)*0.2,1.5)
63 fig = plt.figure(figsize=(params['width'], ints + ht), edgecolor=params['back_color'],facecolor=params['back_color'])
64 ax = fig.add_subplot(111,frame_on=False,axis_bgcolor=params['back_color'])
65 ls, rs = params['ls'], 1.0-params['rs']
66 plt.subplots_adjust(left=ls,right=rs,top=1-head*(1.0-ints/(ints+ht)), bottom=tail*(1.0-ints/(ints+ht)))
67
68 fig.canvas.set_window_title('LDA results')
69
70 l_align = {'horizontalalignment':'left', 'verticalalignment':'baseline'}
71 r_align = {'horizontalalignment':'right', 'verticalalignment':'baseline'}
72 added = []
73 m = 1 if data['rows'][0][2] == cls[0] else -1
74 for i,v in enumerate(data['rows']):
75 indcl = cls.index(v[2])
76 lab = str(v[2]) if str(v[2]) not in added else ""
77 added.append(str(v[2]))
78 col = colors[indcl%len(colors)]
79 if len(cls2) > 0:
80 col = colors[cls2.index(v[2])%len(colors)]
81 vv = fabs(float(v[3])) * (m*(indcl*2-1)) if bcl else fabs(float(v[3]))
82 ax.barh(pos[i],vv, align='center', color=col, label=lab, height=0.8, edgecolor=params['fore_color'])
83 mv = max([abs(float(v[3])) for v in data['rows']])
84 for i,r in enumerate(data['rows']):
85 indcl = cls.index(data['rows'][i][2])
86 if params['n_scl'] < 0: rr = r[0]
87 else: rr = r[0].split(".")[-min(r[0].count("."),params['n_scl'])]
88 if len(rr) > params['max_feature_len']: rr = rr[:params['max_feature_len']/2-2]+" [..]"+rr[-params['max_feature_len']/2+2:]
89 if m*(indcl*2-1) < 0 and bcl: ax.text(mv/40.0,float(i)-0.3,rr, l_align, size=params['feature_font_size'],color=params['fore_color'])
90 else: ax.text(-mv/40.0,float(i)-0.3,rr, r_align, size=params['feature_font_size'],color=params['fore_color'])
91 ax.set_title(params['title'],size=params['title_font_size'],y=1.0+head*(1.0-ints/(ints+ht))*0.8,color=params['fore_color'])
92
93 ax.set_yticks([])
94 ax.set_xlabel("LDA SCORE (log 10)")
95 ax.xaxis.grid(True)
96 xlim = ax.get_xlim()
97 if params['autoscale']:
98 ran = arange(0.0001,round(round((abs(xlim[0])+abs(xlim[1]))/10,4)*100,0)/100)
99 if len(ran) > 1 and len(ran) < 100:
100 ax.set_xticks(arange(xlim[0],xlim[1]+0.0001,min(xlim[1]+0.0001,round(round((abs(xlim[0])+abs(xlim[1]))/10,4)*100,0)/100)))
101 ax.set_ylim((pos[0]-1,pos[-1]+1))
102 leg = ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=5, borderaxespad=0., frameon=False,prop={'size':params['class_legend_font_size']})
103
104 def get_col_attr(x):
105 return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor')
106 for o in leg.findobj(get_col_attr):
107 o.set_color(params['fore_color'])
108 for o in ax.findobj(get_col_attr):
109 o.set_color(params['fore_color'])
110
111
112 plt.savefig(path,format=params['format'],facecolor=params['back_color'],edgecolor=params['fore_color'],dpi=params['dpi'])
113 plt.close()
114
115 def plot_histo_ver(path,params,data):
116 cls = data['cls']
117 mmax = max([fabs(float(a)) for a in zip(*data['rows'])[1]])
118 data['rows'].sort(key=lambda ab: fabs(float(ab[3]))/mmax+(cls.index(ab[2])+1))
119 pos = arange(len(data['rows']))
120 if params['n_scl'] < 0: nam = [d[0] for d in data['rows']]
121 else: nam = [d[0].split(".")[-min(d[0].count("."),params['n_scl'])] for d in data['rows']]
122 fig = plt.figure(edgecolor=params['back_color'],facecolor=params['back_color'],figsize=(params['width'], params['height']))
123 ax = fig.add_subplot(111,axis_bgcolor=params['back_color'])
124 plt.subplots_adjust(top=0.9, left=params['ls'], right=params['rs'], bottom=0.3)
125 fig.canvas.set_window_title('LDA results')
126 l_align = {'horizontalalignment':'left', 'verticalalignment':'baseline'}
127 r_align = {'horizontalalignment':'right', 'verticalalignment':'baseline'}
128 added = []
129 for i,v in enumerate(data['rows']):
130 indcl = data['cls'].index(v[2])
131 lab = str(v[2]) if str(v[2]) not in added else ""
132 added.append(str(v[2]))
133 col = colors[indcl%len(colors)]
134 vv = fabs(float(v[3]))
135 ax.bar(pos[i],vv, align='center', color=col, label=lab)
136 xticks(pos,nam,rotation=-20, ha = 'left',size=params['feature_font_size'])
137 ax.set_title(params['title'],size=params['title_font_size'])
138 ax.set_ylabel("LDA SCORE (log 10)")
139 ax.yaxis.grid(True)
140 a,b = ax.get_xlim()
141 dx = float(len(pos))/float((b-a))
142 ax.set_xlim((0-dx,max(pos)+dx))
143 plt.savefig(path,format=params['format'],facecolor=params['back_color'],edgecolor=params['fore_color'],dpi=params['dpi'])
144 plt.close()
145
146 if __name__ == '__main__':
147 params = read_params(sys.argv)
148 params['fore_color'] = 'w' if params['back_color'] == 'k' else 'k'
149 data = read_data(params['input_file'],params['output_file'])
150 if params['orientation'] == 'v': plot_histo_ver(params['output_file'],params,data)
151 else: plot_histo_hor(params['output_file'],params,data,len(data['cls']) == 2)
152
153