def downhill(prob_func,namefree,parmfree,namefix,parmfix,data,eventinfo,parmref,isspitz,use_color=False,I_minus_L=[]): start = time.clock() tbegin,talert,t0par,t0base,mjd = parmref alpha,delta,oblats,oblongs,obgammas = eventinfo ## compute (qn,qe) once and for all ## qnqe = [] for iob in range(len(data)): date = data[iob][0] qnqe_iob = genlc.getqnqe(date,alpha,delta,t0par,oblats[iob],oblongs[iob],isspitz[iob]) qnqe.append(qnqe_iob) ### Get chi2 based on initial parameters ### # chi2_obs,dof,fsfb = prob_func(parmfree,parmfix,namefree,namefix,data,eventinfo,t0par,isspitz,True,use_color,I_minus_L,qnqe,get_chi2_obs=True) # print chi2_obs,dof # parmbest = fmin(prob_func,parmfree,args=(parmfix,namefree,namefix,data,eventinfo,t0par,isspitz,True,use_color,I_minus_L)) parmbest,chi2min,iter,funcalls,warnflag,allevcs = fmin(prob_func,parmfree,args=(parmfix,namefree,namefix,data,eventinfo,t0par,isspitz,True,use_color,I_minus_L,qnqe),full_output=True,retall=True,maxiter=3000,maxfun=10000) print 'best parameters: ' print namefree print ['%.3f'%iparm for iparm in parmbest]
def mcmc(prob_func,eventname,namefree,parmfree,namefix,parmfix,data,eventinfo,parmref,isspitz,use_color=False,I_minus_L=[]): start = time.clock() tbegin,talert,t0par,t0base,mjd = parmref alpha,delta,oblats,oblongs,obgammas = eventinfo ## compute (qn,qe) once and for all ## qnqe = [] for iob in range(len(data)): date = data[iob][0] qnqe_iob = genlc.getqnqe(date,alpha,delta,t0par,oblats[iob],oblongs[iob],isspitz[iob]) qnqe.append(qnqe_iob) ### Get chi2 based on initial parameters ### # chi2_obs,dof,fsfb = prob_func(parmfree,parmfix,namefree,namefix,data,eventinfo,t0par,isspitz,True,use_color,I_minus_L,qnqe,get_chi2_obs=True) # print chi2_obs,dof ndim = len(parmfree) nwalkers = 30 pos = [parmfree+1e-3*np.random.randn(ndim) for i in range(nwalkers)] sampler = emcee.EnsembleSampler(nwalkers,ndim,prob_func,args=(parmfix,namefree,namefix,data,eventinfo,t0par,isspitz,False,use_color,I_minus_L,qnqe),threads=1) pos,lnprob,rstate = sampler.run_mcmc(pos,100) ## burn in sampler.reset() sampler.run_mcmc(pos,200) ## MCMC sampling ## save the MCMC chain and other useful information ## chain = sampler.chain.reshape((-1,ndim),order='F') chi2s = -2*sampler.lnprobability.reshape(-1,order='F') headerstr = '%s '%namefree[0] for i in range(1,len(namefree)): headerstr += '%s '%namefree[i] np.savetxt('output/mcmc/chain-%s.dat'%eventname,chain,fmt='%f',header=headerstr) np.savetxt('output/mcmc/acceptance-%s'%eventname,sampler.acceptance_fraction,fmt='%f') np.savetxt('output/mcmc/chisq-%s.dat'%eventname,chi2s) ## find the best-fit and error bars ## parmbest = chain[chi2s==min(chi2s)][0] parmmean = np.median(chain,axis=0) parmerrs = np.std(chain,axis=0) print 'best parameters: ' print namefree print ['%.4f'%iparm for iparm in parmbest]