コード例 #1
0
    def likelihood(cube, ndim, nparams):

        lnlikePhot = 0.0
        lnlike_nonPhot = 0.0
        parnames = Photpars['parnames']
        
        # Photometric params
        if MultiDimPriors == True:
            params, lnlikePhot = random_photpar_multidim(cube[0],
                                                         Photpars['MultiDimPrior_Bins'],
                                                         Photpars['MultiDimPrior'][:,0],
                                                         Photpars['MultiDimPrior'][:,1],
                                                         Photpars['MultiDimPrior'][:, -nPhotpars:])
            for i in range(nPhotpars): cube[i] = params[i]
        else:
            for i in range(nPhotpars):
                param, ln_prob_param = random_photpar(cube[i],
                                                      Photpars[parnames[i]][:,0],
                                                      Photpars[parnames[i]][:,1],
                                                      Photpars[parnames[i]][:,2])
                cube[i]=param
                lnlikePhot += ln_prob_param

        idx = nPhotpars

        # x Position at t0:
        thetaS0x, ln_prob_thetaS0x = random_thetaS0x(cube[idx])
        cube[idx] = thetaS0x
        idx += 1
        lnlike_nonPhot += ln_prob_thetaS0x

        # y Position at t0:
        thetaS0y, ln_prob_thetaS0y = random_thetaS0y(cube[idx])
        cube[idx] = thetaS0y
        idx += 1
        lnlike_nonPhot += ln_prob_thetaS0y

        # Source proper motion (x dimension)
        muSx, ln_prob_muSx = random_muSx(cube[idx])
        cube[idx] = muSx
        idx += 1
        lnlike_nonPhot += ln_prob_muSx

        # Source proper motion (y dimension)
        muSy, ln_prob_muSy = random_muSy(cube[idx])
        cube[idx] = muSy
        idx += 1
        lnlike_nonPhot += ln_prob_muSy

        # Source-lens relative proper motion (x dimension)
        muRelx, ln_prob_muRelx = random_muRelx(cube[idx])
        cube[idx] = muRelx
        idx += 1
        lnlike_nonPhot += ln_prob_muRelx

        # Source-lens relative proper motion (y dimension)
        muRely, ln_prob_muRely = random_muRely(cube[idx])
        cube[idx] = muRely
        idx += 1
        lnlike_nonPhot += ln_prob_muRely


        t0 = cube[0]
        beta = cube[1]
        tE = cube[2]
        piEN = cube[3]
        piEE= cube[4]


        #Create astrometric model of source
        thetaS_model, thetaE_amp, M, shift, thetaS_nolens = MCMC_LensModel.LensModel_Trial1(tobs, t0, tE,
                                                                                            [thetaS0x, thetaS0y],
                                                                                            [muSx,muSy],
                                                                                            [muRelx, muRely],
                                                                                            beta,
                                                                                            [piEN, piEE])
        cube[11] = thetaE_amp
        cube[12] = M
        thetaSx_model = thetaS_model[:,0]
        thetaSy_model = thetaS_model[:,1]

        lnlike =  lnlikePhot + lnlike_nonPhot + \
          MCMC_LensModel.lnLikelihood(thetaSx_model, thetaSx_data, xerr_data) + \
          MCMC_LensModel.lnLikelihood(thetaSy_model, thetaSy_data, yerr_data)

        # print "Log Likelihood:  ", lnlike

        return lnlike
