Example #1
0
def MCMC(v1,v2,v3,tdet,s3,Ca0,Cte,t0_actual,Nt):

    import numpy as np
    from posterior import post
    import time
    from juliantime import juliandate
    from progressbar import ProgressBar
    import warnings
    from scipy import stats
    from fileread import readFile
    import matplotlib.pyplot as plt
    from posterior import MT
    from convert import magConvert
    from magfit import magfit
    from scipy.optimize import minimize
    from scipy.optimize import leastsq
    from numpy import linalg as LA

    def fxn():
        warnings.warn("deprecated", DeprecationWarning)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        fxn()

        #initial parameters with arbitrary starting point theta:
        #---------------------------------------------------
        a0 = np.exp(2)
        te = 0.04*np.exp(6)
        ib = 18
        dt = 0.0202*np.exp(6)
        start = time.time()

        #Prior distribution parameters:
        #---------------------------------------------------
        DT = [5.558,1.8226]
        A0 = [0.4023,0.591,0.0124]
        TE = [0.8284,6.0709,1.4283,0.1716,13.7152,1.3578]
        IB = [0.1782,7.4511,3.1355,0.6704,18.89,2.0186,0.1514,28.0466,1.5002]

        #Calibrating Magnification:
        #---------------------------------------------------

        Cdt = t0_actual - tdet
        mcal = MT(v1,Ca0,Cte,Cdt,tdet)
        (a,b) = magfit(v2,mcal)

        #initialising MCMC:
        #---------------------------------------------------
        theta = [dt,a0,te,ib]
        thetaN = np.zeros(4)
        alpha = 0.9
        N = 50000
        p =  post(theta[0],theta[1],theta[2],theta[3],DT,A0,TE,IB,v1,v2,v3,tdet,Nt,a,b)
        samples = []
        pdens = []
        count = 0.0


        pbar = ProgressBar()
        print('\n\n')
        print('==============================================================================')
        print('         Light Curve for MOA '+s3+' Nt = '+str(Nt)+ ' Data Points')
        print('==============================================================================\n')
        print('Progress bar:')
        #------------------------------------------------------------------------------
        #                           -Metropolis-Hastings-
        #------------------------------------------------------------------------------

        for i in pbar(range(N)):

            thetaN = theta + alpha*np.random.normal(size=4)
            if all(thetaN) > 0:

                pn = post(thetaN[0],thetaN[1],thetaN[2],thetaN[3],DT,A0,TE,IB,v1,v2,v3,tdet,Nt,a,b)
                if pn >= p:
                    p = pn
                    theta = thetaN
                    pdens.append(p)
                    #print(thetaN,p,end='\r')
                    count = count + 1
                else:
                    u = np.random.rand()
                    #Modified acceptance ratio to allow for truncation.
                    accMod = (stats.norm.cdf(theta[0])*stats.norm.cdf(theta[1])*stats.norm.cdf(theta[2])*stats.norm.cdf(theta[3]))\
                    /(stats.norm.cdf(thetaN[0])*stats.norm.cdf(thetaN[1])*stats.norm.cdf(thetaN[2])*stats.norm.cdf(thetaN[3]))
                    if u < accMod*pn/p:
                        p = pn
                        theta = thetaN
                        pdens.append(p)
                        #print(thetaN,p,end='\r')
                        count = count + 1

                samples.append(theta)

        #Maximum likelihood:
        #---------------------------------------------------

        xinit = [a0,te,dt]
        xinit = np.array(xinit)

        tl = v1[0:Nt]-tdet
        fl = v2[0:Nt]
        ml = magConvert(fl,a,b)

        objective = lambda x: (ml - (-2 + 2*x[0]*np.sqrt(1/(x[0]**2 - 1))+((tl-x[2])/x[1])**2 + 2)\
        /(np.sqrt((-2 + 2*x[0]*np.sqrt(1/(x[0]**2 - 1))+((tl-x[2])/x[1])**2)**2 \
        +4*((-2 + 2*x[0]*np.sqrt(1/(x[0]**2 - 1))+((tl-x[2])/x[1])**2)))))

        #res = minimize(objective,xinit)
        plsq = leastsq(objective, xinit)
        #print(plsq)

        #Results:
        #---------------------------------------------------

        tt = np.linspace(0,v1[-1]-tdet,1000)
        mdt = samples[pdens.index(max(pdens))][0]
        ma0 = samples[pdens.index(max(pdens))][1]
        mte = samples[pdens.index(max(pdens))][2]
        mib = samples[pdens.index(max(pdens))][3]
        mcon = magConvert(v2,a,b)
        mcon = mcon.tolist()
        acc_ratio = count/N
        samples = np.array(samples)
        elapsedtime = time.time()-start
        final_time = tl[-1]

        #Printing Results:
        #----------------------------------------------------
        if(0):
            print('==============================================')
            print('Report:')
            print('==============================================')
            print('Bayesian Estimate:')
            print('Elapsed time = ' + str(elapsedtime))
            print('t0 = '+str(mdt))
            print('a0 = '+str(ma0))
            print('te = '+str(mte))
            print('ib = '+str(mib))
            print('MAP - '+str(max(pdens)))
            print('Acceptance ratio = '+ str(acc_ratio))
            print('Actual t0 = '+ str(t0_actual - tdet))
            print('==============================================')
            print('Least-squares estimate:')
            print('a0 = '+str(plsq[0][0]))
            print('te = '+str(plsq[0][1]))
            print('t0 = '+str(plsq[0][2]))
            print('==============================================')

        #Plotting Results:
        #----------------------------------------------------
        if(0):
            plt.figure()
            plt.plot(tt,MT(tt+tdet,ma0,mte,mdt,tdet),label='Bayesian prediction')
            plt.plot(v1-tdet,magConvert(v2,a,b),'k.',label='Actual Light Curve')
            plt.plot(tt,MT(tt+tdet,plsq[0][0],plsq[0][1],plsq[0][2],tdet),'grey',label='Least squares')
            plt.plot(final_time*np.ones(100),np.linspace(0,Ca0+1,100),'r',label='Data inclusion point')
            plt.title('Light Curve for MOA '+s3+' with N = '+str(Nt)+' data points')
            plt.legend()
            plt.xlabel('$t$ (days)')
            plt.ylabel('$Magnification$')
            plt.ylim(0,18)
            plt.xlim(0,60)
            plt.show()

        print('Ca0 = '+str(Ca0))
        print('Ba0 = '+str(ma0))
        print('MLa0 = '+str(plsq[0][0]))

        return tdet,ma0,mte,mdt,plsq[0][0],plsq[0][1],plsq[0][2]
