コード例 #1
0
ファイル: posterior.py プロジェクト: peva032/Honours
def post(dt,a0,te,ib,DT,A0,TE,IB,v1,v2,v3,tdet,Nt,a,b):

    import numpy as np
    from juliantime import juliandate
    from posterior import MT
    from fileread import readFile
    from convert import magConvert

    #-------------------------------------------------------------------------
    #                       - Prior distributions -
    #-------------------------------------------------------------------------

    pi_dt = np.exp(-((np.log(dt/0.0202)-DT[0])**2)/(2*DT[1]**2))

    pi_a0 = A0[0]*np.exp(-A0[1]*np.log(np.log(a0)))+A0[2]

    pi_te = TE[0]*np.exp(-((np.log(te/0.04)-TE[1])**2)/(2*TE[2]**2)) + \
    TE[3]*np.exp(-((np.log(te/0.04)-TE[4])**2)/(2*TE[5]**2))

    pi_ib = IB[0]*np.exp(-((ib-IB[1])**2)/(2*IB[2]**2)) + \
    IB[3]*np.exp(-((ib-IB[4])**2)/(2*IB[5]**2)) + \
    IB[6]*np.exp(-((ib-IB[7])**2)/(2*IB[8]**2))

    #-------------------------------------------------------------------------
    #                      - likelihood distribution -
    #-------------------------------------------------------------------------

    t = v1[0:Nt]
    f = v2[0:Nt]
    fsig = v3[0:Nt]

    #Calibration for BLG-004 (Converting to mag units)
    m = magConvert(f,a,b)
    msig = magConvert(fsig,a,b)

    #print('index of peak - '+str((m.tolist()).index(max(m))))

    M = np.zeros(len(m))
    M = MT(t,a0,te,dt,tdet)

    Li = np.exp(-sum(((m-M)**2)/(2*msig**2)))

    #-------------------------------------------------------------------------
    #                      - Posterior distribution -
    #-------------------------------------------------------------------------

    p = Li*pi_dt*pi_te*pi_ib*pi_a0

    return p
コード例 #2
0
#Plotting example of light curve

import numpy as np
import matplotlib.pyplot as plt
from fileread import readFile
from posterior import MT
from magfit import magfit
from convert import magConvert

(v1,v2,v3,tdet,s3,Ca0,Cte,t0_actual) = readFile('2015BLG285.txt')

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

plt.figure()
plt.plot(v1-tdet,magConvert(v2,a,b),'k.',label='Actual Light Curve')
plt.title('Light Curve for MOA '+s3)
plt.xlabel('$t$ (days)')
plt.ylabel('$Magnification$')
plt.show()
コード例 #3
0
ファイル: mcmc.py プロジェクト: peva032/Honours
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]