comparison smart_toolShed/commons/core/writer/CsvWriter.py @ 0:e0f8dcca02ed

Uploaded S-MART tool. A toolbox manages RNA-Seq and ChIP-Seq data.
author yufei-luo
date Thu, 17 Jan 2013 10:52:14 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e0f8dcca02ed
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 os
31 import random
32 from commons.core.writer.TranscriptListWriter import TranscriptListWriter
33 from SMART.Java.Python.misc.Progress import Progress
34
35 class CsvWriter(TranscriptListWriter):
36 """
37 A class that writes a transcript list into a file with CSV (Excel) format
38 @ivar fileName: name of the file
39 @type fileName: string
40 @ivar handle: handle to the file
41 @type handle: file handle
42 """
43
44
45 def __init__(self, fileName, verbosity = 0):
46 """
47 Constructor
48 @param fileName: name of the file
49 @type fileName: string
50 @param verbosity: verbosity
51 @type verbosity: int
52 """
53 super(CsvWriter, self).__init__(fileName, verbosity)
54 self.header = ""
55 self.title = "chromosome,start,end,strand,exons,tags\n"
56 self.modified = False
57
58
59 def __del__(self):
60 """
61 Destructor
62 (Trick to write 1 tag per column)
63 """
64 if self.handle != None:
65 self.modifyCsv()
66 super(CsvWriter, self).__del__()
67
68
69 def close(self):
70 if self.handle != None:
71 self.modifyCsv()
72 super(CsvWriter, self).close()
73
74
75 def modifyCsv(self):
76 """
77 Clean CSV file so that there is one column per tag
78 """
79 if self.modified:
80 return
81
82 # read all the tags
83 self.handle.close()
84 self.handle = open(self.fileName)
85 nbFirstFields = 5
86 tags = set()
87 if self.verbosity >= 10:
88 print "Modifying CSV file..."
89 number = -1
90 for number, line in enumerate(self.handle):
91 if number != 0:
92 theseTags = line.strip().split(",")[nbFirstFields:]
93 for tag in theseTags:
94 if tag.find("=") != -1:
95 (key, value) = tag.split("=", 1)
96 if value != None:
97 tags.add(key)
98 if self.verbosity >= 10:
99 print " ...done"
100
101 # re-write the file
102 tmpFileName = "tmpFile%d.csv" % (random.randint(0, 100000))
103 tmpFile = open(tmpFileName, "w")
104 self.handle.seek(0)
105 progress = Progress(number + 1, "Re-writting CSV file", self.verbosity)
106 tmpFile.write(self.title.replace("tags", ",".join(sorted(tags))))
107 for line in self.handle:
108 tagValues = dict([(key, None) for key in tags])
109 tmpFile.write(",".join(line.strip().split(",")[:nbFirstFields]))
110 for tag in line.strip().split(",")[nbFirstFields:]:
111 if tag.find("=") != -1:
112 key = tag.split("=", 1)[0]
113 tagValues[key] = tag.split("=", 1)[1]
114 else:
115 tagValues[key] += ";%s" % (tag)
116 for key in sorted(tagValues.keys()):
117 tmpFile.write(",%s" % (tagValues[key]))
118 tmpFile.write("\n")
119 progress.inc()
120 tmpFile.close()
121
122 # replace former file
123 import shutil
124 shutil.move(tmpFile.name, self.fileName)
125 progress.done()
126 self.modified = True
127
128
129 @staticmethod
130 def getFileFormats():
131 """
132 Get the format of the file
133 """
134 return ["csv", "xls", "excel"]
135
136
137 @staticmethod
138 def getExtension():
139 """
140 Get the usual extension for the file
141 """
142 return "csv"
143
144
145 def printTranscript(self, transcript):
146 """
147 Export the given transcript with GFF2 format
148 @param transcript: transcript to be printed
149 @type transcript: class L{Transcript<Transcript>}
150 @return: a string
151 """
152 return transcript.printCsv()
153