comparison commons/core/parsing/GffParser.py @ 6:769e306b7933

Change the repository level.
author yufei-luo
date Fri, 18 Jan 2013 04:54:14 -0500
parents
children
comparison
equal deleted inserted replaced
5:ea3082881bf8 6:769e306b7933
1 #
2 # Copyright INRA-URGI 2009-2010
3 #
4 # This software is governed by the CeCILL license under French law and
5 # abiding by the rules of distribution of free software. You can use,
6 # modify and/ or redistribute the software under the terms of the CeCILL
7 # license as circulated by CEA, CNRS and INRIA at the following URL
8 # "http://www.cecill.info".
9 #
10 # As a counterpart to the access to the source code and rights to copy,
11 # modify and redistribute granted by the license, users are provided only
12 # with a limited warranty and the software's author, the holder of the
13 # economic rights, and the successive licensors have only limited
14 # liability.
15 #
16 # In this respect, the user's attention is drawn to the risks associated
17 # with loading, using, modifying and/or developing or reproducing the
18 # software by the user in light of its specific status of free software,
19 # that may mean that it is complicated to manipulate, and that also
20 # therefore means that it is reserved for developers and experienced
21 # professionals having in-depth computer knowledge. Users are therefore
22 # encouraged to load and test the software's suitability as regards their
23 # requirements in conditions enabling the security of their systems and/or
24 # data to be ensured and, more generally, to use and operate it in the
25 # same conditions as regards security.
26 #
27 # The fact that you are presently reading this means that you have had
28 # knowledge of the CeCILL license and that you accept its terms.
29 #
30 import re
31 import sys
32 from SMART.Java.Python.structure.Interval import Interval
33 from SMART.Java.Python.structure.Transcript import Transcript
34 from commons.core.parsing.TranscriptListParser import TranscriptListParser
35
36
37 class GffParser(TranscriptListParser):
38 """A class that parses a GFF file and create a transcript list"""
39
40
41 def __init__(self, fileName, verbosity = 0):
42 super(GffParser, self).__init__(fileName, verbosity)
43
44
45 def __del__(self):
46 super(GffParser, self).__del__()
47
48
49 def getFileFormats():
50 return ["gff", "gff2", "gff3"]
51 getFileFormats = staticmethod(getFileFormats)
52
53
54 def skipFirstLines(self):
55 pass
56
57
58 def getInfos(self):
59 self.chromosomes = set()
60 self.nbTranscripts = 0
61 self.size = 0
62 self.reset()
63 if self.verbosity >= 10:
64 print "Getting information on %s." % (self.fileName)
65 self.reset()
66 for line in self.handle:
67 line = line.strip()
68 if line == "" or line[0] == "#":
69 continue
70 parts = line.split("\t")
71 if len(parts) != 9:
72 raise Exception("Error! Line '%s' has %d tab-separated fields instead of 9!" % (line, len(parts)))
73 self.chromosomes.add(parts[0])
74 if parts[8].find("Parent") == -1:
75 self.nbTranscripts += 1
76 else:
77 self.size += max(int(parts[3]), int(parts[4])) - min(int(parts[3]), int(parts[4])) + 1
78 if self.verbosity >= 10 and self.nbTranscripts % 100000 == 0:
79 sys.stdout.write(" %d transcripts read\r" % (self.nbTranscripts))
80 sys.stdout.flush()
81 self.reset()
82 if self.verbosity >= 10:
83 print " %d transcripts read" % (self.nbTranscripts)
84 print "Done."
85
86
87 def parseLine(self, line):
88 if not line or line[0] == "#":
89 return None
90 m = re.search(r"^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\S+)\s+([+-.])\s+(\S+)\s+(\S.*)$", line)
91 if m == None:
92 raise Exception("\nLine %d '%s' does not have a GFF format\n" % (self.currentLineNb, line))
93 interval = Interval()
94 interval.setChromosome(m.group(1))
95 interval.setName("unnamed transcript")
96 interval.setStart(min(int(m.group(4)), int(m.group(5))))
97 interval.setEnd(max(int(m.group(4)), int(m.group(5))))
98 if m.group(7) == ".":
99 interval.setDirection("+")
100 else:
101 interval.setDirection(m.group(7))
102 interval.setTagValue("feature", m.group(3))
103 if m.group(6).isdigit():
104 interval.setTagValue("score", m.group(6))
105
106 remainings = m.group(9).split(";")
107 for remaining in remainings:
108 remaining = remaining.strip()
109 if remaining == "":
110 continue
111 posSpace = remaining.find(" ")
112 posEqual = remaining.find("=")
113 if posEqual != -1 and (posEqual < posSpace or posSpace == -1):
114 parts = remaining.split("=")
115 else:
116 parts = remaining.split()
117 field = parts[0].strip()
118 value = " ".join(parts[1:]).strip(" \"")
119 if field in ("Name", "name", "Sequence", "TE", "SAT"):
120 interval.setName(value)
121 else:
122 try:
123 intValue = int(value)
124 interval.setTagValue(field, intValue)
125 except ValueError:
126 interval.setTagValue(field, value)
127
128 self.currentTranscriptAddress = self.previousTranscriptAddress
129 if "Parent" in interval.getTagNames():
130 if self.currentTranscript == None:
131 raise Exception("GFF file does not start with a transcript! First line is '%s'." % (line.strip()))
132 if interval.getTagValue("Parent") != self.currentTranscript.getTagValue("ID"):
133 raise Exception("Exon '%s' is not right after its transcript in GFF file!" % (interval))
134 self.currentTranscript.addExon(interval)
135 if interval.name == None:
136 interval.name = self.currentTranscript.name
137 return None
138
139 transcript = self.currentTranscript
140 self.currentTranscript = Transcript()
141 self.currentTranscript.copy(interval)
142 self.previousTranscriptAddress = self.currentAddress
143
144 if transcript != None and transcript.name.startswith("unnamed"):
145 if "ID" in transcript.getTagNames():
146 transcript.name = transcript.getTagValue("ID")
147 else:
148 transcript.name = "unnamed transcript %s" % (self.currentLineNb)
149 return transcript