-
Notifications
You must be signed in to change notification settings - Fork 0
/
pair_frequency.py
executable file
·201 lines (153 loc) · 5.27 KB
/
pair_frequency.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
#!/usr/bin/python
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import string
import os
import optparse
import numpy
import math
import random
import re
import time
from subprocess import call, Popen, PIPE
from itertools import product
from libkmersvm import *
import difflib
def get_overlaps(x,y):
x_overlaps = []
y_overlaps = []
#check left of x right of y
for i in xrange(1, len(x)):
if x[:i] == y[-i:]:
x_overlaps.append(x[:i])
#check left of x right of y
for i in xrange(1, len(y)):
if y[:i] == x[-i:]:
y_overlaps.append(y[:i])
return x_overlaps, y_overlaps
def get_longest_overlap(x,y,k):
max_overlap = ''
x_overlaps, y_overlaps = get_overlaps(x,y)
for i in x_overlaps:
if len(i) > len(max_overlap) and len(i) < k:
max_overlap = i
for i in y_overlaps:
if len(i) > len(max_overlap) and len(i) < k:
max_overlap = i
return max_overlap
def get_pair_frequencies(seqs, k, w):
pair_freq = {}
total = 0.0
for seq in seqs:
total += (len(seq)-w+1)*(w-k)
test = 0.0
progress_count = 0
t = len(seqs)
for seq in seqs:
if progress_count % math.ceil(t/10000.0) == 0:
p = (float(progress_count)/t)*100
sys.stderr.write("\r%.2f%% progress. " % p)
sys.stderr.flush()
progress_count += 1
for i in xrange(0, len(seq)-w+1):
a = seq[i:i+k]
window = seq[i+1:i+w]
for j in xrange(0, len(window)-k+1):
b = window[j:j+k]
test += 1.0
if (a,b) in pair_freq:
pair_freq[(a,b)] += 1.0/total
elif (b,a) in pair_freq:
pair_freq[(b,a)] += 1.0/total
else:
pair_freq[(a,b)] = 1.0/total
sys.stderr.write("\n")
return pair_freq,total
def get_pair_scores(pair_freqs,freqs,k,w,total):
pair_scores = {}
for (p,v) in pair_freqs.items():
(a,b) = p
f_a = freqs[len(a)-1][a]
f_b = freqs[len(b)-1][b]
exp = 0.0
#approximation: consider biggest overlap
overlap = get_longest_overlap(a,b,k)
l = len(overlap)
if l > 0:
if a[:l] == overlap:
exp += f_b * freqs[len(a[l:])-1][a[l:]]
elif b[:l] == overlap:
exp += f_a * freqs[len(b[l:])-1][b[l:]]
else:
exp += f_a*f_b
score = v/exp
pair_scores[(a,b)] = score
return pair_scores
def save_results(pair_scores, pair_freq, freq, output):
pstat = []
for (p,v) in pair_scores.items():
(a,b) = p
f_a = freq[len(a)-1][a]
f_b = freq[len(b)-1][b]
f_ab = 0.0
if (a,b) in pair_freq:
f_ab = pair_freq[(a,b)]
else:
f_ab = pair_freq[(b,a)]
pstat.append( (a,b,f_a,f_b,f_ab,v) )
out = sorted(pstat, key=lambda p: p[5], reverse=True)
f = open(output, 'w')
f.write('\t'.join(["seq1", "seq2","f1","f2","f_12","score"]) + "\n")
for (a,b,f_a,f_b,f_ab,v) in out:
f.write('\t'.join([a, b, str(f_a), str(f_b), str(f_ab), str(v)]) + "\n")
f.close()
def get_frequencies(seqs, k):
freqs = {}
total = 0.0
for seq in seqs:
total += len(seq)-k+1
for seq in seqs:
for i in xrange(0, len(seq)-k+1):
kmer = seq[i:i+k]
if kmer not in freqs:
freqs[kmer] = 0.0
freqs[kmer] += 1.0/total
return freqs
def main(argv = sys.argv):
usage = "Usage: %prog [options] SEQ_FILE OUTPUT_NAME"
parser = optparse.OptionParser(usage=usage)
parser.add_option("-k", dest="kmerlen", type=int, \
help="set kmer length", default=6)
parser.add_option("-w", dest="window", type=int, \
help="set window length", default=50)
parser.add_option("-q", dest="quiet", default=False, action="store_true", \
help="supress messages (default=false)")
(options, args) = parser.parse_args()
if len(args) == 0:
parser.print_help()
sys.exit(0)
if len(args) != 2:
parser.error("incorrect number of arguments")
parser.print_help()
sys.exit(0)
seqf = args[0]
outm = args[1]
seqs, sids = read_fastafile(seqf)
freqs = [{}] * (options.kmerlen)
for i in xrange(0,options.kmerlen):
freqs[i] = get_frequencies(seqs, i+1)
pair_freq, total = get_pair_frequencies(seqs,options.kmerlen,options.window)
pair_scores = get_pair_scores(pair_freq,freqs,options.kmerlen,options.window,total)
save_results(pair_scores,pair_freq,freqs,outm)
if __name__ =='__main__': main()