first pass cleanup of cistematic/genomes; change bamPreprocessing
[erange.git] / plotbardist.py
1 #
2 #  plotbardist.py
3 #  ENRAGE
4 #
5 #  Created by Ali Mortazavi on 12/13/07.
6
7 try:
8     import psyco
9     psyco.full()
10 except:
11     pass
12
13 import sys
14 import optparse
15 import matplotlib
16 from pylab import *
17 from math import *
18 from commoncode import getConfigParser, getConfigOption, getConfigIntOption, getConfigFloatOption
19
20
21 print "plotbardist: version 3.3"
22
23
24 def main(argv=None):
25     if not argv:
26         argv = sys.argv
27
28     usage = "usage: python %prog infile1 [infile2] [infile3] [options] outfile.png"
29
30     parser = makeParser(usage)
31     (options, args) = parser.parse_args(argv[1:])
32
33
34     if len(args) < 2 or len(args) > 4:
35         print usage
36         print "where labelList and legendList are comma delimited strings of the form 'labelA,labelB,...,labelN'"
37         sys.exit(1)
38
39     fileList = args[:-1]
40     pngfilename = args[-1]
41
42     plotbardist(fileList, pngfilename, options.bins, options.binnedField, options.binLength,
43                 options.logBase, options.maxY, options.xLabel, options.yLabel, options.binLabels,
44                 options.figTitle, options.barsLegend, options.pointOffset, options.figSizes)
45
46
47 def makeParser(usage=""):
48     parser = optparse.OptionParser(usage=usage)
49     parser.add_option("--bins", type="int", dest="bins")
50     parser.add_option("--field", type="int", dest="binnedField")
51     parser.add_option("--binSize", type="float", dest="binLength")
52     parser.add_option("--doLog", type="int", dest="logBase")
53     parser.add_option("--ymax", type="int", dest="maxY")
54     parser.add_option("--xlabel", dest="xLabel")
55     parser.add_option("--ylabel", dest="yLabel")
56     parser.add_option("--binLabels", dest="binLabels", help="comma separated list")
57     parser.add_option("--title", dest="figTitle")
58     parser.add_option("--legend", dest="barsLegend", help="comma separated list")
59     parser.add_option("--xoffset", type="float", dest="pointOffset")
60     parser.add_option("--figsize", dest="figSizes", help="x,y pair")
61
62     configParser = getConfigParser()
63     section = "plotbardist"
64     bins = getConfigIntOption(configParser, section, "bins", 10)
65     binnedField = getConfigIntOption(configParser, section, "binnedField", -1)
66     binLength = getConfigIntOption(configParser, section, "binLength", -1)
67     logBase = getConfigOption(configParser, section, "logBase", None)
68     maxY = getConfigIntOption(configParser, section, "maxY", 0)
69     xLabel = getConfigOption(configParser, section, "xLabel", "bins")
70     yLabel = getConfigOption(configParser, section, "yLabel", "count")
71     binLabels = getConfigOption(configParser, section, "binLabels", None)
72     figTitle = getConfigOption(configParser, section, "figTitle", "")
73     barsLegend = getConfigOption(configParser, section, "barsLegend", None)
74     pointOffset = getConfigFloatOption(configParser, section, "pointOffset", 0.)
75     figSizes = getConfigOption(configParser, section, "figSizes", None)
76
77     parser.set_defaults(bins=bins, binnedField=binnedField, binLength=binLength, logBase=logBase, maxY=maxY,
78                         xLabel=xLabel, yLabel=yLabel, binLabels=binLabels, figTitle=figTitle,
79                         barsLegend=barsLegend, pointOffset=pointOffset, figSizes=figSizes)
80
81     return parser
82
83
84 def plotbardist(fileList, pngfilename, bins=10, binnedField=-1, binLength=-1, logBase=None,
85                 maxY=0, xLabel="bins", yLabel="count", binLabels=None, figTitle="",
86                 barsLegend=None, pointOffset=0., figSizes=None):
87
88     matplotlib.use("Agg")
89     plotParameters = {1: {"width": 0.5,
90                           "offset": [-0.25]},
91                       2: {"width": 0.3,
92                           "offset": [-0.3, 0]},
93                       3: {"width": 0.2,
94                           "offset": [-0.2, 0., 0.2]}
95     }
96
97     colorList = ["b", "r", "c"]
98     width = plotParameters[len(fileList)]["width"]
99     offset = plotParameters[len(fileList)]["offset"]
100
101     doLog = False
102     if logBase is not None:
103         doLog = True
104         print "taking log%d of x datapoints" % logBase
105         xLabel = "log%d(%s)" % (logBase, xLabel)
106     else:
107         logBase = 10
108
109     if figSizes is not None:
110         sizes = figSizes.strip().split(",")
111         figure(figsize=(float(sizes[0]),float(sizes[1])))
112
113     doLabels = False
114     if binLabels is not None:
115         binLabels = binLabels.strip().split(",")
116         doLabels = True
117     else:
118         binLabels = []
119
120     if barsLegend is not None:
121         barsLegend = barsLegend.strip().split(",")
122     else:
123         barsLegend = []
124     
125     ind2 = arange(bins)
126
127     bars = []
128     barsColors = []
129     index = 0
130     for fileName in fileList:
131         aFile = open(fileName)
132         distbin = bins * [0]
133
134         dataList = []
135         for line in aFile:
136             fields = line.strip().split()
137             try:
138                 point = float(fields[binnedField]) + pointOffset
139                 if doLog:
140                     if point < 1:
141                         point = 1
142
143                     point = log(point, logBase)
144
145                 dataList.append(point)
146             except:
147                 continue
148
149         print "%d data points" % len(dataList)
150
151         dataList.sort()
152         print "low = %f high = %f" % (dataList[0], dataList[-1])
153
154         if binLength < 0:
155             binLength = abs(dataList[-1] - dataList[0]) / bins
156
157         for point in dataList:
158             try:
159                 distbin[int(round(point/binLength))] += 1
160             except:
161                 distbin[-1] += 1
162
163         print binLength, int(round(point/binLength))
164
165         bars.append(bar(ind2 + offset[index], distbin, width, color=colorList[index]))
166         barsColors.append(bars[-1][0])
167
168         print distbin
169         halfCount = sum(distbin) / 2
170         median = 0
171         foundMedian = False
172         while not foundMedian:
173             if sum(distbin[:median]) < halfCount:
174                 median += 1
175             else:
176                 foundMedian = True
177
178         print median
179         index += 1
180
181     xlim(-1 * width - 0.2, bins + 0.2)
182
183     if len(barsLegend) > 0:
184         legend(barsColors, barsLegend)
185
186     ylabel(yLabel)
187     xlabel(xLabel)
188
189     if doLabels:
190         setp(gca(), "xticklabels", binLabels)
191
192     if maxY > 0:
193         ylim(0, maxY)
194
195     if len(figTitle) > 0:
196         title(figTitle)
197
198     gca().get_xaxis().tick_bottom()
199     gca().get_yaxis().tick_left()
200
201     savefig(pngfilename)
202
203
204 if __name__ == "__main__":
205     main(sys.argv)