forked from enormandeau/Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fasta_count_kmers.py
executable file
·70 lines (58 loc) · 1.77 KB
/
fasta_count_kmers.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
#!/usr/bin/env python
"""Return frequency of kmers present in a fasta file
Usage:
python fasta_count_kmer.py genome_file kmer_length
"""
# Importing modules
from signal import signal, SIGPIPE, SIG_DFL
from collections import defaultdict
import sys
# Defining classes
class Fasta(object):
"""Fasta object with name and sequence
"""
def __init__(self, name, sequence):
self.name = name
self.sequence = sequence
def write_to_file(self, handle):
handle.write(">" + self.name + "\n")
handle.write(self.sequence + "\n")
# Defining functions
def fasta_iterator(input_file):
"""Takes a fasta file input_file and returns a fasta iterator
"""
with open(input_file) as f:
sequence = ""
name = ""
begun = False
for line in f:
line = line.strip()
if line.startswith(">"):
if begun:
yield Fasta(name, sequence)
name = line.replace(">", "")
sequence = ""
begun = True
else:
sequence += line
yield Fasta(name, sequence)
if __name__ == '__main__':
# Prevent broken pipe error
signal(SIGPIPE, SIG_DFL)
# Parse user input
try:
input_file = sys.argv[1]
kmer_length = int(sys.argv[2])
except:
print __doc__
sys.exit(1)
# Cound kmers
kmer_dict = defaultdict(int)
for seq in fasta_iterator(input_file):
for start in xrange(0, len(seq.sequence) - kmer_length):
stop = start + kmer_length
kmer_dict[seq.sequence[start: stop]] += 1
kmer_list = sorted([(kmer_dict[k], k) for k in kmer_dict], reverse=True)
# Print results
for kmer in kmer_list:
print kmer[1], kmer[0]