def metropolis_pb(ks,q,verbose=False,mu_offset=0,iterations=50000): """Metropolis-Hastings sampling for ks, given product-bernoulli proposal function""" G = len(ks) eps = [-log(k) for k in ks] f = lambda mu:sum(fd(ep,mu) for ep in eps) - q mu = bisect_interval(f,-50,50) + mu_offset def weight(ss): return (falling_fac(q,sum(ss))*product(k**s for k,s in zip(ks,ss))) def proposal(ss): #state = [int(random.random() < p) for _ in range(len(ss))] state = rstate(eps,mu) #print "proposed state with occ:",sum(state) return state def dprop(ss): prop = dstate(ss,eps,mu) #print "prop:",prop return prop x0 = proposal([0] * len(ks)) return mh(weight,proposal,x0,dprop=dprop,verbose=verbose,iterations=iterations)
def metropolis_uniform(ks,q,verbose=False,mu_offset=0,iterations=50000): """Metropolis-Hastings sampling for ks, given uniform proposal function""" G = len(ks) eps = [-log(k) for k in ks] f = lambda mu:sum(fd(ep,mu) for ep in eps) - q mu = bisect_interval(f,-50,50) + mu_offset def weight(ss): return (falling_fac(q,sum(ss))*product(k**s for k,s in zip(ks,ss))) def proposal(ss): on_chr_prob = sum(ss)/float(q) on_chr = random.random() < on_chr_prob ss_new = ss[:] if on_chr: pos = random.choice([i for (i,s) in enumerate(ss) if s]) ss_new[pos] = 0 new_pos = random.choice([-1] + [i for (i,s) in enumerate(ss) if not s]) if new_pos >= 0: ss_new[new_pos] = 1 return ss_new x0 = proposal([0] * len(ks)) return mh(weight,proposal,x0,verbose=verbose,iterations=iterations)