コード例 #2
0
def calc_chi2_lens_fit(
        root_dir='/Users/jlu/work/microlens/2015_evan/',
        analysis_dir='analysis_ob110022_2014_03_22al_MC100_omit_1/',
        mnest_run='bf',
        target='OB110022',
        useMedian=False,
        verbose=True):

    # Assume this is NIRC2 data.
    pixScale = 9.952  # mas / pixel

    if target == 'ob120169':
        targname = 'ob120169_R'
    else:
        targname = target

    #Plot astrometric observations
    pointsFile = root_dir + analysis_dir + 'points_d/' + targname + '.points'
    pointsTab = Table.read(pointsFile, format='ascii')
    tobs = pointsTab['col1']
    xpix = pointsTab['col2']
    ypix = pointsTab['col3']
    xerr = pointsTab['col4']
    yerr = pointsTab['col5']

    thetaSx_data = xpix * pixScale
    thetaSy_data = ypix * pixScale
    xerr_data = xerr * pixScale
    yerr_data = yerr * pixScale

    # Load Best-Fit Microlensing Model
    mnest_dir = 'multiNest/' + mnest_run + '/'
    mnest_root = mnest_run
    tab = load_mnest_results(root_dir=root_dir + analysis_dir,
                             mnest_dir=mnest_dir,
                             mnest_root=mnest_root)

    params = tab.keys()
    pcnt = len(params)
    Masslim = 0.0

    # Clean table and only keep valid results.
    ind = np.where((tab['Mass'] >= Masslim))[0]
    tab = tab[ind]

    if not useMedian:
        best = np.argmax(tab['logLike'])
        maxLike = tab['logLike'][best]
        if verbose:
            print 'Best-Fit Solution:'
            print '  Index = {0:d}'.format(best)
            print '  Log(L) = {0:6.2f}'.format(maxLike)
            print '  Params:'
            for i in range(pcnt):
                print '     {0:15s}  {1:10.3f}'.format(params[i],
                                                       tab[params[i]][best])

        t0 = tab['t0'][best]
        tE = tab['tE'][best]
        thetaS0x = tab['thetaS0x'][best]
        thetaS0y = tab['thetaS0y'][best]
        muSx = tab['muSx'][best]
        muSy = tab['muSy'][best]
        muRelx = tab['muRelx'][best]
        muRely = tab['muRely'][best]
        beta = tab['beta'][best]
        piEN = tab['piEN'][best]
        piEE = tab['piEE'][best]

        if verbose:
            print '     muLx = {0:5.2f} mas/yr'.format(muSx - muRelx)
            print '     muLy = {0:5.2f} mas/yr'.format(muSy - muRely)
    else:
        t0 = weighted_quantile(tab['t0'], 0.5, sample_weight=tab['weights'])
        tE = weighted_quantile(tab['tE'], 0.5, sample_weight=tab['weights'])
        thetaS0x = weighted_quantile(tab['thetaS0x'],
                                     0.5,
                                     sample_weight=tab['weights'])
        thetaS0y = weighted_quantile(tab['thetaS0y'],
                                     0.5,
                                     sample_weight=tab['weights'])
        muSx = weighted_quantile(tab['muSx'],
                                 0.5,
                                 sample_weight=tab['weights'])
        muSy = weighted_quantile(tab['muSy'],
                                 0.5,
                                 sample_weight=tab['weights'])
        muRelx = weighted_quantile(tab['muRelx'],
                                   0.5,
                                   sample_weight=tab['weights'])
        muRely = weighted_quantile(tab['muRely'],
                                   0.5,
                                   sample_weight=tab['weights'])
        beta = weighted_quantile(tab['beta'],
                                 0.5,
                                 sample_weight=tab['weights'])
        piEN = weighted_quantile(tab['piEN'],
                                 0.5,
                                 sample_weight=tab['weights'])
        piEE = weighted_quantile(tab['piEE'],
                                 0.5,
                                 sample_weight=tab['weights'])

        if verbose:
            print 'Median Solution:'
            print '   Params:'
            print '     {0:15s}  {1:10.3f}'.format('t0', t0)
            print '     {0:15s}  {1:10.3f}'.format('tE', tE)
            print '     {0:15s}  {1:10.3f}'.format('thetaS0x', thetaS0x)
            print '     {0:15s}  {1:10.3f}'.format('thetaS0y', thetaS0y)
            print '     {0:15s}  {1:10.3f}'.format('muSx', muSx)
            print '     {0:15s}  {1:10.3f}'.format('muSy', muSy)
            print '     {0:15s}  {1:10.3f}'.format('muRelx', muRelx)
            print '     {0:15s}  {1:10.3f}'.format('muRely', muRely)
            print '     {0:15s}  {1:10.3f}'.format('beta', beta)
            print '     {0:15s}  {1:10.3f}'.format('piEN', piEN)
            print '     {0:15s}  {1:10.3f}'.format('piEE', piEE)
            print '     muLx = {0:5.2f} mas/yr'.format(muSx - muRelx)
            print '     muLy = {0:5.2f} mas/yr'.format(muSy - muRely)

    ##########
    # Get astrometry for best-fit model. Do this on a fine time grid
    # and also at the points of the observations.
    ##########
    tmod = np.arange(t0 - 20.0, t0 + 20.0, 0.01)
    model = MCMC_LensModel.LensModel_Trial1(tmod, t0, tE, [thetaS0x, thetaS0y],
                                            [muSx, muSy], [muRelx, muRely],
                                            beta, [piEN, piEE])
    model_tobs = MCMC_LensModel.LensModel_Trial1(tobs, t0, tE,
                                                 [thetaS0x, thetaS0y],
                                                 [muSx, muSy],
                                                 [muRelx, muRely], beta,
                                                 [piEN, piEE])

    thetaS_model = model[0]
    thetaE_amp = model[1]
    M = model[2]
    shift = model[3]
    thetaS_nolens = model[4]

    thetaS_model_tobs = model_tobs[0]
    thetaE_amp_tobs = model_tobs[1]
    M_tobs = model_tobs[2]
    shift_tobs = model_tobs[3]
    thetaS_nolens_tobs = model_tobs[4]

    thetaSx_model = thetaS_model[:, 0]
    thetaSy_model = thetaS_model[:, 1]
    thetaS_nolensx = thetaS_nolens[:, 0]
    thetaS_nolensy = thetaS_nolens[:, 1]
    shiftx = shift[:, 0]
    shifty = shift[:, 1]

    thetaSx_model_tobs = thetaS_model_tobs[:, 0]
    thetaSy_model_tobs = thetaS_model_tobs[:, 1]

    ##########
    # Calculate Chi-Squared Star for comparison to velocity-only fit.
    ##########
    # Find the model points closest to the data.
    dx = thetaSx_data - thetaSx_model_tobs
    dy = thetaSy_data - thetaSy_model_tobs
    chi2_x = ((dx / xerr_data)**2).sum()
    chi2_y = ((dy / yerr_data)**2).sum()
    N_dof = (2 * len(dx)) - 9
    chi2_tot = chi2_x + chi2_y
    chi2_red = chi2_tot / N_dof

    if verbose:
        print 'Chi-Squared of Lens Model Fit:'
        print '        X Chi^2 = {0:5.2f}'.format(chi2_x)
        print '        Y Chi^2 = {0:5.2f}'.format(chi2_y)
        print '    Total Chi^2 = {0:5.2f} ({1:d} DOF)'.format(chi2_tot, N_dof)
        print '  Reduced Chi^2 = {0:5.2f}'.format(chi2_red)
        print ''
        print ''

    return chi2_tot, N_dof, chi2_red
