/
evo_sampling.py
240 lines (228 loc) · 8.69 KB
/
evo_sampling.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
"""perform exact evolutionary sampling via CFTP"""
import random
from tqdm import *
from math import exp, log
from scipy import polyfit, poly1d
from formosa_utils import sorted_indices, subst, mutate_site, seq_scorer, argmin
from formosa_utils import argmax, rslice, sigma_from_matrix, pssm_from_motif
from formosa_utils import psfm_from_motif, motif_ic, sample_matrix, approx_mu
from formosa_utils import mean, matrix_from_motif, occupancies
def sample_motif_cftp(matrix, mu, Ne, n,verbose=False):
iterator = trange(n,desc="sampling cftp motif") if verbose else xrange(n)
return [sample_site_cftp(matrix, mu, Ne)
for i in iterator]
def sample_site_cftp(matrix, mu, Ne):
L = len(matrix)
f = seq_scorer(matrix)
def log_phat(s):
ep = f(s)
nu = Ne - 1
return -nu*log(1 + exp(ep - mu))
best_site = "".join(["ACGT"[argmin(row)] for row in matrix])
worst_site = "".join(["ACGT"[argmax(row)] for row in matrix])
#middle_sites = [[random_site(L)] for i in range(10)]
#trajs = [[best_site]] + middle_sites + [[worst_site]]
trajs = [[best_site],[worst_site]]
ords = [rslice("ACGT",sorted_indices(row)) for row in matrix]
def mutate_site(site,(ri,direction)):
b = (site[ri])
idx = ords[ri].index(b)
idxp = min(max(idx + direction,0),3)
bp = ords[ri][idxp]
return subst(site,bp,ri)
iterations = 1
rs = [(random.randrange(L),random.choice([-1,1]),random.random())
for i in range(iterations)]
converged = False
while not converged:
trajs = [[best_site],[worst_site]] # added Wed Mar 30 15:26:03 EDT 2016
for ri, rdir, r in rs:
for traj in trajs:
x = traj[-1]
xp = mutate_site(x,(ri, rdir))
if log(r) < log_phat(xp) - log_phat(x):
x = xp
traj.append(x)
if trajs[0][-1] == trajs[-1][-1]:
converged = True
iterations *= 2
#print iterations,[traj[-1] for traj in trajs]
rs = [(random.randrange(L),random.choice([-1,1]),random.random())
for i in range(iterations)] + rs
assert all(map(lambda traj:traj[-1] == trajs[0][-1],trajs))
return trajs[0][-1]
#return trajs
def sample_motif_ar(matrix, mu, Ne, N):
L = len(matrix)
ep_min = sum(map(min, matrix))
nu = Ne - 1
des_ep = max(mu - log(nu), ep_min + 1)
def f(lamb):
psfm = psfm_from_matrix(matrix, lamb)
return sum((sum(ep*p for ep, p in zip(eps,ps)) for (eps, ps) in zip(matrix, psfm))) - des_ep
lamb = bisect_interval(f,-20,20)
return [sample_site_ar(matrix, mu, Ne, lamb=lamb) for i in range(N)]
def sample_site_ar(matrix, mu, Ne, lamb=None):
L = len(matrix)
nu = Ne - 1
des_ep = mu - log(nu)
if lamb is None:
def f(lamb):
psfm = psfm_from_matrix(matrix, lamb)
return sum((sum(ep*p for ep, p in zip(eps,ps)) for (eps, ps) in zip(matrix, psfm))) - des_ep
lamb = bisect_interval(f,-20,20)
psfm = psfm_from_matrix(matrix, lamb)
log_psfm = [map(log,row) for row in psfm]
def log_P(site):
ep = score_seq(matrix, site)
return -nu * log(1+exp(ep-mu))
while True:
site = sample_from_psfm(psfm)
log_ar = log_P(site) + -L*log(4) - score_seq(log_psfm, site)
if log(random.random()) < log_ar:
return site
def sample_motif_rocftp(matrix, mu, Ne, N, block_length=None):
L = len(matrix)
f = seq_scorer(matrix)
if block_length is None:
block_length = 10 * L
def log_phat(s):
ep = f(s)
nu = Ne - 1
return -nu*log(1 + exp(ep - mu))
best_site = "".join(["ACGT"[argmin(row)] for row in matrix])
worst_site = "".join(["ACGT"[argmax(row)] for row in matrix])
ords = [rslice("ACGT",sorted_indices(row)) for row in matrix]
#middle_sites = [[random_site(L)] for i in range(10)]
#trajs = [[best_site]] + middle_sites + [[worst_site]]
def mutate_site(site,(ri,direction)):
b = (site[ri])
idx = ords[ri].index(b)
idxp = min(max(idx + direction,0),3)
bp = ords[ri][idxp]
return subst(site,bp,ri)
iterations = 1
trajs = [[best_site],[worst_site]]
def rr():
return (random.randrange(L),random.choice([-1,1]),random.random())
converged = False
sites = []
sample = None
last_sample = None
while len(sites) < N:
#print len(sites)
if sample is None:
trajs = [best_site, worst_site]
else:
trajs = [best_site, worst_site, sample]
for t in xrange(block_length):
ri, rdir, r = rr()
for i, x in enumerate(trajs):
xp = mutate_site(x,(ri, rdir))
if log(r) < log_phat(xp) - log_phat(x):
x = xp
trajs[i] = x
if trajs[0] == trajs[1]:
if not sample is None:
sites.append(last_sample)
else:
sample = trajs[0]
trajs.append(sample)
last_sample = trajs[2] if len(trajs) == 3 else None
#print "last sample:", last_sample
#print iterations,[traj[-1] for traj in trajs]
return sites
#return trajs
def spoof_motif_cftp(motif, num_motifs=10, trials=1, sigma=None,Ne_tol=10**-2,verbose=False):
n = len(motif)
L = len(motif[0])
copies = 10*n
if sigma is None: sigma = sigma_from_matrix(pssm_from_motif(motif,pc=1))
print "sigma:", sigma
bio_ic = motif_ic(motif)
matrix = sample_matrix(L, sigma)
mu = approx_mu(matrix, copies=10*n, G=5*10**6)
print "mu:", mu
def f(Ne):
motifs = [sample_motif_cftp(matrix, mu, Ne, n, verbose=verbose)
for i in trange(trials)]
return mean(map(motif_ic,motifs)) - bio_ic
# lb = 1
# ub = 10
# while f(ub) < 0:
# ub *= 2
# print ub
x0s = [2,10]#(lb + ub)/2.0
# print "choosing starting seed for Ne"
# fs = map(lambda x:abs(f(x)),x0s)
# print "starting values:",x0s,fs
# x0 = x0s[argmin(fs)]
# print "chose:",x0
# Ne = bisect_interval_noisy_ref(f,x0,lb=1,verbose=True)
Ne = log_regress_spec2(f,x0s,tol=Ne_tol)
print "Ne:",Ne
return [sample_motif_cftp(matrix, mu, Ne, n) for _ in trange(num_motifs)]
def spoof_motif_cftp_occ(motif, num_motifs=10, trials=1, sigma=None,Ne_tol=10**-2,verbose=False):
"""spoof motifs based on occupancy rather than motif IC"""
N = len(motif)
L = len(motif[0])
copies = 10*N
pssm = pssm_from_motif(motif,pc=1)
if sigma is None: sigma = sigma_from_matrix(pssm)
print "sigma:", sigma
matrix = sample_matrix(L, sigma)
bio_matrix = matrix_from_motif(motif)
mu = approx_mu(matrix, copies=copies, G=5*10**6)
mean_bio_occ = mean(occupancies(motif))
print "mu:", mu
def f(Ne):
motifs = [sample_motif_cftp(matrix, mu, Ne, N, verbose=verbose)
for i in trange(trials)]
return mean(map(lambda m:mean(occupancies(m)), motifs)) - mean_bio_occ
# lb = 1
# ub = 10
# while f(ub) < 0:
# ub *= 2
# print ub
x0s = [2,10]#(lb + ub)/2.0
# print "choosing starting seed for Ne"
# fs = map(lambda x:abs(f(x)),x0s)
# print "starting values:",x0s,fs
# x0 = x0s[argmin(fs)]
# print "chose:",x0
# Ne = bisect_interval_noisy_ref(f,x0,lb=1,verbose=True)
Ne = log_regress_spec2(f,x0s,tol=Ne_tol)
print "Ne:",Ne
return [sample_motif_cftp(matrix, mu, Ne, N) for _ in trange(num_motifs)]
def log_regress_spec2(f,xs, tol=0.01, diagnose=False):
"""find root f(x) = 0 using logistic regression, starting with xs, using weighted regression"""
print "initial seeding for log_regress (weighted)"
ys = map(f,xs)
log_xs = map(log,xs)
plotting = False
honest_guesses = []
while len(honest_guesses) < 2 or abs(honest_guesses[-1] -
honest_guesses[-2]) > tol:
m, b = weighted_regress(log_xs,ys)
honest_guess = -b/m
dx = 0#-(honest_guesses[-1] - honest_guess) if honest_guesses else 0
log_xp = honest_guess + 2*dx
log_xs.append(log_xp)
yxp = f(exp(log_xp))
ys.append(yxp)
honest_guesses.append(honest_guess)
diff = (abs((honest_guesses[-1]) - (honest_guesses[-2]))
if len(honest_guesses) > 1 else None)
print "honest_guess:",(honest_guess),"xp:",(log_xp),\
"y:",yxp, "diff:",diff
m, b = weighted_regress(log_xs,ys)
log_xp = -b/m
print "final guess: log_xp:",log_xp
if diagnose:
return log_xs,ys
else:
return exp(log_xp)
def weighted_regress(xs,ys):
avg_yval = mean(map(abs,ys))
ws = [exp(-abs(y)/avg_yval) for y in ys]
return (polyfit(xs,ys,1,w=ws))