def mcfit(logpost,bounds,args=(),sampler=None,proposal=None,N=10000,burnin=1000,seed=None,outfile=None): """ Fit args using MCMC and return samples from the PDF. """ if sampler == None: # sampler = MCSampler() sampler = EnsembleSampler(100) try: bounds = np.array(bounds) # if np.shape(bounds)[1] != 2: # raise MCError("provide bounds on the parameter space") if proposal == None: proposal = (bounds[:,1]-bounds[:,0])/10. return sampler.sample_pdf(logpost,bounds,proposal,N,burnin,args,outfile=outfile,seed=None) except (MCError,ProposalErr): # as e: print "MCMC exception raised with message: "+e.value
def mcfit(lnposteriorfn,p0,args=(),sampler=None,N=1000,burnin=0,outfile=None): """ Performs a (kitchen-sink) MCMC to sampler a provided posterior PDF """ #Required Arguments: # `lnposteriorfn` # a function that returns the value of posterior PDF # at the position `p` when called # `lnposteriorfn(p,args)` where `args` is the unpacked # optional keyword argument of `mcfit` # p0 # #Optional Arguments: # args=() # sampler=None # N=1000 # burnin=0 # outfile=None # #""" p0 = np.array(p0) if sampler == None: sampler = EnsembleSampler(np.shape(p0)[0],np.shape(p0)[1], lnposteriorfn,postargs=args,outfile=outfile) pos = p0 state = None if burnin > 0: print "Running: first burn-in pass" pos,prob,state = sampler.run_mcmc(pos,state,burnin/2) pos,prob,state = sampler.clustering(pos,prob,state) print "Running: second burn-in pass" pos,prob,state = sampler.run_mcmc(pos,state,burnin/2) pos,prob,state = sampler.clustering(pos,prob,state) sampler.clear_chain() print "Running: final Markov chain (%d links)"%(N) sampler = EnsembleSampler(np.shape(p0)[0],np.shape(p0)[1],lnposteriorfn, postargs=args,outfile=outfile) sampler.run_mcmc(pos,state,N) frac = np.mean(sampler.acceptance_fraction()) if frac < 0.1: print "Warning: acceptance fraction < 10%" else: print "Acceptance fraction: %.3f"%frac return sampler.chain,sampler.probability,frac