コード例 #3
0
    def likelihood(cube, ndim, nparams):

        lnlikePhot = 0.0
        lnlike_nonPhot = 0.0
        parnames = Photpars['parnames']

        # Photometric params
        if MultiDimPriors == True:
            params, lnlikePhot = random_photpar_multidim(
                cube[0], Photpars['MultiDimPrior_Bins'],
                Photpars['MultiDimPrior'][:, 0], Photpars['MultiDimPrior'][:,
                                                                           1],
                Photpars['MultiDimPrior'][:, -nPhotpars:])
            for i in range(nPhotpars):
                cube[i] = params[i]
        else:
            for i in range(nPhotpars):
                param, ln_prob_param = random_photpar(
                    cube[i], Photpars[parnames[i]][:, 0],
                    Photpars[parnames[i]][:, 1], Photpars[parnames[i]][:, 2])
                cube[i] = param
                lnlikePhot += ln_prob_param

        idx = nPhotpars

        # x Position at t0:
        thetaS0x, ln_prob_thetaS0x = random_thetaS0x(cube[idx])
        cube[idx] = thetaS0x
        idx += 1
        lnlike_nonPhot += ln_prob_thetaS0x

        # y Position at t0:
        thetaS0y, ln_prob_thetaS0y = random_thetaS0y(cube[idx])
        cube[idx] = thetaS0y
        idx += 1
        lnlike_nonPhot += ln_prob_thetaS0y

        # Source proper motion (x dimension)
        muSx, ln_prob_muSx = random_muSx(cube[idx])
        cube[idx] = muSx
        idx += 1
        lnlike_nonPhot += ln_prob_muSx

        # Source proper motion (y dimension)
        muSy, ln_prob_muSy = random_muSy(cube[idx])
        cube[idx] = muSy
        idx += 1
        lnlike_nonPhot += ln_prob_muSy

        # Source-lens relative proper motion (x dimension)
        muRelx, ln_prob_muRelx = random_muRelx(cube[idx])
        cube[idx] = muRelx
        idx += 1
        lnlike_nonPhot += ln_prob_muRelx

        # Source-lens relative proper motion (y dimension)
        muRely, ln_prob_muRely = random_muRely(cube[idx])
        cube[idx] = muRely
        idx += 1
        lnlike_nonPhot += ln_prob_muRely

        t0 = cube[0]
        beta = cube[1]
        tE = cube[2]
        piEN = cube[3]
        piEE = cube[4]

        #Create astrometric model of source
        thetaS_model, thetaE_amp, M, shift, thetaS_nolens = MCMC_LensModel.LensModel_Trial1(
            tobs, t0, tE, [thetaS0x, thetaS0y], [muSx, muSy], [muRelx, muRely],
            beta, [piEN, piEE])
        cube[11] = thetaE_amp
        cube[12] = M
        thetaSx_model = thetaS_model[:, 0]
        thetaSy_model = thetaS_model[:, 1]

        lnlike =  lnlikePhot + lnlike_nonPhot + \
          MCMC_LensModel.lnLikelihood(thetaSx_model, thetaSx_data, xerr_data) + \
          MCMC_LensModel.lnLikelihood(thetaSy_model, thetaSy_data, yerr_data)

        # print "Log Likelihood:  ", lnlike

        return lnlike
