def distanceIntegrand(dist,cosb,Gsamples,rmcenter,onlygreen):
    # Calculate the density
    densmap= densprofiles.healpixelate(dist,densprofiles.expdisk,
                                       [1./3.,1./0.3],nside=_NSIDE,
                                       nest=False)
    # Load the dust map
    if onlygreen:
        combinedmap= dust.load_green15(dist,nest=False,nside_out=_NSIDE)
        combinedmap[combinedmap == healpy.UNSEEN]= 0.
    else:
        combinedmap= dust.load_combined(dist,nest=False,nside_out=_NSIDE)
    # Sample over the distribution of MG
    combinedmask= numpy.zeros_like(combinedmap)
    G0= 0.68+dust.dist2distmod(dist)
    for jj in range(_NGSAMPLES):
        combinedmask+= ((combinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                            *(combinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
    combinedmask/= _NGSAMPLES
    if True or dust.dist2distmod(dist) == 9.5 or dust.dist2distmod(dist) == 10.5:
        print numpy.sum(combinedmask)
        print dust.dist2distmod(dist), numpy.sum(cosb*densmap*combinedmask)
    # If rmcenter, rm the center of the MW
    if rmcenter:
        theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                             numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                             nest=False)
        combinedmask[((phi < 25.*_DEGTORAD)+(phi > (360.-25.)*_DEGTORAD))\
                         *(numpy.fabs(numpy.pi/2.-theta) < 25.*_DEGTORAD)]= 0.
    # Compute cross correlation
    return float(numpy.sum(cosb*densmap*combinedmask))
示例#2
0
def distanceIntegrand(dist, cosb, Gsamples, rmcenter, onlygreen):
    # Calculate the density
    densmap = densprofiles.healpixelate(dist,
                                        densprofiles.expdisk,
                                        [1. / 3., 1. / 0.3],
                                        nside=_NSIDE,
                                        nest=False)
    # Load the dust map
    if onlygreen:
        combinedmap = dust.load_green15(dist, nest=False, nside_out=_NSIDE)
        combinedmap[combinedmap == healpy.UNSEEN] = 0.
    else:
        combinedmap = dust.load_combined(dist, nest=False, nside_out=_NSIDE)
    # Sample over the distribution of MG
    combinedmask = numpy.zeros_like(combinedmap)
    G0 = 0.68 + dust.dist2distmod(dist)
    for jj in range(_NGSAMPLES):
        combinedmask+= ((combinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                            *(combinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
    combinedmask /= _NGSAMPLES
    if True or dust.dist2distmod(dist) == 9.5 or dust.dist2distmod(
            dist) == 10.5:
        print numpy.sum(combinedmask)
        print dust.dist2distmod(dist), numpy.sum(cosb * densmap * combinedmask)
    # If rmcenter, rm the center of the MW
    if rmcenter:
        theta, phi = healpy.pixelfunc.pix2ang(
            _NSIDE,
            numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
            nest=False)
        combinedmask[((phi < 25.*_DEGTORAD)+(phi > (360.-25.)*_DEGTORAD))\
                         *(numpy.fabs(numpy.pi/2.-theta) < 25.*_DEGTORAD)]= 0.
    # Compute cross correlation
    return float(numpy.sum(cosb * densmap * combinedmask))
示例#3
0
def plot_dust_gaia(dist, plotname):
    # Load the dust map
    green15map = dust.load_combined(dist, nest=True, nside_out=_NSIDE)
    dm = dust.dist2distmod(dist)
    green15map[green15map == healpy.UNSEEN] = -1.
    print "%i are NaN" % (numpy.sum(numpy.isnan(green15map)))
    #theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),nest=True)
    #print (numpy.pi/2.-theta)[numpy.isnan(green15map)]/numpy.pi*180.
    #print phi[numpy.isnan(green15map)]/numpy.pi*180.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,
                             min=0.,
                             max=round(10. * (20. - dm - 0.68)) / 10.,
                             format=r'$%g$',
                             cmap='gist_yarg',
                             title="",
                             unit='$A_G\,(\mathrm{mag})$')
    # Plot outline of Marshall et al.
    ls = numpy.linspace(-100.125, 100.125, 1001)
    healpy.visufunc.projplot(ls, ls * 0. - 10.125, 'k--', lw=1.2, lonlat=True)
    healpy.visufunc.projplot(ls, ls * 0. + 10.125, 'k--', lw=1.2, lonlat=True)
    bs = numpy.linspace(-10.125, 10.125, 1001)
    healpy.visufunc.projplot(bs * 0. - 100.125, bs, 'k--', lw=1.2, lonlat=True)
    healpy.visufunc.projplot(bs * 0. + 100.125, bs, 'k--', lw=1.2, lonlat=True)
    # Plot boundary of Green et al. map, dec > -30.
    ras = numpy.linspace(0., 360., 1001)
    decs = ras * 0. - 30.
    lbs = bovy_coords.radec_to_lb(ras, decs, degree=True)
    ls = lbs[:, 0]
    bs = lbs[:, 1]
    # rm those within Marshall et al.
    keepIndx = True - ((ls > 259.875) * (numpy.fabs(bs) < 10.125) +
                       (ls < 100.125) * (numpy.fabs(bs) < 10.125))
    ls = ls[keepIndx]
    bs = bs[keepIndx]
    healpy.visufunc.projplot(ls, bs, 'k-.', lw=1.2, lonlat=True)
    # Labels
    healpy.visufunc.projtext(350.,
                             -8.,
                             r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
                             lonlat=True,
                             size=13.)
    healpy.visufunc.projtext(10.,
                             -60.,
                             r'$\mathrm{Drimmel\ et\ al.\ (2003)}$',
                             lonlat=True,
                             size=13.)
    healpy.visufunc.projtext(160.,
                             40.,
                             r'$\mathrm{Green\ et\ al.\ (2015)}$',
                             lonlat=True,
                             size=13.)
    bovy_plot.bovy_end_print(plotname)
示例#4
0
def plot_dust(dist,plotname):
    # Load the dust map
    green15map= dust.load_green15(dist,nest=True,nside_out=_NSIDE)
    dm= dust.dist2distmod(dist)
    green15map[green15map == healpy.UNSEEN]= -1.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,min=0.,
                             max=round(10.*(12.8-dm+1.49))/10.,
                             format=r'$%g$',
                             title=r'$\mathrm{Extinction\ to\ %.1f\,kpc}$' % dist,
                             cmap='gist_yarg',
                             unit='$A_H\,(\mathrm{mag})$')
    bovy_plot.bovy_end_print(plotname)
示例#5
0
def plot_dust_gaia(dist,plotname):
    # Load the dust map
    green15map= dust.load_combined(dist,nest=True,nside_out=_NSIDE)
    dm= dust.dist2distmod(dist)
    green15map[green15map == healpy.UNSEEN]= -1.
    print "%i are NaN" % (numpy.sum(numpy.isnan(green15map)))
    #theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),nest=True)
    #print (numpy.pi/2.-theta)[numpy.isnan(green15map)]/numpy.pi*180.
    #print phi[numpy.isnan(green15map)]/numpy.pi*180.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,min=0.,
                             max=round(10.*(20.-dm-0.68))/10.,
                             format=r'$%g$',
                             cmap='gist_yarg',
                             title="",
                             unit='$A_G\,(\mathrm{mag})$')
    # Plot outline of Marshall et al.
    ls= numpy.linspace(-100.125,100.125,1001)
    healpy.visufunc.projplot(ls,ls*0.-10.125,'k--',lw=1.2,lonlat=True)
    healpy.visufunc.projplot(ls,ls*0.+10.125,'k--',lw=1.2,lonlat=True)
    bs= numpy.linspace(-10.125,10.125,1001)
    healpy.visufunc.projplot(bs*0.-100.125,bs,'k--',lw=1.2,lonlat=True)
    healpy.visufunc.projplot(bs*0.+100.125,bs,'k--',lw=1.2,lonlat=True)
    # Plot boundary of Green et al. map, dec > -30.
    ras= numpy.linspace(0.,360.,1001)
    decs= ras*0.-30.
    lbs= bovy_coords.radec_to_lb(ras,decs,degree=True)
    ls= lbs[:,0]
    bs= lbs[:,1]
    # rm those within Marshall et al.
    keepIndx= True-((ls > 259.875)*(numpy.fabs(bs) < 10.125)
                    +(ls < 100.125)*(numpy.fabs(bs) < 10.125))
    ls= ls[keepIndx]
    bs= bs[keepIndx]
    healpy.visufunc.projplot(ls,bs,'k-.',lw=1.2,lonlat=True)
    # Labels
    healpy.visufunc.projtext(350.,-8.,r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
                             lonlat=True,size=13.)
    healpy.visufunc.projtext(10.,-60.,r'$\mathrm{Drimmel\ et\ al.\ (2003)}$',
                             lonlat=True,size=13.)
    healpy.visufunc.projtext(160.,40.,r'$\mathrm{Green\ et\ al.\ (2015)}$',
                             lonlat=True,size=13.)
    bovy_plot.bovy_end_print(plotname)
def distanceIntegrandHires(dist, theta, phi, cosb, Gsamples, dmap):
    # Calculate the density
    densmap = densprofiles.expdisk(phi,
                                   numpy.pi / 2. - theta,
                                   dist * numpy.ones(len(theta)),
                                   glon=True,
                                   params=[1. / 3., 1. / 0.3])
    # Distance pixel
    tpix = numpy.argmin(numpy.fabs(dist - _HIRESGREEN15DISTS))
    dmap = dmap[:, tpix]
    # Sample over the distribution of MG
    combinedmask = numpy.zeros_like(dmap)
    G0 = 0.68 + dust.dist2distmod(dist)
    #if dust.dist2distmod(dist) == 9.5 or dust.dist2distmod(dist) == 10.5:
    #    print numpy.sum(numpy.isnan(combinedmap))
    for jj in range(_NGSAMPLES):
        combinedmask+= ((dmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                            *(dmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
    combinedmask /= _NGSAMPLES
    #if dust.dist2distmod(dist) == 9.5 or dust.dist2distmod(dist) == 10.5:
    #    print numpy.sum(combinedmask)
    #    print dust.dist2distmod(dist), numpy.sum(cosb*densmap*combinedmask)
    # Compute cross correlation
    return float(numpy.sum(cosb * densmap * combinedmask))
示例#7
0
def plot_distanceintegral_fewfields(savename, plotname, apogee=False):
    #ls and bs of the patches
    ls = [280., 30., 12., 37.5, 90., 127.5, 30., 60., 20., -20., -40.]
    bs = [45., 4., 2., 0., 0., 0., 0., 0., 0., 0., 0.]
    radius = 1.49
    locs = [4214, 4244, 4378, 4312, 4242, 4318, 4240, 4241]  # for apogee
    # If we are doing APOGEE selection, load the APOGEE selection function
    if apogee:
        selectFile = '../savs/selfunc-nospdata.sav'
        if os.path.exists(selectFile):
            with open(selectFile, 'rb') as savefile:
                apo = pickle.load(savefile)
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
            if apogee:
                area_cdens = pickle.load(savefile)
    else:
        if not apogee:
            # For samping over the absolute magnitude distribution
            iso = gaia_rc.load_iso()
            Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # Loop through each distance slice
        area = numpy.zeros((len(ls), len(dust._GREEN15DISTS)))
        if apogee:
            area_cdens = numpy.zeros((len(ls), len(dust._GREEN15DISTS)))
        for ii, dist in enumerate(dust._GREEN15DISTS):
            print "Working on distance %i: %f" % (ii, dist)
            G0 = 0.68 + dust.dist2distmod(dist)
            H0 = -1.49 + dust.dist2distmod(dist)
            # Load the dust map
            combinedmap = dust.load_combined(dist,
                                             nest=False,
                                             nside_out=_NSIDE)
            # Loop through a few patches
            theta, phi = healpy.pixelfunc.pix2ang(
                _NSIDE,
                numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                nest=False)
            cosb = numpy.sin(theta)
            for ff, (ll, bb) in enumerate(zip(ls, bs)):
                if ff >= len(ls) - 3 * apogee: break
                vec = healpy.pixelfunc.ang2vec((90. - bb) * _DEGTORAD,
                                               ll * _DEGTORAD)
                ipixs = healpy.query_disc(_NSIDE,
                                          vec,
                                          radius * _DEGTORAD,
                                          inclusive=False,
                                          nest=False)
                ipixIndx = numpy.in1d(numpy.arange(
                    healpy.pixelfunc.nside2npix(_NSIDE)),
                                      ipixs,
                                      assume_unique=True)
                # Calculate the density
                densmap = densprofiles.expdisk(phi[ipixIndx],
                                               numpy.pi / 2. - theta[ipixIndx],
                                               dist * numpy.ones(len(ipixs)),
                                               glon=True,
                                               params=[1. / 3., 1. / 0.3])
                combinedmask = numpy.zeros(len(ipixs))
                tcombinedmap = combinedmap[ipixIndx]
                if apogee:
                    # Loop through the three cohorts
                    for c in ['short', 'medium', 'long']:
                        hmin = apo.Hmin(locs[ff], cohort=c)
                        hmax = apo.Hmax(locs[ff], cohort=c)
                        combinedmask+= ((tcombinedmap > (hmin-H0))\
                                            *(tcombinedmap < (hmax-H0))).astype('float')*apo(locs[ff],hmin+0.01)
                else:
                    for jj in range(_NGSAMPLES):
                        combinedmask+= ((tcombinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                            *(tcombinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
                combinedmask /= _NGSAMPLES
                # Compute cross correlation
                area[ff,ii]= float(numpy.sum(cosb[ipixIndx]*densmap\
                                                 *combinedmask))
                if apogee:
                    # Also store the approximation that the density is constant
                    cdens = densprofiles.expdisk(ll * _DEGTORAD,
                                                 bb * _DEGTORAD,
                                                 dist,
                                                 glon=True,
                                                 params=[1. / 3., 1. / 0.3])
                    area_cdens[ff,ii]= float(numpy.sum(cosb[ipixIndx]*cdens\
                                                           *combinedmask))
        if apogee:
            save_pickles(savename, area, area_cdens)
        else:
            save_pickles(savename, area)
    # Plot the power spectrum
    if True:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        colors = [
            'b', 'g', 'r', 'c', 'gold', 'm', 'k', 'orange', 'y', 'b', 'g'
        ]
        lss = ['-', '-', '-', '-', '-', '-', '-', '-', '-', '--', '--']
        for ff in range(len(ls)):
            if ff >= len(ls) - 3 * apogee: break
            psdx, psd = signal.periodogram(
                area[ff] * dust._GREEN15DISTS**3. /
                numpy.sum(area[ff] * dust._GREEN15DISTS**3.),
                fs=1. / (dust._GREEN15DISTMODS[1] - dust._GREEN15DISTMODS[0]),
                detrend=lambda x: x,
                scaling='spectrum')
            bovy_plot.bovy_plot(psdx[1:],
                                psd[1:],
                                '-',
                                loglog=True,
                                xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                                ylabel=r'$P_k$',
                                xrange=[0.04, 4.],
                                color=colors[ff],
                                ls=lss[ff],
                                overplot=ff > 0)
            if ff == 0:
                bovy_plot.bovy_text(
                    r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
                    bottom_left=True,
                    size=16.)
        bovy_plot.bovy_end_print(plotname)
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        for ff in range(len(ls)):
            if ff >= len(ls) - 3 * apogee: break
            bovy_plot.bovy_plot(
                dust._GREEN15DISTMODS,
                area[ff] * dust._GREEN15DISTS**3.,
                'k-',
                xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
                ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    for ff in range(len(ls)):
        if ff >= len(ls) - 3 * apogee: break
        spl = interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                       area[ff] *
                                                       dust._GREEN15DISTS**3.,
                                                       k=5)
        fthder = [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
        print "Simpson error (%f,%f)= %g, volume = %g" % (
            ls[ff], bs[ff], 0.5**4. / 180. * numpy.mean(numpy.fabs(fthder)) /
            integrate.simps(area[ff] * dust._GREEN15DISTS**3., dx=0.5),
            numpy.sum(area[ff] * dust._GREEN15DISTS**3.))
    return None
示例#8
0
def plot_powspec(dist,basename,plotname):
    # Density
    G0= 0.68+dust.dist2distmod(dist)
    densname= basename+'_D%.1f_denscl.sav' % dist
    if not os.path.exists(densname):
        densmap= densprofiles.healpixelate(dist,densprofiles.expdisk,
                                           [1./3.,1./0.3],nside=_NSIDE,
                                           nest=False)
        denscl= healpy.sphtfunc.anafast(densmap,pol=False)
        densmap2= densprofiles.healpixelate(dist,densprofiles.expdisk,
                                            [1./2.,1./0.9],nside=_NSIDE,
                                            nest=False)
        denscl2= healpy.sphtfunc.anafast(densmap2,pol=False)
        ell= numpy.arange(len(denscl))
        save_pickles(densname,ell,denscl,densmap,denscl2,densmap2)
    else:
        with open(densname,'rb') as savefile:
            ell= pickle.load(savefile)
            denscl= pickle.load(savefile)
            densmap= pickle.load(savefile)
            denscl2= pickle.load(savefile)
            densmap2= pickle.load(savefile)
    # dust map Cl and cross-power with dens
    combinedname= basename+'_D%.1f_combinedcl.sav' % dist
    bestfitloaded= False
    if os.path.exists(combinedname):
        with open(combinedname,'rb') as savefile:
            ell= pickle.load(savefile)
            combinedcl= pickle.load(savefile)
            combinedcr= pickle.load(savefile)
            combinedmcl= pickle.load(savefile)
            combinedmcr= pickle.load(savefile)
            combinedmcr2= pickle.load(savefile)
            bestfitloaded= True
    if not bestfitloaded:
        # do the best-fit
        combinedmap= dust.load_combined(dist,nest=False,nside_out=_NSIDE)
        print numpy.sum(numpy.isnan(combinedmap))
        combinedmap[numpy.isnan(combinedmap)]= 0.
        # Sample over the distribution of MG
        combinedmask= numpy.zeros_like(combinedmap)
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        print "Computing effective selection function"
        for jj in range(_NGSAMPLES):
            combinedmask+= ((combinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                *(combinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
        combinedmask/= _NGSAMPLES
        print "Computing Cl of extinction map"
        combinedcl= healpy.sphtfunc.anafast(combinedmap,pol=False)
        print "Computing cross of extinction map w/ densmap"
        combinedcr= healpy.sphtfunc.anafast(combinedmap,map2=densmap,pol=False)
        print "Computing Cl of effective selection function"
        combinedmcl= healpy.sphtfunc.anafast(combinedmask,pol=False)
        print "Computing cross of effective selection function w/ densmap"
        combinedmcr= healpy.sphtfunc.anafast(combinedmask,map2=densmap,pol=False)
        print "Computing cross of effective selection function w/ densmap2"
        combinedmcr2= healpy.sphtfunc.anafast(combinedmask,map2=densmap2,pol=False)
        # Save
        save_pickles(combinedname,ell,combinedcl,combinedcr,
                     combinedmcl,combinedmcr,combinedmcr2)
        gc.collect()
    # Plot (2l+1)Cl!!
    # Can smooth the masked power spectrum, perhaps underplot the non-smoothed in gray
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(combinedmcl)[1:],k=3,s=300.)
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(numpy.fabs(combinedmcr))[1:],k=3,s=10000.)
    # First plot the power-spectrum, then the cross-correlation, then the
    # cumulative sum
    bovy_plot.bovy_print(fig_height=3.)
    yrange=[10.**-12.,20.],
    line1= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*combinedcl[1:],
                               'k-',loglog=True,
                               ylabel=r'$(2\ell+1)\,C_\ell$',
                               xrange=[0.5,20000],
                               yrange=yrange,
                               zorder=3)
    line2= bovy_plot.bovy_plot(ell[2::2],
                               (2.*ell[2::2]+1.)*denscl[2::2],
                               'b-',overplot=True)
    line3= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*combinedmcl[1:],
                               'r-',overplot=True)
    # Add legend
    if dist == 5.:
        pyplot.legend((line2[0],line1[0],line3[0]),
                      (r'$\mathrm{exp.\ disk\ w/}$'+'\n'+r'$h_R = 3\,\mathrm{kpc},$'+'\n'+r'$h_Z = 0.3\,\mathrm{kpc}$',
                       r'$\mathrm{extinction\ map}$',
                       r'$\mathrm{effective\ selection\ function}$'),
                      loc='lower left',bbox_to_anchor=(.02,.02),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False) 
        bovy_plot.bovy_text(r'$\mathrm{power\ spectrum}$',top_right=True,size=16.)
    nullfmt   = NullFormatter()         # no labels
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname)
    # Cross-correlation
    bovy_plot.bovy_print(fig_height=3.)
    line1= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*numpy.fabs(combinedcr[1:]),
                               'k-',loglog=True,
                               ylabel=r'$(2\ell+1)\,C^{\mathrm{cross}}_\ell$',
                               xrange=[0.5,20000],
                               yrange=yrange,
                               zorder=1)
    line2= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*numpy.fabs(combinedmcr[1:]),
                               'r-',overplot=True,zorder=2)
    # Add legend
    if dist == 5.:
        pyplot.legend((line1[0],line2[0]),
                      (r'$\mathrm{extinction\ map}$',
                       r'$\mathrm{effective\ selection}$'+'\n'+r'$\mathrm{function}$'),
                      loc='lower left',bbox_to_anchor=(.02,.02),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False) 
        bovy_plot.bovy_text(r'$\mathrm{cross\ power\ spectrum\ w/\ density}$',top_right=True,size=16.)
    #sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],
    #                                 numpy.log(numpy.fabs(combinedmcr))[1:],
    #                                 k=3,s=100000.)
    #bovy_plot.bovy_plot(ell[1:],
    #                    10.*(2.*ell[1:]+1.)*numpy.exp(sp(numpy.log(ell[1:]))),
    #                    'r-',overplot=True,zorder=2)
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname.replace('powspec','crosspowspec'))
    effvol= numpy.sum((2.*ell+1.)*combinedmcr)
    #effvol2= numpy.sum((2.*ell+1.)*combinedmcr2)
    matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
    line1= bovy_plot.bovy_plot(ell[1:],
                               numpy.fabs(numpy.log(effvol)
                                          -numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr)))[1:],
                               'k-',loglog=True,
                               xlabel=r'$\ell$',
                               ylabel=r'$\left|\Delta\ln\sum_{\ell}\sum_{m}\nu_{*,\ell m}\,\textswab{S}_{\ell m}\right|$',
                               xrange=[0.5,20000],
                               yrange=[2.*10.**-13.,20.],
                               zorder=3)
    """
    line2= bovy_plot.bovy_plot(ell[1:],
                               numpy.fabs(numpy.log(effvol)
                                          -numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr))
                                          -numpy.log(effvol2)
                                          +numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr2)))[1:],
                               'k--',loglog=True,
                               overplot=True,zorder=2)
    # Add legend
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{exp.\ disk\ top\ panel}$',
                   r'$\mathrm{relative\ wrt\ exp.\ disk\ w/}$'+'\n'+
                   r'$h_R = 2\,\mathrm{kpc}, h_Z = 0.9\,\mathrm{kpc}$'),
                   loc='lower right',#bbox_to_anchor=(.91,.375),
                   numpoints=8,
                   prop={'size':14},
                   frameon=False) 
    """
    if dist == 5.:
        bovy_plot.bovy_text(r'$\mathrm{error\ in}\ \ln\ \mathrm{effective\ area}$',top_right=True,size=16.)
    bovy_plot.bovy_end_print(plotname.replace('powspec','cumulcrosspowspec')) 
    return None
示例#9
0
def plot_powspec(dist, basename, plotname):
    # Density
    G0 = 0.68 + dust.dist2distmod(dist)
    densname = basename + '_D%.1f_denscl.sav' % dist
    if not os.path.exists(densname):
        densmap = densprofiles.healpixelate(dist,
                                            densprofiles.expdisk,
                                            [1. / 3., 1. / 0.3],
                                            nside=_NSIDE,
                                            nest=False)
        denscl = healpy.sphtfunc.anafast(densmap, pol=False)
        densmap2 = densprofiles.healpixelate(dist,
                                             densprofiles.expdisk,
                                             [1. / 2., 1. / 0.9],
                                             nside=_NSIDE,
                                             nest=False)
        denscl2 = healpy.sphtfunc.anafast(densmap2, pol=False)
        ell = numpy.arange(len(denscl))
        save_pickles(densname, ell, denscl, densmap, denscl2, densmap2)
    else:
        with open(densname, 'rb') as savefile:
            ell = pickle.load(savefile)
            denscl = pickle.load(savefile)
            densmap = pickle.load(savefile)
            denscl2 = pickle.load(savefile)
            densmap2 = pickle.load(savefile)
    # dust map Cl and cross-power with dens
    combinedname = basename + '_D%.1f_combinedcl.sav' % dist
    bestfitloaded = False
    if os.path.exists(combinedname):
        with open(combinedname, 'rb') as savefile:
            ell = pickle.load(savefile)
            combinedcl = pickle.load(savefile)
            combinedcr = pickle.load(savefile)
            combinedmcl = pickle.load(savefile)
            combinedmcr = pickle.load(savefile)
            combinedmcr2 = pickle.load(savefile)
            bestfitloaded = True
    if not bestfitloaded:
        # do the best-fit
        combinedmap = dust.load_combined(dist, nest=False, nside_out=_NSIDE)
        print numpy.sum(numpy.isnan(combinedmap))
        combinedmap[numpy.isnan(combinedmap)] = 0.
        # Sample over the distribution of MG
        combinedmask = numpy.zeros_like(combinedmap)
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        print "Computing effective selection function"
        for jj in range(_NGSAMPLES):
            combinedmask+= ((combinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                *(combinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
        combinedmask /= _NGSAMPLES
        print "Computing Cl of extinction map"
        combinedcl = healpy.sphtfunc.anafast(combinedmap, pol=False)
        print "Computing cross of extinction map w/ densmap"
        combinedcr = healpy.sphtfunc.anafast(combinedmap,
                                             map2=densmap,
                                             pol=False)
        print "Computing Cl of effective selection function"
        combinedmcl = healpy.sphtfunc.anafast(combinedmask, pol=False)
        print "Computing cross of effective selection function w/ densmap"
        combinedmcr = healpy.sphtfunc.anafast(combinedmask,
                                              map2=densmap,
                                              pol=False)
        print "Computing cross of effective selection function w/ densmap2"
        combinedmcr2 = healpy.sphtfunc.anafast(combinedmask,
                                               map2=densmap2,
                                               pol=False)
        # Save
        save_pickles(combinedname, ell, combinedcl, combinedcr, combinedmcl,
                     combinedmcr, combinedmcr2)
        gc.collect()
    # Plot (2l+1)Cl!!
    # Can smooth the masked power spectrum, perhaps underplot the non-smoothed in gray
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(combinedmcl)[1:],k=3,s=300.)
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(numpy.fabs(combinedmcr))[1:],k=3,s=10000.)
    # First plot the power-spectrum, then the cross-correlation, then the
    # cumulative sum
    bovy_plot.bovy_print(fig_height=3.)
    yrange = [10.**-12., 20.],
    line1 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) * combinedcl[1:],
                                'k-',
                                loglog=True,
                                ylabel=r'$(2\ell+1)\,C_\ell$',
                                xrange=[0.5, 20000],
                                yrange=yrange,
                                zorder=3)
    line2 = bovy_plot.bovy_plot(ell[2::2],
                                (2. * ell[2::2] + 1.) * denscl[2::2],
                                'b-',
                                overplot=True)
    line3 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) * combinedmcl[1:],
                                'r-',
                                overplot=True)
    # Add legend
    if dist == 5.:
        pyplot.legend(
            (line2[0], line1[0], line3[0]),
            (r'$\mathrm{exp.\ disk\ w/}$' + '\n' +
             r'$h_R = 3\,\mathrm{kpc},$' + '\n' + r'$h_Z = 0.3\,\mathrm{kpc}$',
             r'$\mathrm{extinction\ map}$',
             r'$\mathrm{effective\ selection\ function}$'),
            loc='lower left',
            bbox_to_anchor=(.02, .02),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
        bovy_plot.bovy_text(r'$\mathrm{power\ spectrum}$',
                            top_right=True,
                            size=16.)
    nullfmt = NullFormatter()  # no labels
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname)
    # Cross-correlation
    bovy_plot.bovy_print(fig_height=3.)
    line1 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) *
                                numpy.fabs(combinedcr[1:]),
                                'k-',
                                loglog=True,
                                ylabel=r'$(2\ell+1)\,C^{\mathrm{cross}}_\ell$',
                                xrange=[0.5, 20000],
                                yrange=yrange,
                                zorder=1)
    line2 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) *
                                numpy.fabs(combinedmcr[1:]),
                                'r-',
                                overplot=True,
                                zorder=2)
    # Add legend
    if dist == 5.:
        pyplot.legend((line1[0], line2[0]),
                      (r'$\mathrm{extinction\ map}$',
                       r'$\mathrm{effective\ selection}$' + '\n' +
                       r'$\mathrm{function}$'),
                      loc='lower left',
                      bbox_to_anchor=(.02, .02),
                      numpoints=8,
                      prop={'size': 14},
                      frameon=False)
        bovy_plot.bovy_text(r'$\mathrm{cross\ power\ spectrum\ w/\ density}$',
                            top_right=True,
                            size=16.)
    #sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],
    #                                 numpy.log(numpy.fabs(combinedmcr))[1:],
    #                                 k=3,s=100000.)
    #bovy_plot.bovy_plot(ell[1:],
    #                    10.*(2.*ell[1:]+1.)*numpy.exp(sp(numpy.log(ell[1:]))),
    #                    'r-',overplot=True,zorder=2)
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname.replace('powspec', 'crosspowspec'))
    effvol = numpy.sum((2. * ell + 1.) * combinedmcr)
    #effvol2= numpy.sum((2.*ell+1.)*combinedmcr2)
    matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
    line1 = bovy_plot.bovy_plot(
        ell[1:],
        numpy.fabs(
            numpy.log(effvol) -
            numpy.log(numpy.cumsum((2. * ell + 1.) * combinedmcr)))[1:],
        'k-',
        loglog=True,
        xlabel=r'$\ell$',
        ylabel=
        r'$\left|\Delta\ln\sum_{\ell}\sum_{m}\nu_{*,\ell m}\,\textswab{S}_{\ell m}\right|$',
        xrange=[0.5, 20000],
        yrange=[2. * 10.**-13., 20.],
        zorder=3)
    """
    line2= bovy_plot.bovy_plot(ell[1:],
                               numpy.fabs(numpy.log(effvol)
                                          -numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr))
                                          -numpy.log(effvol2)
                                          +numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr2)))[1:],
                               'k--',loglog=True,
                               overplot=True,zorder=2)
    # Add legend
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{exp.\ disk\ top\ panel}$',
                   r'$\mathrm{relative\ wrt\ exp.\ disk\ w/}$'+'\n'+
                   r'$h_R = 2\,\mathrm{kpc}, h_Z = 0.9\,\mathrm{kpc}$'),
                   loc='lower right',#bbox_to_anchor=(.91,.375),
                   numpoints=8,
                   prop={'size':14},
                   frameon=False) 
    """
    if dist == 5.:
        bovy_plot.bovy_text(
            r'$\mathrm{error\ in}\ \ln\ \mathrm{effective\ area}$',
            top_right=True,
            size=16.)
    bovy_plot.bovy_end_print(plotname.replace('powspec', 'cumulcrosspowspec'))
    return None