Example #2
0
#testing the posterior.

from posterior import post
import matplotlib.pyplot as plt
import numpy as np

DT = [5.558,1.8226]
A0 = [0.4023,0.591,0.0124]
TE = [0.8284,6.0709,1.4283,0.1716,13.7152,1.3578]
IB = [0.1782,7.4511,3.1355,0.6704,18.89,2.0186,0.1514,28.0466,1.5002]

dt = np.linspace(-2,14,1000)
a0 = np.linspace(0.1,20,1000)
te = np.linspace(0,20,1000)
ib = np.linspace(-10,50,1000)

p = post(dt,a0,te,ib,DT,A0,TE,IB)
Example #3
0
    #---------------------------------------------------
    Ca0 = 12.29
    Cte = 60.23
    t0_actual = 2457090.20
    Cdt = t0_actual - tdet
    mcal = MT(v1,Ca0,Cte,Cdt,tdet)
    (a,b) = magfit(v2,mcal)

    #initialising MCMC:
    #---------------------------------------------------
    theta = [dt,a0,te,ib]
    thetaN = np.zeros(4)
    alpha = input('Enter alpha: ')
    N = input('Enter Number of Samples: ')
    Nt = input('Enter the number of data points: ')
    p =  post(theta[0],theta[1],theta[2],theta[3],DT,A0,TE,IB,v1,v2,v3,tdet,Nt,a,b)
    samples = []
    pdens = []
    count = 0.0


    pbar = ProgressBar()
    print('\n\n')
    print('==============================================================================')
    print('     MCMC - N = ' + str(N) + ' samples, alpha =  '+ str(alpha) + ' with Nt = '+str(Nt)+ ' Data Points')
    print('==============================================================================\n')
    print('Progress bar:')
    #------------------------------------------------------------------------------
    #                           -Metropolis-Hastings-
    #------------------------------------------------------------------------------