コード例 #4
0
def plot_OB120169(
        root_dir='/Users/jlu/work/microlens/OB120169/analysis_2016_09_14/',
        analysis_dir='analysis_ob120169_2016_09_14_a4_m22_w4_MC100/',
        points_dir='points_d/',
        mnest_dir='multiNest/up/',
        mnest_root='up'):

    target = 'OB120169_R'
    display_name = 'OB120169'

    #Plot astrometric observations
    pointsFile = root_dir + analysis_dir + points_dir + target + '.points'
    pointsTab = Table.read(pointsFile, format='ascii')
    tobs = pointsTab['col1']
    xpix = pointsTab['col2']
    ypix = pointsTab['col3']
    xerr = pointsTab['col4']
    yerr = pointsTab['col5']

    pixScale = 9.952
    thetaSx_data = xpix * pixScale
    thetaSy_data = ypix * pixScale
    xerr_data = xerr * pixScale
    yerr_data = yerr * pixScale

    # Overplot Best-Fit Model
    tab = load_mnest_results_OB120169(root_dir=root_dir + analysis_dir,
                                      mnest_dir=mnest_dir,
                                      mnest_root=mnest_root)
    params = tab.keys()
    pcnt = len(params)
    Masslim = 0.0

    # Clean table and only keep valid results.
    ind = np.where((tab['Mass'] >= Masslim))[0]
    tab = tab[ind]

    best = np.argmax(tab['logLike'])
    maxLike = tab['logLike'][best]
    print 'Best-Fit Solution:'
    print '  Index = {0:d}'.format(best)
    print '  Log(L) = {0:6.2f}'.format(maxLike)
    print '  Params:'
    for i in range(pcnt):
        print '     {0:15s}  {1:10.3f}'.format(params[i], tab[params[i]][best])

    t0 = tab['t0'][best]
    tE = tab['tE'][best]
    thetaS0x = tab['thetaS0x'][best]
    thetaS0y = tab['thetaS0y'][best]
    muSx = tab['muSx'][best]
    muSy = tab['muSy'][best]
    muRelx = tab['muRelx'][best]
    muRely = tab['muRely'][best]
    beta = tab['beta'][best]
    piEN = tab['piEN'][best]
    piEE = tab['piEE'][best]
    print '     muLx = {0:5.2f} mas/yr'.format(muSx - muRelx)
    print '     muLy = {0:5.2f} mas/yr'.format(muSy - muRely)

    ##########
    # Get astrometry for best-fit model. Do this on a fine time grid
    # and also at the points of the observations.
    ##########
    tmod = np.arange(t0 - 20.0, t0 + 20.0, 0.01)
    model = MCMC_LensModel.LensModel_Trial1(tmod, t0, tE, [thetaS0x, thetaS0y],
                                            [muSx, muSy], [muRelx, muRely],
                                            beta, [piEN, piEE])
    model_tobs = MCMC_LensModel.LensModel_Trial1(tobs, t0, tE,
                                                 [thetaS0x, thetaS0y],
                                                 [muSx, muSy],
                                                 [muRelx, muRely], beta,
                                                 [piEN, piEE])

    thetaS_model = model[0]
    thetaE_amp = model[1]
    M = model[2]
    shift = model[3]
    thetaS_nolens = model[4]

    thetaS_model_tobs = model_tobs[0]
    thetaE_amp_tobs = model_tobs[1]
    M_tobs = model_tobs[2]
    shift_tobs = model_tobs[3]
    thetaS_nolens_tobs = model_tobs[4]

    thetaSx_model = thetaS_model[:, 0]
    thetaSy_model = thetaS_model[:, 1]
    thetaS_nolensx = thetaS_nolens[:, 0]
    thetaS_nolensy = thetaS_nolens[:, 1]
    shiftx = shift[:, 0]
    shifty = shift[:, 1]

    thetaSx_model_tobs = thetaS_model_tobs[:, 0]
    thetaSy_model_tobs = thetaS_model_tobs[:, 1]

    ##########
    # Calculate Chi-Squared Stat for comparison to velocity-only fit.
    ##########
    # Find the model points closest to the data.
    dx = thetaSx_data - thetaSx_model_tobs
    dy = thetaSy_data - thetaSy_model_tobs
    chi2_x = ((dx / xerr_data)**2).sum()
    chi2_y = ((dy / yerr_data)**2).sum()
    N_dof = (2 * len(dx)) - 9
    chi2_red = (chi2_x + chi2_y) / N_dof
    print 'Chi-Squared of Lens Model Fit:'
    print '        X Chi^2 = {0:5.2f}'.format(chi2_x)
    print '        Y Chi^2 = {0:5.2f}'.format(chi2_y)
    print '  Reduced Chi^2 = {0:5.2f}'.format(chi2_red)

    ##########
    # Plotting
    ##########
    fontsize1 = 18
    fontsize2 = 14

    py.clf()
    fig1 = py.figure(2, figsize=(10, 8))
    py.subplots_adjust(left=0.1, top=0.95, hspace=0.3, wspace=0.3)

    paxes = py.subplot(2, 2, 1)
    originX = np.mean(thetaSx_model)
    originY = np.mean(thetaSy_model)
    py.plot(tmod - t0, thetaSx_model - originX, 'r-')
    py.plot(tmod - t0, thetaS_nolensx - originX, 'r--')
    py.errorbar(tobs - t0, thetaSx_data - originX, yerr=xerr_data, fmt='k.')
    py.ylabel(r'$\Delta\alpha$ (mas)', fontsize=fontsize1)
    py.xlabel('t - t$_{\mathrm{o}}$ (yr)', fontsize=fontsize1)
    py.ylim(-4, 12)
    py.xlim(-0.5, 6.0)
    xticks = np.arange(0, 4.1, 1, dtype=int)
    py.xticks(xticks, fontsize=fontsize2)
    py.yticks(fontsize=fontsize2)

    paxes = py.subplot(2, 2, 2)
    py.plot(tmod - t0, thetaSy_model - originY, 'b-')
    py.plot(tmod - t0, thetaS_nolensy - originY, 'b--')
    py.errorbar(tobs - t0, thetaSy_data - originY, yerr=yerr_data, fmt='k.')
    py.ylabel(r'$\Delta\delta$ (mas)', fontsize=fontsize1)
    py.xlabel('t - t$_{\mathrm{o}}$ (yr)', fontsize=fontsize1)
    py.ylim(-2, 6)
    py.xlim(-0.5, 6.0)
    py.xticks(xticks, fontsize=fontsize2)
    py.yticks(fontsize=fontsize2)

    paxes = py.subplot(2, 2, 3)
    n = len(tmod)
    py.plot(thetaS_nolensx - originX, thetaS_nolensy - originY, 'g--')
    py.plot(thetaSx_model - originX, thetaSy_model - originY, 'g-')
    py.errorbar(thetaSx_data - originX,
                thetaSy_data - originY,
                xerr=xerr_data,
                yerr=yerr_data,
                fmt='k.')
    py.ylabel(r'$\Delta\delta$ (mas)', fontsize=fontsize1)
    py.xlabel(r'$\Delta\alpha$ (mas)', fontsize=fontsize1)
    py.axis('equal')
    py.ylim(-5, 7)
    py.xlim(-4, 8)
    py.xticks(fontsize=fontsize2)
    py.yticks(fontsize=fontsize2)
    py.xlim(py.xlim()[::-1])

    # Make a histogram of the mass using the weights. This creates the
    # marginalized 1D posteriors.
    paxes = py.subplot(2, 2, 4)
    bins = np.arange(0, 30, 0.25)
    n, bins, patch = py.hist(tab['Mass'],
                             normed=True,
                             histtype='step',
                             weights=tab['weights'],
                             bins=bins,
                             linewidth=1.5)
    bin_centers = (bins[:-1] + bins[1:]) / 2
    py.xlabel('Mass')
    xtitle = r'Lens Mass (M$_{\odot}$)'
    py.xlabel(xtitle, fontsize=fontsize1, labelpad=10)
    py.xlim(0, 20)
    py.ylim(0, 0.2)
    py.ylabel('Relative probability', fontsize=fontsize1, labelpad=10)
    py.xticks(fontsize=fontsize2)
    py.yticks(fontsize=fontsize2)

    outdir = root_dir + analysis_dir + mnest_dir + 'plots/'
    outfile = outdir + 'plot_OB120169_data_vs_model.png'
    fileUtil.mkdir(outdir)
    print 'writing plot to file ' + outfile

    py.savefig(outfile)

    return