forked from salilab/SOAP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcmc.py
420 lines (384 loc) · 18.7 KB
/
mcmc.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
"""
SOAP Markov Chain Monte Carlo
"""
from env import *
class MyMCMC(MCMC):
def restore_sm_state(self):
pass
class MMetropolis(Metropolis): #discrete anchor points and lower limit on the scale factor
def __init__(self, stochastic, blockind=-999, scale=1., proposal_sd=None, proposal_distribution=None, verbose=1, tally=True, check_before_accepting=True):
# Metropolis class initialization
# Initialize superclass
StepMethod.__init__(self, [stochastic], tally=tally)
self.blockind=blockind
# Initialize hidden attributes
self.adaptive_scale_factor = 1.
self.accepted = 0.
self.rejected = 0.
self._state = ['rejected', 'accepted', 'adaptive_scale_factor', 'proposal_sd', 'proposal_distribution', 'check_before_accepting']
self._tuning_info = ['adaptive_scale_factor']
self.check_before_accepting = check_before_accepting
# Set public attributes
self.stochastic = stochastic
if verbose is not None:
self.verbose = verbose
else:
self.verbose = stochastic.verbose
if proposal_distribution != "Prior":
# Avoid zeros when setting proposal variance
if proposal_sd is not None:
self.proposal_sd = proposal_sd
else:
if all(self.stochastic.value != 0.):
self.proposal_sd = np.ones((self.stochastic.value.shape)) * np.abs(self.stochastic.value) * scale
else:
self.proposal_sd = ones(shape(self.stochastic.value)) * scale
# Initialize proposal deviate with array of zeros
self.proposal_deviate = np.zeros((self.stochastic.value.shape), dtype=float)
# Determine size of stochastic
if isinstance(self.stochastic.value, np.ndarray):
self._len = len(self.stochastic.value.ravel())
else:
self._len = 1
self.proposal_distribution='Normal'
self.blockind=blockind
def propose(self):
"""
This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified).
"""
runenv.stepblockind=self.blockind
if self.proposal_distribution == "Normal":
self.stochastic.value = rnormal(self.stochastic.value, self.adaptive_scale_factor * self.proposal_sd, size=self.stochastic.value.shape)
elif self.proposal_distribution == "Prior":
self.stochastic.random()
class MyMetropolis(Metropolis):
def __init__(self, stochastic, parindex, proposemethod, proposepars, blockind=-999, searchind=[],scale=1, proposal_sd=None, proposal_distribution=None, verbose=1, tally=True, check_before_accepting=True):
# Metropolis class initialization
# Initialize superclass
StepMethod.__init__(self, [stochastic], tally=tally)
self.blockind=blockind
if self.blockind>=0:
self.searchind=searchind
parindexstart=parindex[searchind[0]]
parindex=[par-parindexstart for par in parindex]
proposemethod=proposemethod[searchind[0]:searchind[-1]+1]
proposepars=proposepars[searchind[0]:searchind[-1]+1]
else:
self.searchind=range(len(proposemethod))
# Initialize hidden attributes
self.adaptive_scale_factor = 0.5
self.accepted = 0.
self.rejected = 0.
self._state = ['rejected', 'accepted', 'adaptive_scale_factor', 'proposal_sd', 'proposal_distribution', 'check_before_accepting']
self._tuning_info = ['adaptive_scale_factor']
self.check_before_accepting = check_before_accepting
# Set public attributes
self.stochastic = stochastic
if verbose is not None:
self.verbose = verbose
else:
self.verbose = stochastic.verbose
self.parindex=parindex
self.proposemethod=proposemethod
self.proposepars=proposepars
self.proposevalue=np.zeros(self.stochastic.value.shape)
for i in range(len(self.parindex)-1):
if self.proposemethod[i] == "splineparn":
numofpars=self.proposepars[i][2]
parmean=self.proposepars[i][3]
parstd=parmean*scale
cov=np.zeros([numofpars-1,numofpars-1])+parstd**2/(numofpars)
for j in range(numofpars-1):
cov[j,j]-=parstd**2
self.proposepars[i].append(cov)
if proposal_distribution != "Prior":
# Avoid zeros when setting proposal variance
if proposal_sd is not None:
self.proposal_sd = proposal_sd
else:
if all(self.stochastic.value != 0.):
self.proposal_sd = np.ones((self.stochastic.value.shape)) * np.abs(self.stochastic.value) * scale
else:
self.proposal_sd = ones(shape(self.stochastic.value)) * scale
# Initialize proposal deviate with array of zeros
self.proposal_deviate = np.zeros((self.stochastic.value.shape), dtype=float)
# Determine size of stochastic
if isinstance(self.stochastic.value, np.ndarray):
self._len = len(self.stochastic.value.ravel())
else:
self._len = 1
self.proposal_distribution='Normal'
def tune(self, divergence_threshold=1e10, verbose=0):
"""
Tunes the scaling parameter for the proposal distribution
according to the acceptance rate of the last k proposals:
Rate Variance adaptation
---- -------------------
<0.001 x 0.1
<0.05 x 0.5
<0.2 x 0.9
>0.5 x 1.1
>0.75 x 2
>0.95 x 10
This method is called exclusively during the burn-in period of the
sampling algorithm.
May be overridden in subclasses.
"""
if self.verbose is not None:
verbose = self.verbose
if self.verbose is not None:
verbose = self.verbose
# Verbose feedback
if verbose > 0:
print '\t%s tuning:' % self._id
print '\t\tadaptive scale factor(old):', self.adaptive_scale_factor
# Flag for tuning state
tuning = True
# Calculate recent acceptance rate
if not (self.accepted + self.rejected): return tuning
acc_rate = self.accepted / (self.accepted + self.rejected)
print self.accepted
print self.rejected
print "Tunning with acc_rate_ratio "+str(runenv.acc_rate_ratio)
acc_rate=acc_rate*runenv.acc_rate_ratio
# Switch statement
if acc_rate<0.001:
# reduce by 90 percent
self.adaptive_scale_factor *= 0.1
elif acc_rate<0.05:
# reduce by 50 percent
self.adaptive_scale_factor *= 0.5
elif acc_rate<0.2:
# reduce by ten percent
self.adaptive_scale_factor *= 0.9
elif acc_rate>0.95:
# increase by factor of ten
self.adaptive_scale_factor *= 10.0
elif acc_rate>0.75:
# increase by double
self.adaptive_scale_factor *= 2.0
elif acc_rate>0.5:
# increase by ten percent
self.adaptive_scale_factor *= 1.1
else:
tuning = False
if self.adaptive_scale_factor>0.5:
self.adaptive_scale_factor=0.5
elif self.adaptive_scale_factor<0.00001:
self.adaptive_scale_factor=0.00001
# Re-initialize rejection count
self.rejected = 0.
self.accepted = 0.
# More verbose feedback, if requested
if verbose > 0:
if hasattr(self, 'stochastic'):
print '\t\tvalue:', self.stochastic.value
print '\t\tacceptance rate:', acc_rate
print '\t\tadaptive scale factor:', self.adaptive_scale_factor
print
return tuning
def propose(self):
"""
This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified).
"""
runenv.stepblockind=self.blockind
pvalue=np.copy(self.proposevalue)
for i in range(len(self.proposemethod)):
if self.proposemethod[i] == "pnormal":
while True:
value=np.random.normal(self.stochastic.value[self.parindex[i]:self.parindex[i+1]], self.adaptive_scale_factor * self.proposal_sd[self.parindex[i]:self.parindex[i+1]])
if np.all(value>0):
break
pvalue[self.parindex[i]:self.parindex[i+1]]=value
#print value
elif self.proposemethod[i] == "splineparn":
while True:
sv=self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
svr=np.copy(sv)
svr[:-1]=sv[1:]-sv[:-1]
value=np.random.multivariate_normal(svr[:-1],self.proposepars[i][-1]*(self.adaptive_scale_factor**2))
if np.any(value<=0):
continue
parvalue=value.cumsum()+self.proposepars[i][0]
if parvalue[-1]<self.proposepars[i][1]:
break
#print value
#print parvalue
pvalue[self.parindex[i]+1:self.parindex[i+1]]=parvalue
pvalue[self.parindex[i]]=self.proposepars[i][0]
self.stochastic.value=pvalue
class MxMetropolis(MyMetropolis): #discrete anchor points
def __init__(self, stochastic, parindex, proposemethod, proposepars, blockind=-999, searchind=[],scale=1., proposal_sd=None, proposal_distribution=None, verbose=mcverbose, tally=True, check_before_accepting=True):
# Metropolis class initialization
# Initialize superclass
StepMethod.__init__(self, [stochastic], tally=tally)
self.blockind=blockind
if self.blockind>=0:
self.searchind=searchind
parindexstart=parindex[searchind[0]]
parindex=[par-parindexstart for par in parindex]
parindex=parindex[searchind[0]:searchind[-1]+2]
proposemethod=proposemethod[searchind[0]:searchind[-1]+1]
proposepars=proposepars[searchind[0]:searchind[-1]+1]
else:
self.searchind=range(len(proposemethod))
# Initialize hidden attributes
self.adaptive_scale_factor = 1.
self.accepted = 0.
self.rejected = 0.
self._state = ['rejected', 'accepted', 'adaptive_scale_factor', 'proposal_sd', 'proposal_distribution', 'check_before_accepting']
self._tuning_info = ['adaptive_scale_factor']
self.check_before_accepting = check_before_accepting
# Set public attributes
self.stochastic = stochastic
if verbose is not None:
self.verbose = verbose
else:
self.verbose = stochastic.verbose
self.parindex=parindex
self.proposemethod=proposemethod
self.proposepars=proposepars
print self.proposepars
self.proposevalue=np.zeros(self.stochastic.value.shape)
for i in range(len(self.parindex)-1):
if self.proposemethod[i] == "splineparn":
numofpars=self.proposepars[i][2]
parmean=self.proposepars[i][3]-self.proposepars[i][4]
parstd=parmean*scale
cov=np.zeros([numofpars,numofpars])+parstd**2/(numofpars+1)
for j in range(numofpars):
cov[j,j]-=parstd**2
self.proposepars[i].append(cov)
if proposal_distribution != "Prior":
# Avoid zeros when setting proposal variance
if proposal_sd is not None:
self.proposal_sd = proposal_sd
else:
if all(self.stochastic.value != 0.):
self.proposal_sd = np.ones((self.stochastic.value.shape)) *np.abs(self.stochastic.value) * scale
else:
self.proposal_sd = ones(shape(self.stochastic.value)) * scale
# Initialize proposal deviate with array of zeros
self.proposal_deviate = np.zeros((self.stochastic.value.shape), dtype=float)
# Determine size of stochastic
if isinstance(self.stochastic.value, np.ndarray):
self._len = len(self.stochastic.value.ravel())
else:
self._len = 1
self.proposal_distribution='Normal'
def propose(self):
"""
This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified).
"""
runenv.stepblockind=self.blockind
pvalue=np.copy(self.proposevalue)
#print self.proposal_sd
for i in range(len(self.proposemethod)):
if self.proposemethod[i] == "pnormal":
#print "pnormal"
#print self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
#print self.proposal_sd[self.parindex[i]:self.parindex[i+1]]
value=np.random.normal(list(self.stochastic.value[self.parindex[i]:self.parindex[i+1]]), list(self.adaptive_scale_factor * self.proposal_sd[self.parindex[i]:self.parindex[i+1]]))
#print value
while np.any(value<0):
boolfilter=(value<0)
partvalue=np.random.normal(self.stochastic.value[self.parindex[i]:self.parindex[i+1]][boolfilter], self.adaptive_scale_factor * self.proposal_sd[self.parindex[i]:self.parindex[i+1]][boolfilter])
value[boolfilter]=partvalue
#print value
pvalue[self.parindex[i]:self.parindex[i+1]]=value
#print value
elif self.proposemethod[i] == "normal":
#print "pnormal"
#print self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
#print self.proposal_sd[self.parindex[i]:self.parindex[i+1]]
value=np.random.normal(list(self.stochastic.value[self.parindex[i]:self.parindex[i+1]]), list(self.adaptive_scale_factor * self.proposal_sd[self.parindex[i]:self.parindex[i+1]]))
pvalue[self.parindex[i]:self.parindex[i+1]]=value
#print value
elif self.proposemethod[i] == "splineparn":
#print "splineparn"
#print self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
#print self.proposepars[i][-1]
binsize=self.proposepars[i][4]
k=0
success=False
while k<200:
k+=1
sv=self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
svr=np.array([self.proposepars[i][0]]+list(sv))
svr[:-1]=svr[1:]-svr[:-1]
svr=svr-binsize
value=np.random.multivariate_normal(svr[:-1],self.proposepars[i][-1]*(self.adaptive_scale_factor**2))
#print value
if np.any(value<=0):
continue
value=value+binsize
parvalue=value.cumsum()+self.proposepars[i][0]
if parvalue[-1]<(self.proposepars[i][1]-binsize):
success=True
break
#print value
#print parvalue
if success:
parvalue=np.round((parvalue-self.proposepars[i][0])/binsize)*binsize+self.proposepars[i][0]
pvalue[self.parindex[i]:self.parindex[i+1]]=parvalue
else:
pvalue[self.parindex[i]:self.parindex[i+1]]=self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
#print parvalue
#pvalue[self.parindex[i]]=self.proposepars[i][0]
self.stochastic.value=pvalue
class MzMetropolis(MxMetropolis): #discrete anchor points and lower limit on the scale factor
def __init__(self, stochastic, parindex, proposemethod, proposepars, blockind=-999,scale=1., proposal_sd=None, proposal_distribution=None, verbose=1, tally=True, check_before_accepting=True):
# Metropolis class initialization
# Initialize superclass
MxMetropolis.__init__(self, stochastic, parindex, proposemethod, proposepars,blockind, scale, proposal_sd, proposal_distribution, verbose, tally, check_before_accepting)
self.scale_factor_min=[]
for i in range(len(self.parindex)-1):
if self.proposemethod[i] == "splineparn":
parmean=self.proposepars[i][3]-self.proposepars[i][4]
self.scale_factor_min.append(0.5*(self.proposepars[i][4]/(scale*parmean)))
else:
self.scale_factor_min.append(0.001)
def propose(self):
"""
This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified).
"""
runenv.stepblockind=self.blockind
pvalue=np.copy(self.proposevalue)
for i in range(len(self.proposemethod)):
if self.adaptive_scale_factor<self.scale_factor_min[i]:
print "using minscalefactor"
scalefactor=self.scale_factor_min[i]
else:
scalefactor=self.adaptive_scale_factor
if self.proposemethod[i] == "pnormal":
while True:
value=np.random.normal(self.stochastic.value[self.parindex[i]:self.parindex[i+1]], scalefactor * self.proposal_sd[self.parindex[i]:self.parindex[i+1]])
if np.all(value>0):
break
pvalue[self.parindex[i]:self.parindex[i+1]]=value
#print value
elif self.proposemethod[i] == "splineparn":
binsize=self.proposepars[i][4]
while True:
sv=self.stochastic.value[self.parindex[i]:self.parindex[i+1]]
svr=np.copy(sv)
svr[:-1]=sv[1:]-sv[:-1]
svr=svr-binsize
value=np.random.multivariate_normal(svr[:-1],self.proposepars[i][-1]*(scalefactor**2))
if np.any(value<=0):
continue
value=value+binsize
parvalue=value.cumsum()+self.proposepars[i][0]
if parvalue[-1]<(self.proposepars[i][1]-binsize):
break
#print value
#print parvalue
parvalue=np.round((parvalue-self.proposepars[i][0])/binsize)*binsize+self.proposepars[i][0]
#print parvalue
pvalue[self.parindex[i]+1:self.parindex[i+1]]=parvalue
pvalue[self.parindex[i]]=self.proposepars[i][0]
self.stochastic.value=pvalue