def plot_distanceintegral_fewfields(savename,plotname,apogee=False):
    #ls and bs of the patches
    ls= [280.,30.,12.,37.5,90.,127.5,30.,60.,20.,-20.,-40.]
    bs= [45.,4.,2.,0.,0.,0.,0.,0.,0.,0.,0.]
    radius= 1.49
    locs= [4214,4244,4378,4312,4242,4318,4240,4241] # for apogee
    # If we are doing APOGEE selection, load the APOGEE selection function
    if apogee:
        selectFile= '../savs/selfunc-nospdata.sav'
        if os.path.exists(selectFile):
            with open(selectFile,'rb') as savefile:
                apo= pickle.load(savefile)
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            area= pickle.load(savefile)
            if apogee:
                area_cdens= pickle.load(savefile)
    else: 
        if not apogee:
            # For samping over the absolute magnitude distribution
            iso= gaia_rc.load_iso()
            Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        # Loop through each distance slice
        area= numpy.zeros((len(ls),len(dust._GREEN15DISTS)))
        if apogee:
            area_cdens= numpy.zeros((len(ls),len(dust._GREEN15DISTS)))
        for ii,dist in enumerate(dust._GREEN15DISTS):
            print "Working on distance %i: %f" % (ii,dist)
            G0= 0.68+dust.dist2distmod(dist)
            H0= -1.49+dust.dist2distmod(dist)
            # Load the dust map
            combinedmap= dust.load_combined(dist,nest=False,nside_out=_NSIDE)
            # Loop through a few patches
            theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                                 numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                                 nest=False)
            cosb= numpy.sin(theta)
            for ff,(ll,bb) in enumerate(zip(ls,bs)):
                if ff >= len(ls)-3*apogee: break
                vec= healpy.pixelfunc.ang2vec((90.-bb)*_DEGTORAD,ll*_DEGTORAD)
                ipixs= healpy.query_disc(_NSIDE,vec,radius*_DEGTORAD,
                                         inclusive=False,nest=False)
                ipixIndx= numpy.in1d(numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                     ipixs,assume_unique=True)
                # Calculate the density
                densmap= densprofiles.expdisk(phi[ipixIndx],
                                              numpy.pi/2.-theta[ipixIndx],
                                              dist*numpy.ones(len(ipixs)),
                                              glon=True,
                                              params=[1./3.,1./0.3])
                combinedmask= numpy.zeros(len(ipixs))
                tcombinedmap= combinedmap[ipixIndx]
                if apogee:
                    # Loop through the three cohorts
                    for c in ['short','medium','long']:
                        hmin= apo.Hmin(locs[ff],cohort=c)
                        hmax= apo.Hmax(locs[ff],cohort=c)
                        combinedmask+= ((tcombinedmap > (hmin-H0))\
                                            *(tcombinedmap < (hmax-H0))).astype('float')*apo(locs[ff],hmin+0.01)
                else:
                    for jj in range(_NGSAMPLES):
                        combinedmask+= ((tcombinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                            *(tcombinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
                combinedmask/= _NGSAMPLES
                # Compute cross correlation
                area[ff,ii]= float(numpy.sum(cosb[ipixIndx]*densmap\
                                                 *combinedmask))
                if apogee:
                    # Also store the approximation that the density is constant
                    cdens= densprofiles.expdisk(ll*_DEGTORAD,bb*_DEGTORAD,dist,
                                                glon=True,
                                                params=[1./3.,1./0.3])
                    area_cdens[ff,ii]= float(numpy.sum(cosb[ipixIndx]*cdens\
                                                           *combinedmask))
        if apogee:
            save_pickles(savename,area,area_cdens)
        else:
            save_pickles(savename,area)
    # Plot the power spectrum
    if True:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        colors=['b','g','r','c','gold','m','k','orange','y','b','g']
        lss=['-','-','-','-','-','-','-','-','-','--','--']
        for ff in range(len(ls)):
            if ff >= len(ls)-3*apogee: break
            psdx, psd= signal.periodogram(area[ff]*dust._GREEN15DISTS**3./numpy.sum(area[ff]*dust._GREEN15DISTS**3.),
                                          fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                                          detrend=lambda x: x,scaling='spectrum')
            bovy_plot.bovy_plot(psdx[1:],psd[1:],
                                '-',loglog=True,
                                xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                                ylabel=r'$P_k$',
                                xrange=[0.04,4.],
                                color=colors[ff],ls=lss[ff],
                                overplot=ff > 0)
            if ff == 0:
                bovy_plot.bovy_text(r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
                                    bottom_left=True,size=16.)
        bovy_plot.bovy_end_print(plotname)               
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        for ff in range(len(ls)):
            if ff >= len(ls)-3*apogee: break
            bovy_plot.bovy_plot(dust._GREEN15DISTMODS,
                                area[ff]*dust._GREEN15DISTS**3.,
                                'k-',
                                xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
                                ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    for ff in range(len(ls)):
        if ff >= len(ls)-3*apogee: break
        spl= interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                      area[ff]*dust._GREEN15DISTS**3.,
                                                  k=5)
        fthder= [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
        print "Simpson error (%f,%f)= %g, volume = %g" % (ls[ff],bs[ff],0.5**4./180.*numpy.mean(numpy.fabs(fthder))/integrate.simps(area[ff]*dust._GREEN15DISTS**3.,dx=0.5),numpy.sum(area[ff]*dust._GREEN15DISTS**3.))
    return None