-
Notifications
You must be signed in to change notification settings - Fork 295
/
abundance-dist-single.py
executable file
·197 lines (166 loc) · 7.26 KB
/
abundance-dist-single.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
#! /usr/bin/env python2
#
# This file is part of khmer, http://github.com/ged-lab/khmer/, and is
# Copyright (C) Michigan State University, 2010-2015. It is licensed under
# the three-clause BSD license; see doc/LICENSE.txt.
# Contact: khmer-project@idyll.org
#
# pylint: disable=invalid-name,missing-docstring
"""
Produce the k-mer abundance distribution for the given file, without
loading a prebuilt k-mer counting table.
% python scripts/abundance-dist-single.py <data> <histout>
Use '-h' for parameter help.
"""
import os
import sys
import csv
import khmer
import threading
import textwrap
from khmer.khmer_args import (build_counting_args, add_threading_args,
report_on_config, info)
from khmer.kfile import (check_file_status, check_space,
check_space_for_hashtable)
def get_parser():
epilog = '''
Note that with :option:`-b` this script is constant memory; in exchange,
k-mer counts will stop at 255. The memory usage of this script with
:option:`-b` will be about 1.15x the product of the :option:`-x` and
:option:`-N` numbers.
To count k-mers in multiple files use :program:`load_into_counting.py` and
:program:`abundance_dist.py`.
'''
parser = build_counting_args(
descr="Calculate the abundance distribution of k-mers from a "
"single sequence file.", epilog=textwrap.dedent(epilog))
add_threading_args(parser)
parser.add_argument('input_sequence_filename', help='The name of the input'
' FAST[AQ] sequence file.')
parser.add_argument('output_histogram_filename', help='The name of the '
'output histogram file. The columns are: (1) k-mer '
'abundance, (2) k-mer count, (3) cumulative count, '
'(4) fraction of total distinct k-mers.')
parser.add_argument('-z', '--no-zero', dest='output_zero', default=True,
action='store_false',
help='Do not output 0-count bins')
parser.add_argument('-b', '--no-bigcount', dest='bigcount', default=True,
action='store_false',
help='Do not count k-mers past 255')
parser.add_argument('-s', '--squash', dest='squash_output', default=False,
action='store_true',
help='Overwrite output file if it exists')
parser.add_argument('--csv', default=False, action='store_true',
help='Use the CSV format for the histogram. '
'Includes column headers.')
parser.add_argument('--savetable', default='', metavar="filename",
help="Save the k-mer counting table to the specified "
"filename.")
parser.add_argument('--report-total-kmers', '-t', action='store_true',
help="Prints the total number of k-mers to stderr")
parser.add_argument('-f', '--force', default=False, action='store_true',
help='Overwrite output file if it exists')
return parser
def main(): # pylint: disable=too-many-locals,too-many-branches
info('abundance-dist-single.py', ['counting', 'SeqAn'])
args = get_parser().parse_args()
report_on_config(args)
check_file_status(args.input_sequence_filename, args.force)
check_space([args.input_sequence_filename], args.force)
if args.savetable:
check_space_for_hashtable(args.n_tables * args.min_tablesize,
args.force)
if (not args.squash_output and
os.path.exists(args.output_histogram_filename)):
print >> sys.stderr, 'ERROR: %s exists; not squashing.' % \
args.output_histogram_filename
sys.exit(1)
else:
hist_fp = open(args.output_histogram_filename, 'w')
if args.csv:
hist_fp_csv = csv.writer(hist_fp)
# write headers:
hist_fp_csv.writerow(['abundance', 'count', 'cumulative',
'cumulative_fraction'])
print >>sys.stderr, 'making k-mer counting table'
counting_hash = khmer.new_counting_hash(args.ksize, args.min_tablesize,
args.n_tables)
counting_hash.set_use_bigcount(args.bigcount)
print >> sys.stderr, 'building k-mer tracking table'
tracking = khmer.new_hashbits(counting_hash.ksize(), args.min_tablesize,
args.n_tables)
print >>sys.stderr, 'kmer_size:', counting_hash.ksize()
print >>sys.stderr, 'k-mer counting table sizes:', \
counting_hash.hashsizes()
print >>sys.stderr, 'outputting to', args.output_histogram_filename
# start loading
rparser = khmer.ReadParser(args.input_sequence_filename)
threads = []
print >>sys.stderr, 'consuming input, round 1 --', \
args.input_sequence_filename
for _ in xrange(args.threads):
thread = \
threading.Thread(
target=counting_hash.consume_fasta_with_reads_parser,
args=(rparser, )
)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if args.report_total_kmers:
print >> sys.stderr, 'Total number of unique k-mers: {0}'.format(
counting_hash.n_unique_kmers())
abundance_lists = []
def __do_abundance_dist__(read_parser):
abundances = counting_hash.abundance_distribution_with_reads_parser(
read_parser, tracking)
abundance_lists.append(abundances)
print >>sys.stderr, 'preparing hist from %s...' % \
args.input_sequence_filename
rparser = khmer.ReadParser(args.input_sequence_filename)
threads = []
print >>sys.stderr, 'consuming input, round 2 --', \
args.input_sequence_filename
for _ in xrange(args.threads):
thread = \
threading.Thread(
target=__do_abundance_dist__,
args=(rparser, )
)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
assert len(abundance_lists) == args.threads, len(abundance_lists)
abundance = {}
for abundance_list in abundance_lists:
for i, count in enumerate(abundance_list):
abundance[i] = abundance.get(i, 0) + count
total = sum(abundance.values())
if 0 == total:
print >> sys.stderr, \
"ERROR: abundance distribution is uniformly zero; " \
"nothing to report."
print >> sys.stderr, "\tPlease verify that the input files are valid."
sys.exit(1)
sofar = 0
for _, i in sorted(abundance.items()):
if i == 0 and not args.output_zero:
continue
sofar += i
frac = sofar / float(total)
if args.csv:
hist_fp_csv.writerow([_, i, sofar, round(frac, 3)])
else:
print >> hist_fp, _, i, sofar, round(frac, 3)
if sofar == total:
break
if args.savetable:
print >>sys.stderr, 'Saving k-mer counting table ', args.savetable
print >>sys.stderr, '...saving to', args.savetable
counting_hash.save(args.savetable)
print >> sys.stderr, 'wrote to: ' + args.output_histogram_filename
if __name__ == '__main__':
main()
# vim: set ft=python ts=4 sts=4 sw=4 et tw=79: