def plot_distanceintegral(savename,plotname,rmcenter=False,
                          onlygreen=False):
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            area= pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                             numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                             nest=False)
        cosb= numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename,area)
    # Plot the power spectrum
    if True:
        psdx, psd= signal.periodogram(area*dust._GREEN15DISTS**3./numpy.sum(area*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                                      detrend=lambda x: x,scaling='spectrum')
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(psdx[1:],psd[1:],
                            'k-',loglog=True,
                            xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$P_k$',
                            xrange=[0.04,4.])
        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}"]
        bovy_plot.bovy_plot(dust._GREEN15DISTMODS,
                            area*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)
    spl= interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                  area*dust._GREEN15DISTS**3.,
                                                  k=5)
    fthder= [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
    print "Simpson error= %g, volume= %g" % (0.5**4./180.*numpy.mean(numpy.fabs(fthder))/integrate.simps(area*dust._GREEN15DISTS**3.,dx=0.5),numpy.sum(area*dust._GREEN15DISTS**3.))
    return None
Exemple #2
0
def plot_distanceareaintegral(savename,
                              plotname,
                              rmcenter=False,
                              onlygreen=False):
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi = healpy.pixelfunc.pix2ang(
            _NSIDE,
            numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
            nest=False)
        cosb = numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceAreaIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename, area)
    # Plot the power spectrum
    area = numpy.array(area)
    if True:
        psdthis = ((area.T * dust._GREEN15DISTS**3.).T / numpy.sum(
            (area.T * dust._GREEN15DISTS**3.), axis=1))
        psdx, psd = signal.periodogram(
            psdthis,
            fs=1. / (dust._GREEN15DISTMODS[1] - dust._GREEN15DISTMODS[0]),
            detrend=lambda x: x,
            scaling='spectrum',
            axis=0)
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        healpy.visufunc.mollview(numpy.log10(psd[-2]),
                                 nest=False,
                                 xsize=4000,
                                 min=-10.,
                                 max=-3.,
                                 cmap='gist_yarg',
                                 title="")
        bovy_plot.bovy_end_print(plotname)
    return None
def plot_distanceareaintegral(savename,plotname,rmcenter=False,
                          onlygreen=False):
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            area= pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                             numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                             nest=False)
        cosb= numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceAreaIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename,area)
    # Plot the power spectrum
    area= numpy.array(area)
    if True:       
        psdthis= ((area.T*dust._GREEN15DISTS**3.).T/numpy.sum((area.T*dust._GREEN15DISTS**3.),axis=1))
        psdx, psd= signal.periodogram(psdthis,
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                                      detrend=lambda x: x,scaling='spectrum',
                                      axis=0)
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        healpy.visufunc.mollview(numpy.log10(psd[-2]),
                                 nest=False,
                                 xsize=4000,min=-10.,max=-3.,
                                 cmap='gist_yarg',
                                 title="")
        bovy_plot.bovy_end_print(plotname)               
    return None
Exemple #4
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
def plot_distanceintegral_smallpatch(savename, plotname):
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
    else:
        # Load the patch
        hpIndx, dmap = read_patch()
        # For samping over the absolute magnitude distribution
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi = healpy.pixelfunc.pix2ang(_NSIDE_HIRES, hpIndx, nest=False)
        cosb = numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceIntegrandHires(\
                _HIRESGREEN15DISTS[x],theta,phi,cosb,Gsamples,dmap),
                                 range(len(_HIRESGREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(_HIRESGREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename, area)
    # Plot the power spectrum
    if True:
        psdx, psd = signal.periodogram(
            area * _HIRESGREEN15DISTS**3. /
            numpy.sum(area * _HIRESGREEN15DISTS**3.),
            fs=1. / (_HIRESGREEN15DISTMODS[1] - _HIRESGREEN15DISTMODS[0]),
            detrend=lambda x: x,
            scaling='spectrum')
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(psdx[1:],
                            psd[1:],
                            'k-',
                            loglog=True,
                            xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$P_k$',
                            xrange=[0.04, 4.])
        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}"]
        bovy_plot.bovy_plot(
            _HIRESGREEN15DISTMODS,
            area * _HIRESGREEN15DISTS**3.,
            'k-',
            xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
            ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    spl = interpolate.InterpolatedUnivariateSpline(_HIRESGREEN15DISTMODS,
                                                   area *
                                                   _HIRESGREEN15DISTS**3.,
                                                   k=5)
    fthder = [spl.derivatives(dm)[4] for dm in _HIRESGREEN15DISTMODS]
    print "Simpson error= ", 0.5**4. / 180. * numpy.mean(
        numpy.fabs(fthder)) / integrate.simps(area * _HIRESGREEN15DISTS**3.,
                                              dx=0.5)
    return None
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
Exemple #7
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