-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcount_hits.py
executable file
·219 lines (188 loc) · 6.71 KB
/
count_hits.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
#! /usr/bin/env python
"""
Count hits in a tabular blast output. By default, first hit for each read
is used.
"""
import argparse
import logging
import re
import sys
from edl.hits import add_count_arguments, add_weight_arguments, \
applyFractionalCutoff, getAllMethod
from edl.util import add_universal_arguments, setup_logging, \
parseMapFile
# a habit that stuck in Perl
die = sys.exit
def main():
# set up CLI
description = __doc__
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-i", "--infile", dest="infile",
metavar="FILE", help="Read raw table from INFILE")
parser.add_argument(
"-o",
"--outfile",
dest="outfile",
metavar="OUTFILE",
help="Write collapsed table to OUTFILE")
parser.add_argument("-d", "--delim", dest="delim", default="\t",
help="Input table delimiter", metavar="DELIM")
parser.add_argument("-D", "--delimOut", dest="delimOut", default="\t",
help="Output table delimiter", metavar="DELIM")
parser.add_argument(
'-F',
'--countFirst',
action='store_true',
default=False,
help="Don't skip the first line, it's NOT a header")
parser.add_argument(
"-R",
"--readColumn",
dest="readCol",
type=int,
default=0,
help="Index (starting at 0) of column with read name, 0 is default",
metavar="READCOL")
parser.add_argument(
"-H",
"--hitColumn",
dest="hitCol",
type=int,
default=2,
help="Index (starting at 0) of column with hit name (for counting), "
"2 is default, if less than zero, all (non-read) columns will "
"be used as multiple hits",
metavar="HITCOL")
parser.add_argument(
'-s',
'--hitSep',
default=None,
help="Use this string to split multiple values in single hit cell. "
"Default is 'None' to leave hits as is, use 'eval' to parse "
"as python repr strings")
add_weight_arguments(parser, multiple=False)
parser.add_argument("-T", "--total", default=False, action="store_true",
help="Report 'Total' in the first row")
# cutoff options
add_count_arguments(parser, {'cutoff': 0})
# log level and help
add_universal_arguments(parser)
arguments = parser.parse_args()
setup_logging(arguments)
# make sure we have something to do
if (arguments.infile is None):
logging.info("Reading table from: STDIN")
else:
logging.info("Reading table from: " + arguments.infile)
if (arguments.outfile is None):
logging.info("Writing counts to: STDOUT")
else:
logging.info("Writing counts to: " + arguments.outfile)
# process arguments
takeFirst = (arguments.allMethod == 'first')
splitHits = (arguments.hitSep is not None and arguments.hitSep != 'None')
uncluster = (arguments.weights is not None)
if arguments.hitSep == 'eval':
parser.error("Sorry, parsing with eval is not yet supported!")
# inform the curious user
logging.info("Delimiter: '" + arguments.delim)
logging.info("Read names in col: '" + str(arguments.readCol))
logging.info("Hit names in col: '" + str(arguments.hitCol))
if splitHits:
logging.info("Splitting hits with: %s" % (arguments.hitSep))
logging.warn(
"Splitting hits has not been tested yet! Let me know how it goes.")
if takeFirst:
logging.info("Taking first hit for each read.")
else:
if arguments.allMethod == 'portion':
logging.info("Dividing count among all hits for each read.")
else:
logging.info("Adding 1 to every hit for each read")
if uncluster:
logging.info(
"Getting read cluster sizes from: %s" %
(arguments.weights))
if arguments.countFirst:
logging.info("First line is data")
else:
logging.info("Skipping first line")
# Do the counting!
counts = {}
countHitsForRead = getAllMethod(arguments.allMethod)
clusteredReadCounts = {}
if uncluster:
clusteredReadCounts = parseMapFile(
arguments.clusterFile, valueType=int)
currentRead = ''
readCount = 1
hits = []
if arguments.infile is None:
infile = sys.stdin
else:
infile = open(arguments.infile)
# loop over lines
if not arguments.countFirst:
# skip first line
try:
next(infile)
except StopIteration:
raise Exception("No lines in %s" % str(infile))
for line in infile:
line = line.rstrip('\r\n')
rowcells = line.split(arguments.delim)
# get read
read = rowcells[arguments.readCol]
# if it's a new read, process previous read
if currentRead == '':
currentRead = read
elif read != currentRead and currentRead != '':
readCount += 1
logging.info("Checking hits for %s" % currentRead)
# was it part of a cluster?
multiplier = 1
if uncluster:
multiplier = clusteredReadCounts[currentRead]
# where does the count for this read go
countHitsForRead(hits, counts, multiplier=multiplier)
hits = []
currentRead = read
# get hit from this line
if arguments.hitCol >= 0:
hit = rowcells[arguments.hitCol]
if splitHits:
hits.extend(hit.split(arguments.hitSep))
else:
hits.append(hit)
else:
rowcells.pop(arguments.readCol)
hits.extend(rowcells)
# check last read!
logging.info("Checking hits for %s" % currentRead)
# was it part of a cluster?
multiplier = 1
if uncluster:
multiplier = clusteredReadCounts[currentRead]
# where does the count for this read go
countHitsForRead(hits, counts, multiplier=multiplier)
# apply cutoff
if arguments.cutoff > 0:
applyFractionalCutoff(counts, threshold=arguments.cutoff * readCount)
# print output
if arguments.outfile is None:
outhandle = sys.stdout
else:
outhandle = open(arguments.outfile, 'w')
if arguments.total:
outhandle.write("Total%s%d\n" % (arguments.delimOut, readCount))
if arguments.allMethod == 'portion':
outFmtString = "%s%s%f\n"
else:
outFmtString = "%s%s%d\n"
delimRE = re.compile(arguments.delimOut)
for hit in sorted(counts.keys()):
count = counts[hit]
hit = delimRE.sub('_', hit)
outhandle.write(outFmtString % (hit, arguments.delimOut, count))
if __name__ == '__main__':
main()