38
|
1 #! /usr/bin/env python
|
|
2 #
|
|
3 # Copyright INRA-URGI 2009-2010
|
|
4 #
|
|
5 # This software is governed by the CeCILL license under French law and
|
|
6 # abiding by the rules of distribution of free software. You can use,
|
|
7 # modify and/ or redistribute the software under the terms of the CeCILL
|
|
8 # license as circulated by CEA, CNRS and INRIA at the following URL
|
|
9 # "http://www.cecill.info".
|
|
10 #
|
|
11 # As a counterpart to the access to the source code and rights to copy,
|
|
12 # modify and redistribute granted by the license, users are provided only
|
|
13 # with a limited warranty and the software's author, the holder of the
|
|
14 # economic rights, and the successive licensors have only limited
|
|
15 # liability.
|
|
16 #
|
|
17 # In this respect, the user's attention is drawn to the risks associated
|
|
18 # with loading, using, modifying and/or developing or reproducing the
|
|
19 # software by the user in light of its specific status of free software,
|
|
20 # that may mean that it is complicated to manipulate, and that also
|
|
21 # therefore means that it is reserved for developers and experienced
|
|
22 # professionals having in-depth computer knowledge. Users are therefore
|
|
23 # encouraged to load and test the software's suitability as regards their
|
|
24 # requirements in conditions enabling the security of their systems and/or
|
|
25 # data to be ensured and, more generally, to use and operate it in the
|
|
26 # same conditions as regards security.
|
|
27 #
|
|
28 # The fact that you are presently reading this means that you have had
|
|
29 # knowledge of the CeCILL license and that you accept its terms.
|
|
30 #
|
|
31 import random, os, glob, subprocess
|
|
32 from commons.core.parsing.ParserChooser import ParserChooser
|
|
33 from commons.core.parsing.GffParser import GffParser
|
|
34 from SMART.Java.Python.misc.UnlimitedProgress import UnlimitedProgress
|
|
35 from SMART.Java.Python.misc.Progress import Progress
|
|
36 from SMART.Java.Python.misc import Utils
|
|
37 from commons.core.LoggerFactory import LoggerFactory
|
|
38 from commons.core.utils.RepetOptionParser import RepetOptionParser
|
|
39
|
|
40 LOG_DEPTH = "smart"
|
|
41 DEFAULT_REGION = "_all_"
|
|
42
|
|
43 class GetReadSizes(object):
|
|
44
|
|
45 def __init__(self, verbosity = 0):
|
|
46 self.xLab = "Size"
|
|
47 self.yLab = "# reads"
|
|
48 self.verbosity = verbosity
|
|
49 self.number = random.randint(0, 100000)
|
|
50 self.log = LoggerFactory.createLogger("%s.%s" % (LOG_DEPTH, self.__class__.__name__), self.verbosity)
|
|
51 self.parsers = {}
|
|
52 self.sizes = {}
|
|
53 self.factors = {}
|
|
54 self.regions = None
|
46
|
55 self.percentage = False
|
38
|
56 self.tmpDatName = None
|
|
57 self.tmpRName = None
|
|
58 self.width = 800
|
|
59 self.height = 300
|
|
60 self.arial = False
|
|
61
|
|
62 def setNames(self, names):
|
|
63 self.names = names
|
|
64
|
|
65 def setInputFiles(self, fileNames, format):
|
|
66 chooser = ParserChooser(self.verbosity)
|
|
67 chooser.findFormat(format)
|
|
68 for cpt, fileName in enumerate(fileNames):
|
|
69 self.parsers[self.names[cpt]] = chooser.getParser(fileName)
|
46
|
70 if not self.factors:
|
|
71 self.factors = dict([name, 1.0] for name in self.names)
|
38
|
72
|
|
73 def setOutputFileName(self, fileName):
|
|
74 self.outputFileName = fileName
|
|
75
|
|
76 def setLabs(self, xLab, yLab):
|
|
77 self.xLab = xLab
|
|
78 self.yLab = yLab
|
|
79
|
|
80 def setSizes(self, minSize, maxSize):
|
|
81 self.minSize = minSize
|
|
82 self.maxSize = maxSize
|
|
83
|
|
84 def setColors(self, colors):
|
|
85 self.colors = colors
|
|
86
|
|
87 def setFactors(self, factors):
|
46
|
88 if factors:
|
|
89 self.factors = dict(zip(self.names, factors))
|
38
|
90
|
|
91 def setRegionsFile(self, fileName):
|
|
92 if fileName != None:
|
|
93 self._loadRegions(fileName)
|
|
94
|
46
|
95 def setPercentage(self, percentage):
|
|
96 self.percentage = percentage
|
|
97 self.xLab = "% reads"
|
|
98
|
38
|
99 def setImageSize(self, width, height):
|
|
100 if width != None:
|
|
101 self.width = width
|
|
102 if height != None:
|
|
103 self.height = height
|
|
104
|
|
105 def setArial(self, arial):
|
|
106 self.arial = arial
|
|
107
|
|
108 def _checkOptions(self):
|
|
109 if not self.parsers:
|
|
110 self.logAndRaise("ERROR: Missing input file names")
|
|
111
|
|
112 def _logAndRaise(self, errorMsg):
|
|
113 self.log.error(errorMsg)
|
|
114 raise Exception(errorMsg)
|
|
115
|
|
116 def _loadRegions(self, fileName):
|
|
117 self.regions = {}
|
|
118 parser = GffParser(fileName, self.verbosity)
|
|
119 for transcript in parser.getIterator():
|
|
120 chromosome = transcript.getChromosome()
|
|
121 start = transcript.getStart()
|
|
122 end = transcript.getEnd()
|
|
123 name = transcript.getName()
|
|
124 if chromosome not in self.regions:
|
|
125 self.regions[chromosome] = {}
|
|
126 if start not in self.regions[chromosome]:
|
|
127 self.regions[chromosome][start] = {}
|
|
128 if end not in self.regions[chromosome][start]:
|
|
129 self.regions[chromosome][start][end] = []
|
|
130 self.regions[chromosome][start][end].append(name)
|
|
131
|
|
132 def _getRegions(self, transcript):
|
|
133 if self.regions == None:
|
|
134 return [DEFAULT_REGION]
|
|
135 chromosome = transcript.getChromosome()
|
|
136 start = transcript.getStart()
|
|
137 end = transcript.getEnd()
|
|
138 if chromosome not in self.regions:
|
|
139 return []
|
|
140 names = []
|
|
141 for loadedStart in sorted(self.regions[chromosome].keys()):
|
|
142 if loadedStart > end:
|
|
143 return names
|
|
144 for loadedEnd in reversed(sorted(self.regions[chromosome][loadedStart].keys())):
|
|
145 if loadedEnd < start:
|
|
146 break
|
|
147 names.extend(self.regions[chromosome][loadedStart][loadedEnd])
|
|
148 return names
|
|
149
|
|
150 def _parse(self, name):
|
|
151 progress = UnlimitedProgress(10000, "Reading file '%s'" % (name), self.verbosity)
|
|
152 for transcript in self.parsers[name].getIterator():
|
|
153 if transcript.__class__.__name__ == "Mapping":
|
|
154 transcript = transcript.getTranscript()
|
|
155 regions = self._getRegions(transcript)
|
|
156 for region in regions:
|
|
157 if region not in self.sizes:
|
|
158 self.sizes[region] = {}
|
|
159 if name not in self.sizes[region]:
|
|
160 self.sizes[region][name] = {}
|
|
161 size = transcript.getSize()
|
|
162 if (self.minSize == None or size >= self.minSize) and (self.maxSize == None or size <= self.maxSize):
|
|
163 nbElements = float(transcript.getTagValue("nbElements")) if "nbElements" in transcript.getTagNames() else 1
|
|
164 nbElements *= self.factors.get(name, 1)
|
|
165 self.sizes[region][name][size] = self.sizes[region][name].get(size, 0) + nbElements
|
|
166 progress.inc()
|
|
167 progress.done()
|
|
168 if self.minSize == None:
|
|
169 self.minSize = min([min(self.sizes[region][name].keys()) for name in self.names for region in region])
|
|
170 if self.maxSize == None:
|
|
171 self.maxSize = max([max(self.sizes[region][name].keys()) for name in self.names for region in region])
|
|
172
|
|
173 def _checkQuorum(self, region):
|
|
174 return (max([sum(self.sizes[region][name].values()) for name in self.sizes[region]]) > 0)
|
|
175
|
46
|
176 def _computePercentage(self):
|
|
177 for region in self.sizes:
|
|
178 for name in self.sizes[region]:
|
|
179 if self.sizes[region][name]:
|
|
180 sumData = float(sum(self.sizes[region][name].values()))
|
|
181 for size in self.sizes[region][name]:
|
|
182 self.sizes[region][name][size] = self.sizes[region][name][size] / sumData * 100
|
|
183
|
38
|
184 def _writeData(self, region):
|
|
185 self.tmpDatName = "tmpFile%d.dat" % (self.number)
|
|
186 handle = open(self.tmpDatName, "w")
|
|
187 handle.write("Size\tCount\tSample\n")
|
|
188 for name in self.sizes[region]:
|
|
189 for size in sorted(self.sizes[region][name].keys()):
|
|
190 handle.write("%d\t%d\t\"%s\"\n" % (size, self.sizes[region][name].get(size, 0), name))
|
|
191 handle.close()
|
|
192
|
|
193 def _writeScript(self, region):
|
|
194 self.tmpRName = "tmpFile%d.R" % (self.number)
|
|
195 fileName = self.outputFileName if region == DEFAULT_REGION else "%s_%s.png" % (os.path.splitext(self.outputFileName)[0], region)
|
|
196 colors = "scale_fill_brewer(palette=\"Set1\")" if self.colors == None else "scale_fill_manual(values = c(%s))" % (", ".join(["\"%s\"" % (color) for color in self.colors]))
|
|
197 title = "" if region == DEFAULT_REGION else " + labs(title = \"Sizes of %s\")" % (region)
|
|
198 handle = open(self.tmpRName, "w")
|
|
199 arial = ", text = element_text(family=\"Arial\", size=20)" if self.arial else ""
|
|
200 if self.arial:
|
|
201 handle.write("library(extrafont)\nloadfonts()\n")
|
|
202 handle.write("library(ggplot2)\n")
|
|
203 handle.write("data <- read.table(\"%s\", header = T)\n" % (self.tmpDatName))
|
|
204 handle.write("data$Sample <- factor(data$Sample, levels=c(%s))\n" % (", ".join(["\"%s\"" % (name) for name in self.names])))
|
|
205 handle.write("data$Size <- factor(data$Size, levels=c(%s))\n" % (", ".join(["%d" % (size) for size in range(self.minSize, self.maxSize+1)])))
|
|
206 handle.write("png(\"%s\", width = %d, height = %d)\n" % (fileName, self.width, self.height))
|
|
207 handle.write("ggplot(data, aes(x = Size, y = Count, fill = Size)) %s + geom_bar(stat = \"identity\") + facet_grid(. ~ Sample, space=\"free_x\") + xlab(\"%s\") + ylab(\"%s\") + %s + theme(legend.position = \"none\", panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank()%s)\n" % (title, self.xLab, self.yLab, colors, arial))
|
|
208 handle.write("dev.off()\n")
|
|
209
|
|
210 def _runR(self):
|
|
211 rCommand = os.environ["SMARTRPATH"] if "SMARTRPATH" in os.environ else "R"
|
|
212 command = "\"%s\" CMD BATCH %s" % (rCommand, self.tmpRName)
|
|
213 status = subprocess.call(command, shell=True)
|
|
214 if status != 0:
|
|
215 raise Exception("Problem with the execution of script file %s, status is: %s" % (self.tmpRName, status))
|
|
216
|
|
217 def _plot(self):
|
|
218 progress = Progress(len(self.sizes), "Plotting data", self.verbosity)
|
|
219 for region in self.sizes:
|
|
220 if not self._checkQuorum(region):
|
|
221 self.log.info("Not displaying '%s' for it contains no data." % (region))
|
|
222 else:
|
|
223 self._writeData(region)
|
|
224 self._writeScript(region)
|
|
225 self._runR()
|
|
226 progress.inc()
|
|
227 progress.done()
|
|
228
|
|
229 def _cleanFiles(self):
|
|
230 for fileName in (self.tmpDatName, self.tmpRName):
|
|
231 if fileName != None and os.path.exists(fileName):
|
|
232 os.remove(fileName)
|
|
233 for otherFileName in glob.glob("%s*" % (fileName)):
|
|
234 os.remove(otherFileName)
|
|
235
|
|
236 def run(self):
|
|
237 LoggerFactory.setLevel(self.log, self.verbosity)
|
|
238 self._checkOptions()
|
|
239 self.log.info("START Get Read Sizes")
|
|
240 for name in self.names:
|
|
241 self._parse(name)
|
46
|
242 if self.percentage:
|
|
243 self._computePercentage()
|
38
|
244 self._plot()
|
|
245 self._cleanFiles()
|
|
246 self.log.info("END Get Read Sizes")
|
|
247
|
|
248
|
|
249 if __name__ == "__main__":
|
|
250 description = "Usage: GetReadSizes.py [options]\n\nGet Read Sizes v1.0.1: Get the sizes of a set of reads. [Category: Personal]\n"
|
|
251 epilog = ""
|
|
252 parser = RepetOptionParser(description = description, epilog = epilog)
|
|
253 parser.add_option("-i", "--input", dest="inputFileNames", action="store", default=None, type="string", help="input files, separated by commas [compulsory] [format: string]")
|
|
254 parser.add_option("-f", "--format", dest="format", action="store", default=None, type="string", help="format of the input [compulsory] [format: transcript or sequence file format]")
|
|
255 parser.add_option("-n", "--names", dest="names", action="store", default=None, type="string", help="name of the input data, separated by commas [compulsory] [format: string]")
|
|
256 parser.add_option("-o", "--output", dest="outputFileName", action="store", default=None, type="string", help="output file [format: output file in PNG format]")
|
|
257 parser.add_option("-s", "--minSize", dest="minSize", action="store", default=None, type="int", help="minimum size [format: int]")
|
|
258 parser.add_option("-S", "--maxSize", dest="maxSize", action="store", default=None, type="int", help="maximum size [format: int]")
|
|
259 parser.add_option("-l", "--xLabel", dest="xLab", action="store", default="Size", type="string", help="x-axis label name [format: string] [default: Size]")
|
|
260 parser.add_option("-L", "--yLabel", dest="yLab", action="store", default="# reads", type="string", help="y-axis label name [format: string] [default: Reads]")
|
|
261 parser.add_option("-c", "--colors", dest="colors", action="store", default=None, type="string", help="colors of the bars, separated by commas [format: string]")
|
|
262 parser.add_option("-a", "--factors", dest="factors", action="store", default=None, type="string", help="normalization factors, separated by commas [format: string]")
|
|
263 parser.add_option("-r", "--regions", dest="regionsFileName", action="store", default=None, type="string", help="regions to plot [format: transcript file in GFF format]")
|
46
|
264 parser.add_option("-p", "--percent", dest="percentage", action="store_true", default=False, help="compute percentage instead [format: boolean] [default: false]")
|
38
|
265 parser.add_option("-z", "--width", dest="width", action="store", default=800, type="int", help="width of the image [format: int] [default: 800]")
|
|
266 parser.add_option("-Z", "--height", dest="height", action="store", default=300, type="int", help="height of the image [format: int] [default: 300]")
|
|
267 parser.add_option("-A", "--arial", dest="arial", action="store_true", default=False, help="use Arial font [format: boolean] [default: false]")
|
|
268 parser.add_option("-v", "--verbosity", dest="verbosity", action="store", default=1, type="int", help="trace level [format: int]")
|
|
269 options = parser.parse_args()[0]
|
|
270 iGetReadSizes = GetReadSizes(options.verbosity)
|
|
271 iGetReadSizes.setNames(options.names.split(","))
|
|
272 iGetReadSizes.setInputFiles(options.inputFileNames.split(","), options.format)
|
|
273 iGetReadSizes.setOutputFileName(options.outputFileName)
|
|
274 iGetReadSizes.setSizes(options.minSize, options.maxSize)
|
|
275 iGetReadSizes.setColors(None if options.colors == None else options.colors.split(","))
|
|
276 iGetReadSizes.setFactors(None if options.factors == None else map(float, options.factors.split(",")))
|
|
277 iGetReadSizes.setRegionsFile(options.regionsFileName)
|
46
|
278 iGetReadSizes.setPercentage(options.percentage)
|
38
|
279 iGetReadSizes.setImageSize(options.width, options.height)
|
46
|
280 iGetReadSizes.setLabs(options.xLab, options.yLab)
|
38
|
281 iGetReadSizes.setArial(options.arial)
|
|
282 iGetReadSizes.run()
|