-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCDHIT_mothurize_clstr.py
executable file
·252 lines (200 loc) · 6.92 KB
/
CDHIT_mothurize_clstr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
########################################################################################
## This file is a part of YAP package of scripts. https://github.com/shpakoo/YAP
## Distributed under the MIT license: http://www.opensource.org/licenses/mit-license.php
## Copyright (c) 2011-2013 Sebastian Szpakowski
########################################################################################
#################################################
## create or merge with existing names file an output from
## CD-HIT
#################################################
import sys
from optparse import OptionParser
from collections import defaultdict
_author="Sebastian Szpakowski"
_date="2011/01/01"
_version="Version 1"
#################################################
## Classes
##
#################################################
### Iterator over input file.
### every line is converted into a dictionary with variables referred to by their
### header name
class GeneralPurposeParser:
def __init__(self, file, skip=0, sep="\t"):
self.filename = file
self.fp = open(self.filename, "r")
self.sep = sep
self.linecounter = 0
self.currline=""
def __iter__(self):
return (self)
def next(self):
otpt = dict()
for currline in self.fp:
currline = currline.strip().split(self.sep)
self.currline = currline
self.linecounter = self.linecounter + 1
return(currline)
raise StopIteration
def __str__(self):
return "%s [%s]\n\t%s" % (self.filename, self.linecounter, self.currline)
class FastaLikeParser:
def __init__ (self, x):
self.filename = x
self.fp = open(x, "r")
self.currline = ""
self.currentFastaName = ""
self.currentFastaSequence = ""
self.lastitem=False
def __iter__(self):
return(self)
#####
def next(self):
for self.currline in self.fp:
if self.currline.startswith(">"):
self.currline = self.currline[1:]
if self.currentFastaName == "":
self.currentFastaName = self.currline
else:
otpt = (self.currentFastaName.strip(), self.currentFastaSequence.strip())
self.currentFastaName = self.currline
self.currentFastaSequence = ""
self.previoustell = self.fp.tell()
return (otpt)
else:
self.addSequence(self.currline)
if not self.lastitem:
self.lastitem=True
return (self.currentFastaName.strip(), self.currentFastaSequence.strip())
else:
raise StopIteration
def addSequence(self, x):
self.currentFastaSequence = "%s\n%s" % (self.currentFastaSequence, x.strip())
def __str__():
return ("reading file: %s" %self.filename)
#################################################
### Iterator over input fata file.
### Only reading when requested
### Useful for very large FASTA files
### with many sequences
class FastaParser:
def __init__ (self, x, quals=False):
self.filename = x
self.fp = open(x, "r")
self.currline = ""
self.currentFastaName = ""
self.currentFastaSequence = ""
self.lastitem=False
if quals:
self.linesep=" "
else:
self.linesep=""
def __iter__(self):
return(self)
#####
def next(self):
for self.currline in self.fp:
if self.currline.startswith(">"):
self.currline = self.currline[1:]
if self.currentFastaName == "":
self.currentFastaName = self.currline
else:
otpt = (self.currentFastaName.strip(), self.currentFastaSequence.strip())
self.currentFastaName = self.currline
self.currentFastaSequence = ""
self.previoustell = self.fp.tell()
return (otpt)
else:
self.addSequence(self.currline)
if not self.lastitem:
self.lastitem=True
return (self.currentFastaName.strip(), self.currentFastaSequence.strip())
else:
raise StopIteration
def addSequence(self, x):
self.currentFastaSequence = "%s%s%s" % (self.currentFastaSequence,self.linesep, x.strip())
def __str__():
return ("reading file: %s" %self.filename)
#################################################
## Functions
##
#################################################
## Arguments
##
parser = OptionParser()
parser.add_option("-c", "--cluster", dest="fn_clstr",
help="clustering from CDHIT", metavar="FILE")
parser.add_option("-n", "--names", dest="fn_name", default ="",
help="names from CDHIT", metavar="FILE")
parser.add_option("-o", "--output_mode", dest="out_mode", default = "name",
help="output mode, i.e. either output list or names files", metavar="FILE")
#parser.add_option("-q", "--quiet",
# action="store_false", dest="verbose", default=True,
# help="don't print status messages to stdout")
(options, args) = parser.parse_args()
#################################################
## Begin
##
names = defaultdict(set)
outputnames = defaultdict(set)
if options.fn_name != "" :
for id, desc in GeneralPurposeParser(options.fn_name, skip=0, sep="\t"):
[names[id].add(x) for x in desc.split(",")]
for clusterid, contents in FastaLikeParser(options.fn_clstr):
representative= ""
descendants = set()
for line in contents.strip().split("\n"):
line = line.strip()
id = line.split(">")[1].split("...")[0].split()[0]
if line.endswith("*"):
representative = id
#print "repr"
### self is always a descendant of itself!
descendants.add(id)
[descendants.add(x) for x in names[id]]
outputnames[representative] = descendants
if options.out_mode =="name":
prefix = options.fn_clstr.strip().split("/")[-1]
otptfile = open("%s.name" % (prefix), "w")
for key, vals in outputnames.items():
otptfile.write("%s\t%s" % (key, key))
vals.discard(key)
if len(vals)>0:
otptfile.write(",%s\n" % (",".join(list(vals))))
else:
otptfile.write("\n")
otptfile.close()
else:
otus = defaultdict(list)
prefix = options.fn_clstr.strip().split("/")[-1]
listfile = open("%s.list" % (prefix), "w" )
listfile.write("%s\t%s" % (options.out_mode, len(outputnames.keys() )))
rafile =open("%s.rabund" % (prefix), "w")
rafile.write("%s\t%s" % (options.out_mode, len(outputnames.keys() )))
safile = open("%s.sabund" % (prefix), "w")
safile.write("%s" % (options.out_mode))
mx = 0
for key, vals in outputnames.items():
otus[len(vals)].append(vals)
### the OTUs must start with a representative, followed by rest
#print key, vals
vals.remove(key)
curotu = "%s,%s" % (key, (",").join(list(vals)))
listfile.write("\t%s" % curotu.strip(","))
### we removed the representative, add one!)
rafile.write("\t%s" % (len(vals)+1))
mx = max (mx, len(vals)+1)
safile.write("\t%s" % (mx) )
for x in range (max(otus.keys())):
x = x+1
safile.write("\t%s" % len(otus[x]))
listfile.write("\n")
rafile.write("\n")
safile.write("\n")
listfile.close()
rafile.close()
safile.close()
#################################################
## Finish
#################################################