Exemplo n.º 1
0
def plotJuricIvezicDiff(dir):
    #Plot difference for a few metallicities
    fehs= [0.,-0.1,-0.2,-0.3,-0.5,-1.,-1.5]
    colors= ['b','c','g','y','orange','m','r']
    #Set up plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([-100.,-100.],[-100.,-100],'k,',
                        xrange=[0.47,0.58],
                        yrange=[-1.,1.],
                        xlabel=r'$g-r\ [\mathrm{mag}]$',
                        ylabel=r'$\mathrm{DM}_{\mathrm{Juri\acute{c}}}-\mathrm{DM}_{\mathrm{Ivezi\acute{c}}}\ [\mathrm{mag}]$')
    xlegend, ylegend, dy= 0.55, 0.8,-0.12
    grs= numpy.linspace(0.48,0.55,1001)
    for ii in range(len(fehs)):
        ybright= -1.*(_mr_ri_bright(_ri_gr(grs))-_mr_gi(_gi_gr(grs),fehs[ii]))
        yfaint= -1.*(_mr_ri_faint(_ri_gr(grs))-_mr_gi(_gi_gr(grs),fehs[ii]))
        bovy_plot.bovy_plot(grs,
                            ybright,
                            '-',color=colors[ii],
                            overplot=True)
        bovy_plot.bovy_plot(grs,
                            yfaint,
                            '--',color=colors[ii],
                            overplot=True)
        bovy_plot.bovy_text(xlegend,ylegend+ii*dy,
                            r'$[\mathrm{Fe/H]=%+4.1f}$' % fehs[ii],
                            color=colors[ii])
    bovy_plot.bovy_end_print(os.path.join(dir,'dm_juric_ivezic.'+_EXT))
Exemplo n.º 2
0
def veldist_1d_rolr(plotfilename,phi=_DEFAULTPHI,R=_DEFAULTR,
                    ngrid=201,saveDir='../bar/1dvar/'):
    """
    NAME:
       veldist_1d_rolr
    PURPOSE:
       make a plot showing the influence of the bar R_OLR
    INPUT:
       plotfilename - filename for figure
       phi - Galactocentric azimuth
       R - Galactocentric radius
       ngrid - number of grid-points to calculate the los velocity distribution
               on
       saveDir - save pickles here
    OUTPUT:
       Figure in plotfilename
    HISTORY:
       2010-09-11 - Written - Bovy (NYU)
    """
    rolrs= [0.85,0.9,0.95]

    vloslinspace= (-.9,.9,ngrid)
    vloss= sc.linspace(*vloslinspace)

    vlosds= []
    basesavefilename= os.path.join(saveDir,'rolr_')
    for rolr in rolrs:
        thissavefilename= basesavefilename+'%.3f.sav' % rolr
        if os.path.exists(thissavefilename):
            print "Restoring los-velocity distribution at R_OLR %.2f" % rolr
            savefile= open(thissavefilename,'r')
            vlosd= pickle.load(savefile)
            savefile.close()
        else:
            print "Calculating los-velocity distribution at R_OLR %.2f" % rolr
            potparams= (rolr,0.01,25.*_degtorad,.8,None)
            vlosd= predictVlos(vloslinspace,
                               l=phi,
                               d=R,
                               distCoord='GCGC',
                               pot='bar',beta=0.,
                               potparams=potparams)
            vlosd= vlosd/(sc.nansum(vlosd)*(vloss[1]-vloss[0]))
            savefile= open(thissavefilename,'w')
            pickle.dump(vlosd,savefile)
            savefile.close()
        vlosds.append(vlosd)
    #Plot
    plot.bovy_print()
    plot.bovy_plot(vloss,vlosds[1],'k-',zorder=3,
                   xrange=[vloslinspace[0],vloslinspace[1]],
                   yrange=[0.,sc.amax(sc.array(vlosds).flatten())*1.1],
                   xlabel=r'$v_{\mathrm{los}} / v_0$')
    plot.bovy_plot(vloss,vlosds[0],ls='-',color='0.75',
                   overplot=True,zorder=2,lw=2.)
    plot.bovy_plot(vloss,vlosds[2],ls='-',color='0.5',
                   overplot=True,zorder=2,lw=1.5)
    plot.bovy_text(r'$\mathrm{bar}\ R_{\mathrm{OLR}}$',title=True)
    plot.bovy_text(0.36,.75,r'$R_{\mathrm{OLR}} = 0.95\ R_0$'+'\n'+r'$R_{\mathrm{OLR}} = 0.90\ R_0$'+ '\n'+r'$R_{\mathrm{OLR}} = 0.85\ R_0$')
    plot.bovy_end_print(plotfilename)
Exemplo n.º 3
0
def triangleMAPs(savefilename,basename):
    with open(savefilename,'rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
        bf_g15= numpy.array(pickle.load(savefile))
        samples_g15= numpy.array(pickle.load(savefile))
        bf_zero= numpy.array(pickle.load(savefile))
        samples_zero= numpy.array(pickle.load(savefile))
    labels= []
    for jj in range(samples.shape[2]):
        labels.append(r"$\mathrm{param}\ %i$" % jj)
    maps= define_rcsample.MAPs()
    for ii, map in enumerate(maps.map()):
        if ii >= len(bf): break
        tfeh= numpy.nanmedian(map['FE_H'])
        tafe= numpy.nanmedian(map[define_rcsample._AFETAG])
        for tbf,tsamples,ext in zip([bf,bf_g15,bf_zero],
                                    [samples,samples_g15,samples_zero],
                                    ['fid','g15','zero']):
            try:
                triangle.corner(tsamples[ii,].T,quantiles=[0.16, 0.5, 0.84],
                                labels=labels,
                                show_titles=True,title_args={"fontsize": 12},
                                bins=21)
            except ValueError: pass
            else:
                bovy_plot.bovy_text(r'$[\mathrm{{Fe/H}}] = {feh:.1f},$'\
                                        .format(feh=tfeh)+'\n'
                                    +r'$[\alpha/\mathrm{{Fe}}] = {afe:.2f}$'\
                                        .format(afe=tafe),
                                    top_left=True,size=16.)
                bovy_plot.bovy_end_print(basename+"_%i_%s.png" % (ii,ext))
    return None
Exemplo n.º 4
0
def plotprops(options,args):
    #Go through all of the bins
    if options.sample.lower() == 'g':
        npops= 62
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        npops= 30
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    ndatas= pickle.load(savefile)
    savefile.close()
    for ii in range(npops):
        bovy_plot.bovy_print()
        bovy_plot.bovy_text(r'$[\mathrm{Fe/H}] = %.2f$' % (fehs[ii])
                            +'\n'
                            r'$[\alpha/\mathrm{Fe}] = %.3f$' % (afes[ii])
                            +'\n'
                            r'$N_{\mathrm{data}} = %i$' % (ndatas[ii])
                            +'\n'
                            r'$\ln h_R / 8\,\mathrm{kpc} = %.1f$' % (numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii])/8.)) 
                            +'\n'
                            +r'$\ln \sigma_R / 220\,\mathrm{km\,s}^{-1} = %.1f$' % (numpy.log(monoAbundanceMW.sigmar(fehs[ii],afes[ii])/220.))
                            +'\n'
                            +r'$\ln \sigma_Z / 220\,\mathrm{km\,s}^{-1} = %.1f$' % (numpy.log(monoAbundanceMW.sigmaz(fehs[ii],afes[ii])/220.)),
                            top_left=True,size=16.)
        #Plotname
        spl= options.outfilename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        bovy_plot.bovy_end_print(newname)
Exemplo n.º 5
0
def veldist_1d_vrconvolve(plotfilename,phi=_DEFAULTPHI,R=_DEFAULTR,
                        ngrid=201,saveDir='../bar/1dvar/'):
    """
    NAME:
       veldist_1d_vrconvolve
    PURPOSE:
       make a plot showing the influence of the los velocity uncertainties
    INPUT:
       plotfilename - filename for figure
       phi - Galactocentric azimuth
       R - Galactocentric radius
       ngrid - number of grid-points to calculate the los velocity distribution
               on
       saveDir - save pickles here
    OUTPUT:
       Figure in plotfilename
    HISTORY:
       2010-09-11 - Written - Bovy (NYU)
    """
    convolves= [0.02,0.04,0.08]#0, 5, 10, 20 km/s

    vloslinspace= (-.9,.9,ngrid)
    vloss= sc.linspace(*vloslinspace)

    vlosds= []
    thissavefilename= os.path.join(saveDir,'convolve_')+'%.1f.sav' % 0.
    print "Restoring los-velocity distribution at distance uncertainties %.1f" % 0.
    savefile= open(thissavefilename,'r')
    vlosd= pickle.load(savefile)
    savefile.close()
    vlosds.append(vlosd)
    basesavefilename= os.path.join(saveDir,'vrconvolve_')
    for distsig in convolves:
        thissavefilename= os.path.join(saveDir,'convolve_')+'%.1f.sav' % 0.
        print "Restoring los-velocity distribution at distance uncertainties %.1f" % 0.
        savefile= open(thissavefilename,'r')
        vlosd= pickle.load(savefile)
        savefile.close()
        #Create Gaussian
        gauss= sc.exp(-0.5*vloss**2./distsig**2.)
        #gauss= gauss/sc.sum(gauss)/(vloss[1]-vloss[0])
        vlosd= signal.convolve(vlosd,gauss,mode='same')
        vlosd= vlosd/sc.sum(vlosd)/(vloss[1]-vloss[0])
        vlosds.append(vlosd)
    #Plot
    plot.bovy_print()
    plot.bovy_plot(vloss,vlosds[0],'k-',zorder=3,
                   xrange=[vloslinspace[0],vloslinspace[1]],
                   yrange=[0.,sc.nanmax(sc.array(vlosds).flatten())*1.1],
                   xlabel=r'$v_{\mathrm{los}} / v_0$')
    plot.bovy_plot(vloss,vlosds[1],ls='-',color='0.75',
                   overplot=True,zorder=2,lw=2.)
    plot.bovy_plot(vloss,vlosds[2],ls='-',color='0.6',
                   overplot=True,zorder=2,lw=2.)
    plot.bovy_plot(vloss,vlosds[3],ls='-',color='0.45',
                   overplot=True,zorder=2,lw=2.)
    kms= r' \mathrm{km\ s}^{-1}$'
    plot.bovy_text(r'$\mathrm{line-of-sight\ velocity\ uncertainties}$',title=True)
    plot.bovy_text(0.4,.65,r'$\sigma_v = 0\ '+kms+'\n'+r'$\sigma_v = 5\ '+kms+'\n'+r'$\sigma_v = 10\ '+kms+'\n'+r'$\sigma_v = 20\ '+kms)
    plot.bovy_end_print(plotfilename)
Exemplo n.º 6
0
def plotAnIvezicDiff(dir):
    #Load An isochrones
    a= isodist.AnIsochrone()
    #Plot difference for a few metallicities
    fehs= [0.,-0.1,-0.2,-0.3,-0.5,-1.,-1.5]
    colors= ['b','c','g','y','orange','m','r']
    #Set up plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([-100.,-100.],[-100.,-100],'k,',
                        #xrange=[0.47,0.58],
                        xrange=[0.53,0.78],
                        yrange=[-0.25,.25],
                        xlabel=r'$g-r\ [\mathrm{mag}]$',
                        ylabel=r'$\mathrm{DM}_{\mathrm{An}}-\mathrm{DM}_{\mathrm{Ivezi\acute{c}}}\ [\mathrm{mag}]$')
    xlegend, ylegend, dy= 0.545, 0.2,-0.03
    for ii in range(len(fehs)):
        iso= a(numpy.log10(10.),feh=fehs[ii])
        #Get G dwarfs
        indx= (iso['g']-iso['r'] <= 0.75)*(iso['g']-iso['r'] >= 0.55)\
            *(iso['logg'] > 4.1)
        y= -1.*(iso['r'][indx]-_mr_gi(_gi_gr(iso['g'][indx]
                                             -iso['r'][indx]),fehs[ii]))
        bovy_plot.bovy_plot(iso['g'][indx]-iso['r'][indx],
                            y,
                            '-',color=colors[ii],
                            overplot=True)
        bovy_plot.bovy_text(xlegend,ylegend+ii*dy,
                            r'$[\mathrm{Fe/H]=%+4.1f}$' % fehs[ii],
                            color=colors[ii])
    bovy_plot.bovy_end_print(os.path.join(dir,'dm_an_ivezic.'+_EXT))
Exemplo n.º 7
0
def plot_data_h_jk(location=None,
                   plotfilename=os.path.join(OUTDIR, 'data_h_jk.' + OUTEXT)):
    data = readVclosData()
    if not location is None:
        if location == 0:
            locs = set(data['LOCATION'])
            for l in locs:
                plot_data_h_jk(location=l,
                               plotfilename=os.path.join(
                                   OUTDIR, 'data_h_jk_%i.' % l + OUTEXT))
            return None
        data = data[(data['LOCATION'] == location)]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['J0MAG'] - data['K0MAG'],
                        data['H0MAG'],
                        'k,',
                        xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                        ylabel=r'$H_0\ [\mathrm{mag}]$',
                        xrange=[0.4, 1.4],
                        yrange=[5., 14.],
                        onedhists=True,
                        bins=31)
    #Overplot distance if wanted
    if _PLOTDISTANCE:
        iso = isomodel(imfmodel='lognormalChabrier2001', Z=0.019, expsfh=True)
        nds = 101
        ds = numpy.zeros((nds, nds))
        jks = numpy.linspace(0.5, 1.2, nds)
        hs = numpy.linspace(14., 5., nds)
        for ii in range(nds):
            for jj in range(nds):
                ds[ii, jj] = iso.peak(jks[ii], hs[jj])
        #Now contour this
        levels = [1., 3., 10., 30.]
        colors = '0.6'  #['0.5','0.5','0.5','k','k','k']
        CS = pyplot.contour(jks,
                            hs,
                            ds.T,
                            levels=levels,
                            colors=colors,
                            zorder=10.,
                            linewidths=2.)
        ys = [5.3, 6.7, 9.22, 11.7]
        for ii in range(len(levels)):
            bovy_plot.bovy_text(1.21,
                                ys[ii],
                                r'$%.0f\ \mathrm{kpc}$' % levels[ii],
                                fontsize=14.,
                                color='0.3')
        if False:
            pyplot.clabel(CS,
                          levels,
                          inline=1,
                          fmt='%.0f',
                          fontsize=14,
                          colors=colors,
                          zorder=10.)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 8
0
def plot_apogee_jkz(plotfilename,sample):
    if sample == 'disk':
        data= readData()
    elif sample == 'halo':
        data= readData(halo=True)
    elif sample == 'bulge':
        data= readData(bulge=True)
    ntotal= len(data)
    #logg cut
    data= data[(data['LOGG_AVG'] < 2.8)*(data['LOGG_AVG'] > 1.8)]
    npass= len(data)
    #Deredden
    aj= data['AK_WISE']*2.5
    ah= data['AK_WISE']*1.55
    j0= data['JMAG']-aj
    h0= data['HMAG']-ah
    k0= data['KMAG']-data['AK_WISE']
    #calculate Zs
    zsolar= 0.019
    z= isodist.FEH2Z(data['METALS_AVG'])/zsolar
    #Plot
    bovy_plot.bovy_print()
    if sample == 'bulge':
        bovy_plot.bovy_plot(j0-k0,z,'ko',
                            xrange=[0.5,0.75],
                            yrange=[0.,0.03/zsolar],
                            xlabel=r'$(J-K_s)_0$',
                            ylabel=r'$Z/Z_\odot$',ms=5.)
    else:
        bovy_plot.scatterplot(j0-k0,z,'k,',
                              xrange=[0.5,0.75],
                              yrange=[0.,0.03/zsolar],
                              xlabel=r'$(J-K_s)_0$',
                              ylabel=r'$Z/Z_\odot$',
                              bins=21)
    #Overplot cuts
    jks= numpy.linspace(0.5,0.75,1001)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks)/zsolar,
                        'k--',lw=2.,overplot=True)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks,upper=True)/zsolar,
                        'k--',lw=2.,overplot=True)
    #Data between the cuts
    indx= (j0-k0 < 0.75)*(j0-k0 > 0.5)\
                   *(z <= rcmodel.jkzcut(j0-k0,upper=True)/zsolar)\
                   *(z >= rcmodel.jkzcut(j0-k0)/zsolar)
#    j0= j0[indx]
#    h0= h0[indx]
#    k0= k0[indx]
#    z= z[indx]
#    bovy_plot.bovy_plot(j0-k0,z,'w.',
#                        overplot=True,
#                        mec='w',
#                        ms=.5)
    bovy_plot.bovy_text(r'$\mathrm{APOGEE\ ' + sample + '\ sample}$',
                        title=True)
    bovy_plot.bovy_text(r'$%i/%i/%i$' % (numpy.sum(indx),npass,ntotal),
                        bottom_right=True,size=14.)
    bovy_plot.bovy_end_print(plotfilename)
    return None                        
def plot_chains(drct, nwalkers=12, ffmt=".dat"):
    """Plot MCMC Chains.

    Parameters
    ----------
    drct : str
        directory

    """
    drct = drct + "/" if not drct.endswith("/") else drct

    # getting number of chains
    files = os.listdir(drct)  # all files in directory
    chains = np.sort([f for f in files if f.endswith(ffmt)
                      ])  # get files with right file format.

    npot = len(chains)
    ncol = 4
    nrow = int(np.ceil(npot / ncol))
    fig = plt.figure(figsize=(16, nrow * ncol))  # todo, dynamic figsize
    cmap = plt.get_cmap("plasma")

    for en, (ii, fn) in enumerate(zip(range(len(chains)), chains)):
        # fn = drct + "mwpot14-fitsigma-%i.dat" % ii
        data = np.loadtxt(drct + fn, comments="#", delimiter=",")
        plt.subplot(nrow, 4, en + 1)
        sdata = np.reshape(data[:, -1],
                           (len(data[:, 5]) // nwalkers, nwalkers))
        for jj in range(nwalkers):
            if ii % 4 == 0 and jj == 0:
                tylabel = r"$\ln \mathcal{L}$"
            else:
                tylabel = None
            if ii // 4 == nrow - 1 and jj == 0:
                txlabel = r"$\#\ \mathrm{of\ steps}$"
            else:
                txlabel = None
            bovy_plot.bovy_plot(
                list(range(len(sdata[:, jj]))),
                sdata[:, jj],
                "-",
                alpha=0.4,
                color=cmap(jj / 11.0),
                # yrange=[-40.0, -15.0],
                yrange=[-100.0, 0.0],
                ylabel=tylabel,
                xlabel=txlabel,
                gcf=True,
            )
            bovy_plot.bovy_text(r"$\mathrm{Potential}\ %i$" % ii,
                                size=17.0,
                                top_left=True)
        nburn = determine_nburn(drct + fn) // nwalkers
        plt.axvline(nburn, lw=2.0, zorder=1, color="k")

    plt.tight_layout()

    return fig
def set_ranges_and_labels_dens():
    bovy_plot.bovy_text(r'$\sqrt{\delta\delta}$',top_left=True,size=18.)
    xlabel(r'$1/k_{\xi}\,(\mathrm{deg})$')
    ylim(0.01,10.)
    xlim(1.,100.)
    for axis in [gca().xaxis,gca().yaxis]:
        axis.set_major_formatter(FuncFormatter(
                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
    return None
Exemplo n.º 11
0
def plot_dfcorrections(plotfilename):
    niters= [1,2,3,4,5,10,15,20,25]
    bovy_plot.bovy_print(fig_height=7.,fig_width=8.)
    ii= 0
    # Load DF
    pyplot.subplot(2,1,1)
    dfc= dehnendf(beta=0.,correct=True,niter=niters[ii])
    bovy_plot.bovy_plot(dfc._corr._rs,
                        numpy.log(dfc._corr._corrections[:,0]),
                        '-',gcf=True,color=cm.jet(1.),lw=2.,zorder=1,
                        xrange=[0.,5.],
                        yrange=[-0.25,0.25],
                        ylabel=r'$\ln \Sigma_{\mathrm{out}}(R)-\ln\Sigma_{\mathrm{DF}}(R)$')
    linthresh= 0.0001
    pyplot.yscale('symlog',linthreshy=linthresh)
    for ii,niter in enumerate(niters[1:]):
        dfcn= dehnendf(beta=0.,correct=True,niter=niter)
        dfcp= dehnendf(beta=0.,correct=True,niter=niter-1)
        bovy_plot.bovy_plot(dfc._corr._rs,
                            numpy.log(dfcn._corr._corrections[:,0])-numpy.log(dfcp._corr._corrections[:,0]),
                            '-',overplot=True,
                            color=cm.jet(1.-(ii+1)/float(len(niters))),lw=2.,
                            zorder=ii+2)
    pyplot.fill_between(numpy.linspace(0.,5.,2.),
                        -linthresh*numpy.ones(2),
                         linthresh*numpy.ones(2),color='0.9',
                         zorder=0)
    bovy_plot.bovy_text(4.,-0.00008,r'$\mathrm{linear\ scale}$',
                        backgroundcolor='w',size=16.)
    pyplot.subplot(2,1,2)
    bovy_plot.bovy_plot(dfc._corr._rs,
                        0.5*numpy.log(dfc._corr._corrections[:,1]),
                        '-',gcf=True,color=cm.jet(1.),lw=2.,zorder=1,
                        xrange=[0.,5.],
                        yrange=[-0.25,0.25],
                        xlabel=r'$R/R_0$',
                        ylabel=r'$\ln \sigma_{R,\mathrm{out}}(R)-\ln\sigma_{R,\mathrm{DF}}(R)$')
    pyplot.yscale('symlog',linthreshy=linthresh)
    for ii,niter in enumerate(niters[1:]):
        dfcn= dehnendf(beta=0.,correct=True,niter=niter)
        dfcp= dehnendf(beta=0.,correct=True,niter=niter-1)
        bovy_plot.bovy_plot(dfc._corr._rs,
                            numpy.log(dfcn._corr._corrections[:,1])-numpy.log(dfcp._corr._corrections[:,1]),
                            '-',overplot=True,
                            color=cm.jet(1.-(ii+1)/float(len(niters))),lw=2.,
                            zorder=ii+2)
    pyplot.fill_between(numpy.linspace(0.,5.,2.),
                        -linthresh*numpy.ones(2),
                         linthresh*numpy.ones(2),color='0.9',
                         zorder=0)
    bovy_plot.bovy_text(4.,-0.00008,r'$\mathrm{linear\ scale}$',
                        backgroundcolor='w',size=16.)
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 12
0
def simplePlot(location=4242,
               plotfile=None,
               predict=False,
               nv=11,
               dmax=10. / 8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data = readVclosData(**kwargs)
    data = data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range = [-200., 200.]
    hist, xvec, p = bovy_plot.bovy_hist(
        data['VHELIO'],
        range=range,
        bins=31,
        histtype='step',
        color='k',
        xlabel=
        r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs = numpy.linspace(range[0], range[1], nv)
        pred_dist = _calc_pred(pred_vs, location, numpy.mean(data['GLON']),
                               dmax)
        data_int = numpy.sum(hist) * (xvec[1] - xvec[0])
        pred_dist *= data_int / numpy.sum(pred_dist) / (pred_vs[1] -
                                                        pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,
                            pred_dist,
                            '-',
                            color='0.65',
                            overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location + '\n' +
                        r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,
                        size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
Exemplo n.º 13
0
def plotCombinedPDF(options,args):
    if options.sample.lower() == 'g':
        npops= 62
    elif options.sample.lower() == 'k':
        npops= 54
    if options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    savefile.close()
    #First calculate the derivative properties
    if not options.group is None:
        gafes, gfehs, legend= getMultiComparisonBins(options)
    else:
        legend= None
    if not options.multi is None:
        PDFs= multi.parallel_map((lambda x: calcAllPDFs(x,options,args)),
                                  range(npops),
                                  numcores=numpy.amin([options.multi,
                                                       npops,
                                                       multiprocessing.cpu_count()]))
    else:
        PDFs= []
        for ii in range(npops):
            PDFs.append(calcAllPDFs(ii,options,args))
    #Go through and combine
    combined_lnpdf= numpy.zeros((options.nrds,options.nfhs))
    for ii in range(npops):
        if not options.group is None:
            if numpy.amin((gfehs-fehs[ii])**2./0.1+(gafes-afes[ii])**2./0.0025) > 0.001:
                continue
        combined_lnpdf+= PDFs[ii]
    alogl= combined_lnpdf-numpy.nanmax(combined_lnpdf)
    #Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(numpy.exp(alogl).T,
                          origin='lower',cmap='gist_yarg',
                          interpolation='nearest',
                          xrange=[1.9,3.5],yrange=[-1./32.,1.+1./32.],
                          xlabel=r'$R_d\ (\mathrm{kpc})$',ylabel=r'$f_h$')
    if not legend is None:
        bovy_plot.bovy_text(legend,top_left=True,
                            size=14.)
    bovy_plot.bovy_end_print(options.outfilename)
    #Calculate and print derived properties
    derivProps= rawDerived(alogl,options,
                           vo=options.fixvc/_REFV0,zh=options.fixzh,
                           dlnvcdlnr=options.dlnvcdlnr)
    for key in derivProps.keys():
        if not '_err' in key:
            print key, derivProps[key], derivProps[key+'_err'], \
                derivProps[key]/derivProps[key+'_err'] 
    return None
Exemplo n.º 14
0
def _plotMRZ_single(XYZ,R,data,options,args,all=True,overplot=True,xrange=None,
                    Zrange=None,Rrange=None,yrange=None,colorrange=None,
                    fehrange=None):
    if all:
        bovy_plot.scatterplot(data.dered_g-data.dered_r,
                              data.feh,
                              'k,',
                              bins=21,
                              xrange=xrange,
                              yrange=yrange,
                              xlabel=r'$g-r\ [\mathrm{mag}]$',
                              ylabel=r'$[\mathrm{Fe/H}]$',
                              onedhists=True)
        platestr= '\mathrm{all\ plates}'
        bovy_plot.bovy_text(r'$'+platestr+'$'
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            len(data.feh),top_right=True,size=16)
    else:
        #Cut to range
        indx= (numpy.fabs(XYZ[:,2]) > Zrange[0])\
        *(numpy.fabs(XYZ[:,2]) <= Zrange[1])\
        *(R > Rrange[0])\
        *(R <= Rrange[1])
        thisdata= data[indx]
        if len(thisdata) > 1500:
            bovy_plot.scatterplot(thisdata.dered_g-thisdata.dered_r,
                                  thisdata.feh,
                                  'k,',
                                  bins=21,
                                  xrange=xrange,
                                  yrange=yrange,
                                  xlabel=r'$g-r\ [\mathrm{mag}]$',
                                  ylabel=r'$[\mathrm{Fe/H}]$',
                                  onedhists=True)
        else:
            bovy_plot.bovy_plot(thisdata.dered_g-thisdata.dered_r,
                                thisdata.feh,
                                'k,',
                                bins=21,
                                xrange=xrange,
                                yrange=yrange,
                                xlabel=r'$g-r\ [\mathrm{mag}]$',
                                ylabel=r'$[\mathrm{Fe/H}]$',
                                onedhists=True)
        if options.plottype.lower() == 'r':
            lbstr= r'$%i < R / \mathrm{kpc} \leq %i$' % (int(Rrange[0]),int(Rrange[1]))
        else:
            lbstr= r'$%i < |Z| / \mathrm{pc} \leq %i$' % (int(1000*Zrange[0]),int(1000*Zrange[1]))
        bovy_plot.bovy_text(r'$%i \ \ \mathrm{stars}$' % 
                            len(thisdata.feh)
                            +'\n'+
                            lbstr,top_right=True,size=16)
    return None
Exemplo n.º 15
0
def plotPriorSurf(plotfilename):
    #Calculate the surface density profile for each trial potential, then plot the range
    if '.png' in plotfilename:
        savefilename= plotfilename.replace('.png','.sav')
    elif '.ps' in plotfilename:
        savefilename= plotfilename.replace('.ps','.sav')
    if not os.path.exists(savefilename):
        options= setup_options(None)
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        options.fitdvt= False
        rs= numpy.linspace(4.2,9.8,101)
        rds= numpy.linspace(2.,3.4,8)
        fhs= numpy.linspace(0.,1.,16)
        surfz= numpy.zeros((len(rs),len(rds)*len(fhs)))+numpy.nan
        ro= 1.
        vo= 230./220.
        dlnvcdlnr= 0.
        zh= 400.
        for jj in range(len(rds)):
            for kk in range(len(fhs)):
                #Setup potential to calculate stuff
                potparams= numpy.array([numpy.log(rds[jj]/8.),vo,numpy.log(zh/8000.),fhs[kk],dlnvcdlnr])
                try:
                    pot= setup_potential(potparams,options,0,returnrawpot=True)
                except RuntimeError:
                    continue
                for ii in range(len(rs)):
                    surfz[ii,jj*len(fhs)+kk]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(rs[ii]/8.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
        #Find minimum and maximum curves
        minsurfz= numpy.nanmin(surfz,axis=1)
        maxsurfz= numpy.nanmax(surfz,axis=1)
        #Save
        save_pickles(savefilename,rs,minsurfz,maxsurfz)
    else:
        savefile= open(savefilename,'rb')
        rs= pickle.load(savefile)
        minsurfz= pickle.load(savefile)
        maxsurfz= pickle.load(savefile)
        savefile.close()
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([numpy.nan],[numpy.nan],'ko',
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$\Sigma(R,|Z| \leq 1.1\,\mathrm{kpc})\ (M_\odot\,\mathrm{pc}^{-2})$',
                        xrange=[4.,10.],
                        yrange=[10,1050.],
                        semilogy=True)
    pyplot.fill_between(rs,minsurfz,maxsurfz,
                        color='0.50')
    bovy_plot.bovy_text(8.,68.,r'$\odot$',size=16.,verticalalignment='center',
                        horizontalalignment='center')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 16
0
def plot_dustnearplane(plotname,green=False):
    if green: savefile= _SAVEFILE_GREEN
    else: savefile= _SAVEFILE_MARSHALL
    # Grid
    ls= numpy.linspace(15.,70.,_NL)
    bs= numpy.linspace(-2.,2.,_NB)
    if not os.path.exists(savefile):
        # Setup dust map
        if green:
            dmap= mwdust.Green15(filter='2MASS H')
        else:
            dmap= mwdust.Marshall06(filter='2MASS H')
        plotthis= numpy.empty((_NL,_NB))
        rad= 0.5 # deg
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                pa, ah= dmap.dust_vals_disk(ls[ii],bs[jj],7.,rad)
                plotthis[ii,jj]= numpy.sum(pa*ah)/numpy.sum(pa)
        save_pickles(savefile,plotthis)
    else:
        with open(savefile,'rb') as f:
            plotthis= pickle.load(f)
    # Now plot
    bovy_plot.bovy_print(fig_width=8.4,fig_height=4.)
    bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm,
#                          interpolation='nearest',
                          colorbar=True,shrink=0.45,
                          vmin=0.,vmax=2.-0.75*green,aspect=3.,
                          xrange=[ls[-1]+(ls[1]-ls[0])/2.,
                                  ls[0]-(ls[1]-ls[0])/2.],
                          yrange=[bs[0]-(bs[1]-bs[0])/2.,
                                  bs[-1]+(bs[1]-bs[0])/2.],
                          xlabel=r'$l\,\mathrm{(deg)}$',
                          ylabel=r'$b\,\mathrm{(deg)}$',
                          zlabel=r'$A_H\,(\mathrm{mag})$',
                          zorder=0)
    bovy_plot.bovy_text(r'$D = 7\,\mathrm{kpc}$',top_left=True,
                        color='w',size=16.)
    # Overplot fields
    glons= [34.,64.,27.]
    glats= [0.,0.,0.]
    colors= ['w','w','y']
    xs= numpy.linspace(-1.5,1.5,201)
    ys= numpy.sqrt(1.5**2.-xs**2.)
    for glon,glat,c in zip(glons,glats,colors):
        bovy_plot.bovy_plot(xs+glon,ys+glat,'-',overplot=True,zorder=1,lw=2.,
                            color=c)
        bovy_plot.bovy_plot(xs+glon,-ys+glat,'-',overplot=True,zorder=1,lw=2.,
                            color=c)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 17
0
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
Exemplo n.º 18
0
def testErrs(options,args):
    ndfehs, ndafes= 201,201
    dfehs= numpy.linspace(0.01,0.4,ndfehs)
    dafes= numpy.linspace(0.01,0.3,ndafes)
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        loglike= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        loglike= numpy.zeros((ndfehs,ndafes))
        ii, jj= 0, 0
    while ii < ndfehs:
        while jj < ndafes:
            sys.stdout.write('\r'+"Working on %i / %i" %(ii*ndafes+jj+1,ndafes*ndfehs))
            sys.stdout.flush()
            loglike[ii,jj]= errsLogLike(dfehs[ii],dafes[jj],options)
            jj+= 1
        ii+= 1
        jj= 0
        save_pickles(args[0],loglike,ii,jj)
    save_pickles(args[0],loglike,ii,jj)
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    if options.prior:
        prior= numpy.zeros((ndfehs,ndafes))
        for ii in range(ndfehs):
            prior[ii,:]= -0.5*(dafes-0.1)**2./0.1**2.-0.5*(dfehs[ii]-0.2)**2./0.1**2.
        loglike+= prior
    loglike-= maxentropy.logsumexp(loglike)
    loglike= numpy.exp(loglike)
    loglike/= numpy.sum(loglike)*(dfehs[1]-dfehs[0])*(dafes[1]-dafes[0])
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(loglike.T,origin='lower',
                          cmap='gist_yarg',
                          xlabel=r'\delta_{[\mathrm{Fe/H}]}',
                          ylabel=r'\delta_{[\alpha/\mathrm{Fe}]}',
                          xrange=[dfehs[0],dfehs[-1]],
                          yrange=[dafes[0],dafes[-1]],
                          contours=True,
                          cntrmass=True,
                          onedhists=True,
                          levels= special.erf(0.5*numpy.arange(1,4)))
    if options.prior:
        bovy_plot.bovy_text(r'$\mathrm{with\ Gaussian\ prior:}$'+
                            '\n'+r'$\delta_{[\mathrm{Fe/H}]}= 0.2 \pm 0.1$'
                            +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]}= 0.1 \pm 0.1$',
top_right=True)
    bovy_plot.bovy_end_print(options.plotfile)
Exemplo n.º 19
0
def plot_distanceintegral_final(plotname):
    # Reload full area
    with open('../savs/distInt.sav', 'rb') as savefile:
        area_full = pickle.load(savefile)
    # Reload full area w/o center
    with open('../savs/distIntRmcenter.sav', 'rb') as savefile:
        area_rmcenter = pickle.load(savefile)
    # Calculate PSD of each
    psdx_full, psd_full= \
        signal.periodogram(area_full*dust._GREEN15DISTS**3./numpy.sum(area_full*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                           detrend=lambda x: x,scaling='spectrum')
    psdx_rmcenter, psd_rmcenter= \
        signal.periodogram(area_rmcenter*dust._GREEN15DISTS**3./numpy.sum(area_rmcenter*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                           detrend=lambda x: x,scaling='spectrum')
    bovy_plot.bovy_print(fig_height=5.5)
    matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
    line1 = bovy_plot.bovy_plot(
        psdx_full[1:],
        numpy.sqrt(psd_full[1:]),
        'k-',
        loglog=True,
        xlabel=r'$\mathrm{distance\ resolution}\ k_\mu\,(\mathrm{mag}^{-1})$',
        ylabel=r'$\mathrm{effective\ volume\ error}\ \sqrt{P_k}$',
        xrange=[0.04, 20.],
        yrange=[10**-11., 5.])
    line2 = bovy_plot.bovy_plot(psdx_rmcenter[1:],
                                numpy.sqrt(psd_rmcenter[1:]),
                                'r-',
                                overplot=True)
    bovy_plot.bovy_plot([1., 10.], [6. * 10.**-4., 6. * 10.**-7.],
                        'k--',
                        overplot=True)
    bovy_plot.bovy_plot([1., 10.], [2. * 10.**-5., 2. * 10.**-10.],
                        'r--',
                        overplot=True)
    pyplot.legend(
        (line1[0], line2[0]),
        (r'$\mathrm{full\ sky}$',
         r'$\mathrm{excluding}\ |180^\circ-l| > 155^\circ, |b| < 25^\circ$'),
        loc='upper right',  #bbox_to_anchor=(.02,.02),
        numpoints=8,
        prop={'size': 14},
        frameon=False)
    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)
    return None
Exemplo n.º 20
0
def plot_data_h_jk(location=None,
                   plotfilename=os.path.join(OUTDIR,'data_h_jk.'+OUTEXT)):
    data= readVclosData()
    if not location is None:
        if location == 0:
            locs= set(data['LOCATION'])
            for l in locs:
                plot_data_h_jk(location=l,
                               plotfilename=os.path.join(OUTDIR,'data_h_jk_%i.' % l +OUTEXT))
            return None
        data= data[(data['LOCATION'] == location)]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['J0MAG']-data['K0MAG'],
                        data['H0MAG'],'k,',
                        xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                        ylabel=r'$H_0\ [\mathrm{mag}]$',
                        xrange=[0.4,1.4],
                        yrange=[5.,14.],
                        onedhists=True,bins=31)
    #Overplot distance if wanted
    if _PLOTDISTANCE:
        iso= isomodel(imfmodel='lognormalChabrier2001',
                      Z=0.019,
                      expsfh=True)
        nds= 101
        ds= numpy.zeros((nds,nds))
        jks= numpy.linspace(0.5,1.2,nds)
        hs= numpy.linspace(14.,5.,nds)
        for ii in range(nds):
            for jj in range(nds):
                ds[ii,jj]= iso.peak(jks[ii],hs[jj])
        #Now contour this
        levels=[1.,3.,10.,30.]
        colors='0.6'#['0.5','0.5','0.5','k','k','k']
        CS=pyplot.contour(jks,hs,ds.T,levels=levels,
                          colors=colors,zorder=10.,linewidths=2.)
        ys= [5.3,6.7,9.22,11.7]
        for ii in range(len(levels)):
            bovy_plot.bovy_text(1.21,ys[ii],r'$%.0f\ \mathrm{kpc}$' % levels[ii],
                                fontsize=14.,color='0.3')
        if False:
            pyplot.clabel(CS, levels,
                          inline=1,
                          fmt='%.0f',
                          fontsize=14,
                          colors=colors,zorder=10.)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 21
0
 def plot(self,
          log=False,
          conditional=False,
          nbins=None,
          overlay_mode=False,
          nmodebins=21,
          overlay_cuts=False):
     """
     NAME:
        plot
     PURPOSE:
        plot the resulting (J-Ks,H) distribution
     INPUT:
        log= (default: False) if True, plot log
        conditional= (default: False) if True, plot conditional distribution
                     of H given J-Ks
        nbins= if set, set the number of bins
        overlay_mode= False, if True, plot the mode and half-maxs
        nmodebins= (21) number of bins to calculate the mode etc. at
        overlay_cuts= False, if True, plot the RC cuts
     OUTPUT:
        plot to output device
     HISTORY:
        2012-02-17 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     out = isomodel.plot(self,
                         log=log,
                         conditional=conditional,
                         nbins=nbins,
                         overlay_mode=overlay_mode)
     if overlay_cuts:
         bovy_plot.bovy_plot(
             [zjkcut(self._Z), zjkcut(self._Z)], [0., -3.],
             'k--',
             lw=2.,
             overplot=True)
         bovy_plot.bovy_plot(
             [zjkcut(self._Z, upper=True),
              zjkcut(self._Z, upper=True)], [0., -3.],
             'k--',
             lw=2.,
             overplot=True)
     zstr = r'$Z = %.3f$' % self._Z
     bovy_plot.bovy_text(zstr, bottom_right=True, size=20.)
     return out
Exemplo n.º 22
0
def plot_dustinfield(plotname, field, threshold=False):
    savefile = _SAVEFILE_MARSHALL
    savefile = savefile.replace('FIELD', '%i' % field)
    # Grid
    ls = numpy.linspace(-1.75, 1.75, _NL) + field
    bs = numpy.linspace(-1.75, 1.75, _NB)
    if not os.path.exists(savefile):
        # Setup dust map
        dmap = mwdust.Marshall06(filter='2MASS H')
        plotthis = numpy.empty((_NL, _NB))
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                plotthis[ii, jj] = dmap(ls[ii], bs[jj], 7.)
        save_pickles(savefile, plotthis)
    else:
        with open(savefile, 'rb') as f:
            plotthis = pickle.load(f)
    # Remove outside the field
    tls = numpy.tile(ls, (_NB, 1)).T
    tbs = numpy.tile(bs, (_NL, 1))
    plotthis[(tls - field)**2. + tbs**2. > 1.5**2.] = numpy.nan
    if threshold:
        plotthis[plotthis > 1.4] = numpy.nan
    # Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(
        plotthis[::-1].T,
        origin='lower',
        cmap=cm.coolwarm,
        interpolation='nearest',
        vmin=0.,
        vmax=2.,
        aspect=1.,
        xrange=[ls[-1] + (ls[1] - ls[0]) / 2., ls[0] - (ls[1] - ls[0]) / 2.],
        yrange=[bs[0] - (bs[1] - bs[0]) / 2., bs[-1] + (bs[1] - bs[0]) / 2.],
        xlabel=r'$l\,\mathrm{(deg)}$',
        ylabel=r'$b\,\mathrm{(deg)}$',
        zlabel=r'$A_H\,(\mathrm{mag})$',
        zorder=0)
    bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field,
                        top_left=True,
                        color='k',
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 23
0
def _plotMC_single(data,options,args,all=False,overplot=False,xrange=None,
                   yrange=None,platels=None,platebs=None,
                   rmin=None,rmax=None,grmin=None,grmax=None,
                   rx=None,ry=None,fehrange=None,colorrange=None):
    if all:
        bovy_plot.scatterplot(data.dered_g-data.dered_r,
                              data.feh,
                              'k,',
                              bins=21,
                              xrange=xrange,
                              yrange=yrange,
                              xlabel=r'$g-r\ [\mathrm{mag}]$',
                              ylabel=r'$[\mathrm{Fe/H}]$',
                              onedhists=True)
        platestr= '\mathrm{all\ plates}'
        bovy_plot.bovy_text(r'$'+platestr+'$'
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            len(data.feh),top_right=True,size=16)
    else:
        bovy_plot.bovy_plot(data.dered_g-data.dered_r,
                              data.feh,
                              'k,',
                              bins=21,
                              xrange=xrange,
                              yrange=yrange,
                              xlabel=r'$g-r\ [\mathrm{mag}]$',
                              ylabel=r'$[\mathrm{Fe/H}]$',
                              onedhists=True)
        platestr= '%i\ \mathrm{plates}' % len(set(list(data.plate)))
        lbstr= '$l = %i^\circ \pm %i^\circ$' % (
            int(numpy.mean(platels)),int(numpy.std(platels)))+'\n'\
            +'$b = %i^\circ\pm%i^\circ$' % (int(numpy.mean(platebs)),
                                            int(numpy.std(platebs)))
        bovy_plot.bovy_text(r'$'+platestr+'$'
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            len(data.feh)
                            +'\n'+
                            lbstr,top_right=True,size=16)
        _add_coordinset(rx=rx,ry=ry,platels=platels,platebs=platebs,
                        feh=numpy.mean(data.feh),
                        rmin=rmin,rmax=rmax,
                        grmin=grmin,grmax=grmin)
def plot_rotcurve_samples(options=None,args=None):
    """Plot sample rotation curves"""
    options= set_options(options)
    params= numpy.random.permutation(load_samples(args[0]))
    rotcurves= []
    rs= numpy.linspace(3.5,16.,1001)
    add= 0
    if options.nooutliermean: add-= 1
    if not options.dwarf: add-= 1
    for ii in range(options.nsamples):
        if options.rotcurve.lower() == 'flat':
            thisrc= params[ii][0]*rs**0.*_REFV0
        elif options.rotcurve.lower() == 'powerlaw':
            thisrc= params[ii][0]*(rs/_REFR0/params[ii][1])**params[ii][6+add]*_REFV0
        elif options.rotcurve.lower() == 'linear':
            thisrc= (params[ii][0]+params[ii][6+add]*(rs/_REFR0/params[ii][1]-1.))*_REFV0
        elif options.rotcurve.lower() == 'quadratic':
            thisrc= (params[ii][0]+params[ii][6+add]*(rs/_REFR0/params[ii][1]-1.)+params[ii][7+add]*(rs/_REFR0/params[ii][1]-1)**2.)*_REFV0
        elif options.rotcurve.lower() == 'cubic':
            thisrc= (params[ii][0]+params[ii][6+add]*(rs/_REFR0/params[ii][1]-1)+params[ii][7+add]*(rs/_REFR0/params[ii][1]-1.)**2.+params[ii][8+add]*(rs/_REFR0/params[ii][1]-1.)**3.)*_REFV0
        rotcurves.append(thisrc)
    bovy_plot.bovy_print(fig_width=8.)
    ii= 0
    bovy_plot.bovy_plot(rs,rotcurves[ii],'-',color='0.65',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$V_c\ [\mathrm{km\ s}^{-1}]$',
                        xrange=[0.,20.],
                        yrange=[150.,300.])
    for ii in range(1,options.nsamples):
        bovy_plot.bovy_plot(rs,rotcurves[ii],'-',color='0.65',overplot=True,alpha=0.1)
    if _PLOTM31:
        #Read file
        m31data= numpy.loadtxt('../data/m31.dat',comments='#')
        rm31= m31data[:,0]
        vcm31= m31data[:,1]
        bovy_plot.bovy_plot(rm31,vcm31,'ks',overplot=True,mfc='none',mew=2.)
        bovy_plot.bovy_text(17.,260.,r'$\mathrm{M31}$',size=14.)
        indx= (rm31 > 15.2)*(rm31 <= 16.8)
        bovy_plot.bovy_plot([17.,rm31[indx]],[260.,vcm31[indx]],'k-',
                            overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Exemplo n.º 25
0
def plot_rotcurves(plotfilename):
    rs= numpy.linspace(3.5,16.,1001)
    #1: flat
    vo,ro= 0.92772766, 1.00939298
    vflat= rs**0.*vo*_REFV0
    #2: power-law
    vo, ro, beta= 0.92881531,  1.0009845, 0.00750639
    vpl= vo*(rs/_REFR0/ro)**beta*_REFV0
    #3: linear
    vo, ro, dvdr= 0.93050113,  1.00377579, 0.01625223
    vlinear= (vo+dvdr*(rs/_REFR0-1.))*_REFV0
    #4: quadratic
    vo, ro, dvdr, d2vdr2= 0.92954738,  1.00440273, 0.02909439,  0.25129582
    vquadratic= (vo+dvdr*(rs/_REFR0-1.)+d2vdr2*(rs/_REFR0-1.)**2.)*_REFV0
    #5: cubic
    vo, ro, dvdr, d2vdr2, d3vdr3=  0.9416574, 1.01691786, -0.10708624, -0.07733835,  0.42241186
    vcubic= (vo+dvdr*(rs/_REFR0-1.)+d2vdr2*(rs/_REFR0-1.)**2.\
                 +d3vdr3*(rs/_REFR0-1.)**3.)*_REFV0
    #Plot all
    bovy_plot.bovy_print(fig_width=8.)
    bovy_plot.bovy_plot(rs,vflat,'k-',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$V_c\ [\mathrm{km\ s}^{-1}]$',
                        xrange=[0.,20.],
                        yrange=[150.,300.])
    bovy_plot.bovy_plot(rs,vpl,'k--',overplot=True)
    bovy_plot.bovy_plot(rs,vlinear,'k-.',overplot=True)
    bovy_plot.bovy_plot(rs,vquadratic,'k:',overplot=True)
    bovy_plot.bovy_plot(rs,vcubic,'k-.',overplot=True,color='red')
    if _PLOTM31:
        #Read file
        m31data= numpy.loadtxt('../data/m31.dat',comments='#')
        rm31= m31data[:,0]
        vcm31= m31data[:,1]
        bovy_plot.bovy_plot(rm31,vcm31,'ks',overplot=True,mfc='none',mew=2.)
        bovy_plot.bovy_text(17.,260.,r'$\mathrm{M31}$',size=14.)
        indx= (rm31 > 15.2)*(rm31 <= 16.8)
        bovy_plot.bovy_plot([17.,rm31[indx]],[260.,vcm31[indx]],'k-',
                            overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 26
0
def plot_dustinfield(plotname,field,threshold=False):
    savefile= _SAVEFILE_MARSHALL
    savefile= savefile.replace('FIELD','%i' % field)
    # Grid
    ls= numpy.linspace(-1.75,1.75,_NL)+field
    bs= numpy.linspace(-1.75,1.75,_NB)
    if not os.path.exists(savefile):
        # Setup dust map
        dmap= mwdust.Marshall06(filter='2MASS H')
        plotthis= numpy.empty((_NL,_NB))
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                plotthis[ii,jj]= dmap(ls[ii],bs[jj],7.)
        save_pickles(savefile,plotthis)
    else:
        with open(savefile,'rb') as f:
            plotthis= pickle.load(f)
    # Remove outside the field
    tls= numpy.tile(ls,(_NB,1)).T
    tbs= numpy.tile(bs,(_NL,1))
    plotthis[(tls-field)**2.+tbs**2. > 1.5**2.]= numpy.nan
    if threshold:
        plotthis[plotthis > 1.4]= numpy.nan
    # Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm,
                          interpolation='nearest',
                          vmin=0.,vmax=2.,aspect=1.,
                          xrange=[ls[-1]+(ls[1]-ls[0])/2.,
                                  ls[0]-(ls[1]-ls[0])/2.],
                          yrange=[bs[0]-(bs[1]-bs[0])/2.,
                                  bs[-1]+(bs[1]-bs[0])/2.],
                          xlabel=r'$l\,\mathrm{(deg)}$',
                          ylabel=r'$b\,\mathrm{(deg)}$',
                          zlabel=r'$A_H\,(\mathrm{mag})$',
                          zorder=0)
    bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field,top_left=True,
                        color='k',size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 27
0
def plot_elliptical_constraint(plotfilename,future=False):
    cs= numpy.linspace(-0.25,0.25,201)
    ss= numpy.linspace(-0.25,0.25,201)
    cons= numpy.zeros((len(cs),len(ss),200))
    for ii in range(len(cs)):
        for jj in range(len(ss)):
            twophio= numpy.sqrt(cs[ii]**2.+ss[jj]**2.)
            phib= math.atan2(ss[jj],cs[ii])/2.
            q= 1-twophio
            for zz in range(8+future*10):
                for ww in range(zz,8+future*10):
                    if future:
                        cons[ii,jj,ww+zz*7]= q**2.*(1./numpy.sqrt(q**2.*numpy.cos((45.-zz*5.)*numpy.pi/180.-phib)**2.+numpy.sin((45.-zz*5.)*numpy.pi/180.-phib)**2.)-1./numpy.sqrt(q**2.*numpy.cos((40.-5.*ww)*numpy.pi/180.-phib)**2.+numpy.sin((40.-ww*5.)*numpy.pi/180.-phib)**2.))**2.
                    else:
                        cons[ii,jj,ww+zz*7]= q**2.*(1./numpy.sqrt(q**2.*numpy.cos((25.-zz*5.)*numpy.pi/180.-phib)**2.+numpy.sin((25.-zz*5.)*numpy.pi/180.-phib)**2.)-1./numpy.sqrt(q**2.*numpy.cos((20.-5.*ww)*numpy.pi/180.-phib)**2.+numpy.sin((20.-ww*5.)*numpy.pi/180.-phib)**2.))**2.
                    #cons[ii,jj,zz]= q**2.*(1./numpy.sqrt(q**2.*numpy.cos((25.*numpy.pi/180.-phib)**2.+numpy.sin(25.*numpy.pi/180.-phib)**2.)-1./numpy.sqrt(q**2.*numpy.cos((20.-5.*zz)*numpy.pi/180.-phib)**2.+numpy.sin((20.-zz*5.)*numpy.pi/180.-phib)**2.))**2.
    plotthis= numpy.all(cons < 1./40.**2.,axis=2)*0.65
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,
                          origin='lower',
                          cmap='gist_yarg',
                          xrange=[-0.25,0.25],
                          yrange=[-0.25,0.25],
                          xlabel=r'$c_\Psi = \varepsilon_\Psi\,\cos 2 \phi_b$',
                          ylabel=r'$s_\Psi = \varepsilon_\Psi\,\sin 2 \phi_b$',
                          vmax=1.)
    bovy_plot.bovy_plot([-0.15,-0.12],[0.15,0.02],'k-',zorder=1,
                        overplot=True)
    bovy_plot.bovy_plot([-0.06363636363636363],[0.],'wx',overplot=True,ms=10.,
                        mew=2.,zorder=2.)
    bovy_plot.bovy_plot([-0.06363636363636363,-0.02],[0.,-0.14],'k-',zorder=1,
                        overplot=True)
    bovy_plot.bovy_text(-0.08,-0.2,r'$\mathrm{model\ with}$'+'\n'+r'$\mathrm{local}\ V_c - \mathrm{global}\ V_c = 14\,\mathrm{km\,s}^{-1}$',
                         size=13.)
    bovy_plot.bovy_text(r'$\mathrm{Elliptical\ disk\ models\ with}$'+'\n'+r'$\forall i \in [0,7] \cap \mathbb{Z}:  \forall j \in [i,7] \cap \mathbb{Z}:$'+'\n'+r'$|\Delta R(\phi=25^\circ - 5^\circ\,i,\phi=20^\circ-5^\circ\,j)| < 200\,\mathrm{pc}$',
                        size=13.,
                        top_left=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def plot_distanceintegral_final(plotname):
    # Reload full area
    with open('../savs/distInt.sav','rb') as savefile:
        area_full= pickle.load(savefile)
    # Reload full area w/o center
    with open('../savs/distIntRmcenter.sav','rb') as savefile:
        area_rmcenter= pickle.load(savefile)
    # Calculate PSD of each
    psdx_full, psd_full= \
        signal.periodogram(area_full*dust._GREEN15DISTS**3./numpy.sum(area_full*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                           detrend=lambda x: x,scaling='spectrum')
    psdx_rmcenter, psd_rmcenter= \
        signal.periodogram(area_rmcenter*dust._GREEN15DISTS**3./numpy.sum(area_rmcenter*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                           detrend=lambda x: x,scaling='spectrum')
    bovy_plot.bovy_print(fig_height=5.5)
    matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
    line1= bovy_plot.bovy_plot(psdx_full[1:],numpy.sqrt(psd_full[1:]),
                               'k-',loglog=True,
                               xlabel=r'$\mathrm{distance\ resolution}\ k_\mu\,(\mathrm{mag}^{-1})$',
                               ylabel=r'$\mathrm{effective\ volume\ error}\ \sqrt{P_k}$',
                               xrange=[0.04,20.],
                               yrange=[10**-11.,5.])
    line2= bovy_plot.bovy_plot(psdx_rmcenter[1:],numpy.sqrt(psd_rmcenter[1:]),
                               'r-',overplot=True)
    bovy_plot.bovy_plot([1.,10.],[6.*10.**-4.,6.*10.**-7.],'k--',overplot=True)
    bovy_plot.bovy_plot([1.,10.],[2.*10.**-5.,2.*10.**-10.],
                        'r--',overplot=True)
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{full\ sky}$',
                   r'$\mathrm{excluding}\ |180^\circ-l| > 155^\circ, |b| < 25^\circ$'),
                  loc='upper right',#bbox_to_anchor=(.02,.02),
                  numpoints=8,
                  prop={'size':14},
                  frameon=False)
    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)
    return None
def set_ranges_and_labels_cross():
    subplot(1,3,1)
    bovy_plot.bovy_text(r'$\sqrt{|\delta b|}$',top_left=True,size=18.)
    xlabel(r'$1/k_{\xi}\,(\mathrm{deg})$')
    ylim(0.001,10.)
    xlim(1.,100.)
    for axis in [gca().xaxis,gca().yaxis]:
        axis.set_major_formatter(FuncFormatter(
                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
    subplot(1,3,2)
    bovy_plot.bovy_text(r'$\sqrt{|\delta D|}$',top_left=True,size=18.)
    xlabel(r'$1/k_{\xi}\,(\mathrm{deg})$')
    ylim(0.001,10.)
    xlim(1.,100.)
    gca().xaxis.set_major_formatter(FuncFormatter(
            lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
    gca().yaxis.set_major_formatter(NullFormatter())
    subplot(1,3,3)
    bovy_plot.bovy_text(r'$\sqrt{|\delta V_{\mathrm{los}}|}$',top_left=True,size=18.)
    xlabel(r'$1/k_{\xi}\,(\mathrm{deg})$')
    ylim(0.001,10.)
    xlim(1.,100.)
    gca().xaxis.set_major_formatter(FuncFormatter(
            lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
    gca().yaxis.set_major_formatter(NullFormatter())
    return None
Exemplo n.º 30
0
def simplePlot(location=4242,plotfile=None,predict=False,nv=11,dmax=10./8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data= readVclosData(**kwargs)
    data= data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range= [-200.,200.]
    hist, xvec, p= bovy_plot.bovy_hist(data['VHELIO'],range=range,bins=31,
                                       histtype='step',color='k',
                                       xlabel=r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs= numpy.linspace(range[0],range[1],nv)
        pred_dist= _calc_pred(pred_vs,location,numpy.mean(data['GLON']),dmax)
        data_int= numpy.sum(hist)*(xvec[1]-xvec[0])
        pred_dist*= data_int/numpy.sum(pred_dist)/(pred_vs[1]-pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,pred_dist,'-',color='0.65',overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location
                        +'\n'
                        +r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
Exemplo n.º 31
0
def plot_data_feh(location=0,
                  plotfilename=os.path.join(OUTDIR,'data_h_jk.'+OUTEXT)):
    data= readVclosData()
    #Good feh
    data= data[(data['FEH']!= -9999.00)]
    if not location is None:
        if location == 0:
            locs= set(data['LOCATION'])
            for l in locs:
                plot_data_feh(location=l,
                              plotfilename=os.path.join(OUTDIR,'data_feh_%i.' % l +OUTEXT))
            return None
        data= data[(data['LOCATION'] == location)]
    meanfeh= numpy.mean(data['FEH'])
    sigfeh= numpy.std(data['FEH'])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data['FEH'],
                        xlabel=r'$[\mathrm{Fe/H}]$',
                        xrange=[meanfeh-1.,meanfeh+1],
                        bins=16)
    bovy_plot.bovy_text(r'$\sigma = %.2f$' % sigfeh,top_right=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 32
0
def plot_spatial_broad(plotname):
    # Load subsamples, plot
    load_funcs = [
        define_rcsample.get_lowlowsample, define_rcsample.get_highalphasample,
        define_rcsample.get_solarsample, define_rcsample.get_highfehsample
    ]
    names = ['lowlow', 'highalpha', 'solar', 'highfeh']
    labels = [
        r'$\mathrm{low\ [Fe/H]}$', r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
        r'$\mathrm{solar}$', r'$\mathrm{high\ [Fe/H]}$'
    ]
    for ii in range(4):
        data = load_funcs[ii]()
        if ii == 1:
            ylabel = r'$Z\,(\mathrm{kpc})$'
        else:
            ylabel = ' '
        bovy_plot.bovy_print(axes_labelsize=24,
                             text_fontsize=24,
                             xtick_labelsize=24,
                             ytick_labelsize=24)
        bovy_plot.bovy_plot(data['RC_GALR_H'],
                            data['RC_GALZ_H'],
                            'k.',
                            ms=2.,
                            xrange=[0., 16.],
                            yrange=[-3., 3.],
                            xlabel=r'$R\,(\mathrm{kpc})$',
                            ylabel=ylabel,
                            onedhists=True,
                            bins=31)
        if ii != 1:
            bovy_plot.bovy_text(labels[ii], top_left=True, size=24)
        else:
            bovy_plot.bovy_text(labels[ii], bottom_left=True, size=24)
        bovy_plot.bovy_end_print(plotname.replace('SAMPLE', names[ii]))
    return None
Exemplo n.º 33
0
def fakeSlopesFig1(options,args):
    #Read data for bins
    raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    binned= pixelAfeFeh(raw,dfeh=_DFEH,dafe=_DAFE)#these dfehs are binsizes
    tightbinned= pixelAfeFeh(raw,dfeh=_DFEH,dafe=_DAFE,
                             fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                             afemax=0.55)
    plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if len(data) < _MINNDATA:
                plotthis[ii,jj]= numpy.nan
                continue
            plotthis[ii,jj]= calcSlope(tightbinned.feh(ii),tightbinned.afe(jj),
                                       options.dfeh,options.dafe,options)
    vmin, vmax= -5.,5.
    zlabel= r'$\frac{\mathrm{d} \sigma_z(z_{1/2})}{\mathrm{d} z}\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    xrange=[-1.6,0.5]
    yrange=[-0.05,0.55]
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          zlabel=zlabel,
                          xrange=xrange,yrange=yrange,
                          vmin=vmin,vmax=vmax,
                          contours=False,
                          colorbar=True,shrink=0.78)
    bovy_plot.bovy_text(r'$\delta_{[\mathrm{Fe/H}]} = %.2f$' % options.dfeh
                        +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]} = %.2f$' % options.dafe,
                        top_right=True,size=18.)
    bovy_plot.bovy_end_print(options.plotfile)
Exemplo n.º 34
0
def triangleMAPs(savefilename, basename):
    with open(savefilename, 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples = numpy.array(pickle.load(savefile))
        bf_g15 = numpy.array(pickle.load(savefile))
        samples_g15 = numpy.array(pickle.load(savefile))
        bf_zero = numpy.array(pickle.load(savefile))
        samples_zero = numpy.array(pickle.load(savefile))
    labels = []
    for jj in range(samples.shape[2]):
        labels.append(r"$\mathrm{param}\ %i$" % jj)
    maps = define_rcsample.MAPs()
    for ii, map in enumerate(maps.map()):
        if ii >= len(bf): break
        tfeh = numpy.nanmedian(map['FE_H'])
        tafe = numpy.nanmedian(map[define_rcsample._AFETAG])
        for tbf, tsamples, ext in zip([bf, bf_g15, bf_zero],
                                      [samples, samples_g15, samples_zero],
                                      ['fid', 'g15', 'zero']):
            try:
                triangle.corner(tsamples[ii, ].T,
                                quantiles=[0.16, 0.5, 0.84],
                                labels=labels,
                                show_titles=True,
                                title_args={"fontsize": 12},
                                bins=21)
            except ValueError:
                pass
            else:
                bovy_plot.bovy_text(r'$[\mathrm{{Fe/H}}] = {feh:.1f},$'\
                                        .format(feh=tfeh)+'\n'
                                    +r'$[\alpha/\mathrm{{Fe}}] = {afe:.2f}$'\
                                        .format(afe=tafe),
                                    top_left=True,size=16.)
                bovy_plot.bovy_end_print(basename + "_%i_%s.png" % (ii, ext))
    return None
Exemplo n.º 35
0
 def plot(self,log=False,conditional=False,nbins=None,
          overlay_mode=False,nmodebins=21,
          overlay_cuts=False):
     """
     NAME:
        plot
     PURPOSE:
        plot the resulting (J-Ks,H) distribution
     INPUT:
        log= (default: False) if True, plot log
        conditional= (default: False) if True, plot conditional distribution
                     of H given J-Ks
        nbins= if set, set the number of bins
        overlay_mode= False, if True, plot the mode and half-maxs
        nmodebins= (21) number of bins to calculate the mode etc. at
        overlay_cuts= False, if True, plot the RC cuts
     OUTPUT:
        plot to output device
     HISTORY:
        2012-02-17 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     out= isomodel.plot(self,log=log,conditional=conditional,nbins=nbins,
                        overlay_mode=overlay_mode)
     if overlay_cuts:
         bovy_plot.bovy_plot([zjkcut(self._Z),
                              zjkcut(self._Z)],
                             [0.,-3.],'k--',lw=2.,overplot=True)
         bovy_plot.bovy_plot([zjkcut(self._Z,upper=True),
                              zjkcut(self._Z,upper=True)],
                             [0.,-3.],'k--',lw=2.,overplot=True)
     zstr= r'$Z = %.3f$' % self._Z
     bovy_plot.bovy_text(zstr,
                         bottom_right=True,size=20.)
     return out
Exemplo n.º 36
0
def plot_data_feh(location=0,
                  plotfilename=os.path.join(OUTDIR, 'data_h_jk.' + OUTEXT)):
    data = readVclosData()
    #Good feh
    data = data[(data['FEH'] != -9999.00)]
    if not location is None:
        if location == 0:
            locs = set(data['LOCATION'])
            for l in locs:
                plot_data_feh(location=l,
                              plotfilename=os.path.join(
                                  OUTDIR, 'data_feh_%i.' % l + OUTEXT))
            return None
        data = data[(data['LOCATION'] == location)]
    meanfeh = numpy.mean(data['FEH'])
    sigfeh = numpy.std(data['FEH'])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data['FEH'],
                        xlabel=r'$[\mathrm{Fe/H}]$',
                        xrange=[meanfeh - 1., meanfeh + 1],
                        bins=16)
    bovy_plot.bovy_text(r'$\sigma = %.2f$' % sigfeh, top_right=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 37
0
def plot_spatial_broad(plotname):
    # Load subsamples, plot
    load_funcs= [define_rcsample.get_lowlowsample,
                 define_rcsample.get_highalphasample,
                 define_rcsample.get_solarsample,
                 define_rcsample.get_highfehsample]
    names= ['lowlow','highalpha','solar','highfeh']
    labels= [r'$\mathrm{low\ [Fe/H]}$',
             r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
             r'$\mathrm{solar}$',
             r'$\mathrm{high\ [Fe/H]}$']            
    for ii in range(4):
        data= load_funcs[ii]()
        if ii == 1:
            ylabel= r'$Z\,(\mathrm{kpc})$'
        else:
            ylabel= ' '
        bovy_plot.bovy_print(axes_labelsize=24,text_fontsize=24,
                             xtick_labelsize=24,ytick_labelsize=24)
        bovy_plot.bovy_plot(data['RC_GALR_H'],
                            data['RC_GALZ_H'],
                            'k.',ms=2.,
                            xrange=[0.,16.],
                            yrange=[-3.,3.],
                            xlabel=r'$R\,(\mathrm{kpc})$',
                            ylabel=ylabel,
                            onedhists=True,
                            bins=31)
        if ii != 1:
            bovy_plot.bovy_text(labels[ii],top_left=True,
                                size=24)
        else:
            bovy_plot.bovy_text(labels[ii],bottom_left=True,
                                size=24)
        bovy_plot.bovy_end_print(plotname.replace('SAMPLE',names[ii]))
    return None
Exemplo n.º 38
0
def plot_mapsurfdens(plotname):
    with open('../mapfits/tribrokenexpflare.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples_brexp= numpy.array(pickle.load(savefile))
    plotmaps= [19,26,32,39,45]
    bovy_plot.bovy_print(fig_width=8.,fig_height=3.)
    maps= define_rcsample.MAPs()
    cmap= cm.coolwarm
    overplot= False
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        # Create all density profiles
        Rs= numpy.linspace(4.,14.,1001)
        samples= samples_brexp[ii,:,::_SKIP]
        nsamples= len(samples[0])
        tRs= numpy.tile(Rs,(nsamples,1)).T
        ldp= numpy.empty((len(Rs),nsamples))
        Rb= numpy.tile(numpy.exp(samples[3]),(len(Rs),1))
        ihRin= numpy.tile(samples[0],(len(Rs),1))
        ihRout= numpy.tile(samples[2],(len(Rs),1))
        # Rb >= R0
        leRb= (tRs <= Rb)*(Rb >= densprofiles._R0)
        ldp[leRb]= ihRin[leRb]*(tRs[leRb]-densprofiles._R0)
        gtRb= (tRs > Rb)*(Rb >= densprofiles._R0)
        ldp[gtRb]= -ihRout[gtRb]*(tRs[gtRb]-densprofiles._R0)\
            +ihRout[gtRb]*(Rb[gtRb]-densprofiles._R0)\
            +ihRin[gtRb]*(Rb[gtRb]-densprofiles._R0)
        # Rb < R0, normalize outer at R0
        leRb= (tRs <= Rb)*(Rb < densprofiles._R0)
        ldp[leRb]= ihRin[leRb]*(tRs[leRb]-densprofiles._R0)\
            -ihRout[leRb]*(Rb[leRb]-densprofiles._R0)\
            -ihRin[leRb]*(Rb[leRb]-densprofiles._R0)
        gtRb= (tRs > Rb)*(Rb < densprofiles._R0)
        ldp[gtRb]= -ihRout[gtRb]*(tRs[gtRb]-densprofiles._R0)
        # Label and relative normalization
        tfeh= round(numpy.median(map['FE_H'])*20.)/20.
        if tfeh == 0.25: tfeh= 0.3
        if tfeh == -0.1: tfeh= -0.1
        print ii, tfeh, len(map)
        anorm= 10**(-10.*(-tfeh-0.5))
        #if (-tfeh-0.4) > 0.3: anorm= 10**(-12.*(-tfeh+0.4)) 
        if (-tfeh-0.5) == -0.2: anorm= 10**(-11.*(-tfeh-0.5))
        anorm= 1./anorm # re-order
        anorm/= 3.
        norm= numpy.exp(numpy.median(ldp,axis=1))[numpy.argmin(numpy.fabs(Rs-densprofiles._R0))]/anorm
        bovy_plot.bovy_plot(Rs,numpy.exp(numpy.median(ldp,axis=1))/norm,
                            '-',
                            color=cmap((tfeh+0.5)*0.95/0.5+0.05),
                            lw=2.,overplot=overplot,
                            ylabel=r'$\Sigma(R)\times\mathrm{constant}$',
                            xrange=[0.,16.],
                            yrange=[0.000001,90.],
                            semilogy=True)
        pyplot.fill_between(Rs,
                            numpy.exp(numpy.sort(ldp,axis=1)[:,int(round(_SIGNIF*nsamples))])/norm,
                            numpy.exp(numpy.sort(ldp,axis=1)[:,int(round((1.-_SIGNIF)*nsamples))])/norm,
                            color=cmap((tfeh+0.5)/0.4),
                            lw=0.)
        overplot= True
        if ii == 19:
            bovy_plot.bovy_text(2.,
                                10.**1.,
                                r'$[\mathrm{Fe/H}]$',size=16.,color='k')
        bovy_plot.bovy_text(2.,(numpy.exp(numpy.median(ldp,axis=1))/norm)[0],
                            r'$%+.1f$' % tfeh,size=16.,
                            color=cmap((tfeh+0.5)*0.95/0.5+0.05))
    bovy_plot.bovy_text(10.,10.**1.,
                        r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                        size=16.)
    pyplot.gca().tick_params(axis='y',which='minor',left='off',right='off')
    bovy_plot.bovy_end_print(plotname)
Exemplo n.º 39
0
def plot_vpecvo(filename, plotfilename):
    if not os.path.exists(filename):
        raise IOError("given filename does not exist")
    savefile = open(filename, 'rb')
    params = pickle.load(savefile)
    savefile.close()
    vos = numpy.array([s[0] for s in params]) * _REFV0
    ros = numpy.array([s[1] for s in params]) * _REFR0
    if _ROTCURVE == 'flat':
        vpec = numpy.array([s[7] for s in params
                            ]) * _PMSGRA * ros - vos  #7 w/ dwarf
        vpecR = numpy.array([s[6] for s in params]) * _VRSUN  #6 w/ dwarf
    elif _ROTCURVE == 'powerlaw' or _ROTCURVE == 'linear':
        vpec = numpy.array([s[8] for s in params
                            ]) * _PMSGRA * ros - vos  #7 w/ dwarf
        vpecR = numpy.array([s[7] for s in params]) * _VRSUN  #6 w/ dwarf
    bovy_plot.bovy_print()
    levels = list(special.erf(0.5 * numpy.arange(1, 4)))
    levels.append(1.01)  #HACK to not plot outliers
    axScatter, axHistx, axHisty = bovy_plot.scatterplot(
        vpecR,  #vos/ros+vpec/ros,
        vpec,
        'k,',
        levels=levels,
        xlabel=r'$V_{R,\odot}\ [\mathrm{km\ s}^{-1}]$',
        ylabel=r'$V_{\phi,\odot}-V_c\ [\mathrm{km\ s}^{-1}]$',
        bins=31,
        xrange=[-15., 0.],
        yrange=[0., 35.],
        contours=True,
        cntrcolors='k',
        onedhists=True,
        cmap='gist_yarg',
        retAxes=True)
    #SBD10 value
    bovy_plot.bovy_plot([-20., 40.], [12.24, 12.24],
                        '--',
                        color='0.5',
                        overplot=True)
    bovy_plot.bovy_text(-4., 12.7, r'$\mathrm{SBD10}$')
    axHisty.plot([0., 100.], [12.24, 12.24], '--', color='0.5')
    bovy_plot.bovy_plot([_VRSUN, _VRSUN], [-100., 100.],
                        '--',
                        color='0.5',
                        overplot=True)
    bovy_plot.bovy_text(_VRSUN - .75, 7., r'$\mathrm{SBD10}$', rotation=90.)
    axHistx.plot([_VRSUN, _VRSUN], [0., 100.], '--', color='0.5')
    #Reid / Brunthaler
    #bovy_plot.bovy_plot([_PMSGRA,_PMSGRA],[-10.,100.],
    #                    '--',color='0.5',overplot=True)
    #axHistx.plot([_PMSGRA,_PMSGRA],[0.,100.],'--',color='0.5')
    #bovy_plot.bovy_text(29.4,5.,r'$\mathrm{RB04}$')

    #Inset, closed orbit at the Sun
    lp = LogarithmicHaloPotential(normalize=1.)
    ep = EllipticalDiskPotential(phib=numpy.pi / 2.,
                                 p=0.,
                                 tform=-100.,
                                 tsteady=-100.,
                                 twophio=14. / 220.)  #0.072725)
    o = Orbit([1., 0., 1. + 14. / 220., 0.])
    oc = Orbit([1., 0., 1., 0.])
    ts = numpy.linspace(0., 4. * numpy.pi, 1001)
    o.integrate(ts, [lp, ep])
    print o.e(analytic=True, pot=lp)
    oc.integrate(ts, lp)
    left, bottom, width, height = 0.45, 0.45, 0.25, 0.25
    axInset = pyplot.axes([left, bottom, width, height])
    pyplot.sca(axInset)
    pyplot.plot(o._orb.orbit[:, 0] * numpy.cos(o._orb.orbit[:, 3]),
                o._orb.orbit[:, 0] * numpy.sin(o._orb.orbit[:, 3]), 'k-')
    pyplot.plot(oc._orb.orbit[:, 0] * numpy.cos(oc._orb.orbit[:, 3]),
                oc._orb.orbit[:, 0] * numpy.sin(oc._orb.orbit[:, 3]),
                '--',
                color='0.6')
    pyplot.xlim(-1.5, 1.5)
    pyplot.ylim(-1.5, 1.5)
    #pyplot.xlabel(r'$x / R_0$')
    #pyplot.ylabel(r'$y / R_0$')
    nullfmt = NullFormatter()  # no labels
    axInset.xaxis.set_major_formatter(nullfmt)
    axInset.yaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotfilename)
def plot_mapflare(plotname):
    with open('../mapfits/tribrokenexpflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp = numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexpinvlinflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp_invlin = numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexplinflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp_lin = numpy.array(pickle.load(savefile))
    plotmaps = [19, 26, 32, 39, 45]
    bovy_plot.bovy_print(fig_width=8., fig_height=9. * 3.99 / 8.98)
    maps = define_rcsample.MAPs()
    cmap = cm.coolwarm
    overplot = False
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        # Create all flaring profiles
        #Rmin= numpy.sort(map['RC_GALR_H'])[int(round(0.005*len(map)))]
        #Rmax= numpy.sort(map['RC_GALR_H'])[numpy.amin([len(map)-1,int(round(0.995*len(map)))])]
        Rs = numpy.linspace(4., 14., 1001)
        samples = samples_brexp[ii, :, ::_SKIP]
        samples_invlin = samples_brexp_invlin[ii, :, ::_SKIP]
        samples_lin = samples_brexp_lin[ii, :, ::_SKIP]
        nsamples = len(samples[0])
        tRs = numpy.tile(Rs, (nsamples, 1)).T
        ldp = numpy.empty((len(Rs), nsamples))
        ldp = samples[1] * numpy.exp(samples[4] * (tRs - densprofiles._R0))
        ldp_invlin= samples_invlin[1]\
            *(1.+samples_invlin[4]*(tRs-densprofiles._R0)*(numpy.exp(1.)-1.))
        ldp_lin= samples_lin[1]\
            /(1.-(tRs-densprofiles._R0)*samples_lin[4]*(numpy.exp(1.)-1.))
        ldp = 1000. / ldp  # make it hz instead of its inverse
        ldp_invlin = 1000. / ldp_invlin
        ldp_lin = 1000. / ldp_lin
        # Label and relative normalization
        tfeh = round(numpy.median(map['FE_H']) * 20.) / 20.
        if tfeh == 0.25: tfeh = 0.3
        if tfeh == -0.0: tfeh = 0.0
        offset = 10.**(-6. * (tfeh + 0.1)) - 0.4
        if tfeh < -0.1: offset /= 1.5
        if tfeh < -0.2: offset /= 1.15
        print ii, tfeh, len(map), offset
        bovy_plot.bovy_plot(
            Rs,
            numpy.median(ldp, axis=1) * offset,
            '-',
            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05),
            lw=2.,
            overplot=overplot,
            ylabel=r'$h_Z\,(\mathrm{pc})\times\mathrm{constant}$',
            xrange=[0., 16.],
            yrange=[10.**2., 10**5.99],
            zorder=10 + ii,
            semilogy=True)
        #skipped because the median for the other profiles are indistinguishable for that with exponential flaring
        """
            pyplot.fill_between(Rs,
                                numpy.median(ldp_lin,axis=1)*offset,
                                numpy.median(ldp_invlin,axis=1)*offset,
                                color='0.65',
                                lw=0.,zorder=ii-1)
        """
        pyplot.fill_between(
            Rs,
            numpy.sort(ldp, axis=1)[:, int(round(_SIGNIF * nsamples))] *
            offset,
            numpy.sort(ldp, axis=1)[:,
                                    int(round(
                                        (1. - _SIGNIF) * nsamples))] * offset,
            color=cmap((tfeh + 0.5) / 0.4),
            lw=0.,
            zorder=ii)
        line, = pyplot.plot(Rs,
                            Rs * 0. + 300. * offset,
                            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05),
                            ls='--',
                            lw=2. * 0.8,
                            zorder=ii + 5)
        line.set_dashes([8, 6])
        overplot = True
        if ii == 19:
            bovy_plot.bovy_text(2.,
                                10.**5.6,
                                r'$[\mathrm{Fe/H}]$',
                                size=16.,
                                color='k')
        bovy_plot.bovy_text(2.,
                            numpy.median(ldp, axis=1)[0] * offset,
                            r'$%+.1f$' % tfeh,
                            size=16.,
                            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05))
    bovy_plot.bovy_text(10.,
                        10.**5.6,
                        r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
Exemplo n.º 41
0
def plotFits(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    params = []
    for filename in args:
        if os.path.exists(filename):
            savefile = open(filename, 'rb')
            if options.kmeansOut:
                thisparams = pickle.load(savefile)
                thisDict = {}
                for kk in range(len(thisparams)):
                    thisDict[str(kk)] = thisparams[kk]
                params.append(thisDict)
            else:
                params.append(pickle.load(savefile))
            savefile.close()
        else:
            print filename + " does not exist ..."
            print "Returning ..."
            return
    if options.plottype == 'Ag':
        ys = nu.array([p['gamma']
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logA'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [0., 1.25]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'As':
        ys = nu.array([p['s'] - 1.
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logA'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [-0.9, 0.4]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$s_{' + options.band + r'}$'
    if options.plottype == 'gs':
        ys = nu.array([p['s'] - 1.
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = nu.array([p['gamma'] for p in params[0].values()]).reshape(
            len(params[0])) / 2.
        xrange = [0., 1.2]
        yrange = [-0.9, 0.4]
        xlabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power-law\ index)}$'
        ylabel = r'$s_{' + options.band + r'}$'
    elif options.plottype == 'AA':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['logA'] / 2.)
                xs.append(params[0][key]['logA'] / 2.)
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [-9.21 / 2., 0.]
        yrange = xrange
        xlabel = r'$\log A_' + options.band[
            0] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A_' + options.band[
            1] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabelnounits = r'$\log A_' + options.band[0] + r'$'
        ylabelnounits = r'$\log A_' + options.band[1] + r'$'
    elif options.plottype == 'AAz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xtmp = qsos[qsoDict[key]].z
            except KeyError:
                continue
            try:
                ytmp = params[1][key]['logA'] / 2.
            except KeyError:
                continue
            ys.append(params[0][key]['logA'] / 2 - ytmp)
            xs.append(xtmp)
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        yrange = [-1., 1.]
        xrange = [0., 5.5]
        ylabel = r'$\log A_r/A_g\ \mathrm{(amplitudes\ at\ 1\ yr)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'gg':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['gamma'])
                xs.append(params[0][key]['gamma'])
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [0., 1.15]
        yrange = xrange
        xlabel = r'$\gamma_' + options.band[
            0] + r'\ \mathrm{(power\ law\ exponent)}$'
        ylabel = r'$\gamma_' + options.band[
            1] + r'\ \mathrm{(power\ law\ exponent)}$'
        xlabelnounits = r'$\gamma_' + options.band[0] + r'$'
        ylabelnounits = r'$\gamma_' + options.band[1] + r'$'
    elif options.plottype == 'Acgc':
        ys = nu.array([p['gammagr']
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logAgr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [0., 1.25]
        xlabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'Acg':
        ys = nu.array([p['gamma']
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logAgr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [0., 1.25]
        xlabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'AcAc':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['logAgr'] / 2.)
                xs.append(params[0][key]['logAgr'] / 2.)
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [-9.21 / 2., 0.]
        yrange = xrange
        xlabel = r'$\log A^c_' + options.band[
            0] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^c_' + options.band[
            1] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabelnounits = r'$\log A^c_' + options.band[0] + r'$'
        ylabelnounits = r'$\log A^c_' + options.band[1] + r'$'
    elif options.plottype == 'gcgc':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['gammagr'])
                xs.append(params[0][key]['gammagr'])
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [0., 1.15]
        yrange = xrange
        xlabel = r'$\gamma^c_' + options.band[
            0] + r'\ \mathrm{(power\ law\ exponent)}$'
        ylabel = r'$\gamma^c_' + options.band[
            1] + r'\ \mathrm{(power\ law\ exponent)}$'
        xlabelnounits = r'$\gamma^c_' + options.band[0] + r'$'
        ylabelnounits = r'$\gamma^c_' + options.band[1] + r'$'
    elif options.plottype == 'AAc':
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
            ys = nu.array([p['logAri'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logA'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
            ys = nu.array([p['logAgr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [-9.21 / 2., 0.]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
    elif options.plottype == 'ggc':
        if len(params) == 2:
            xs, ys = [], []
            for key in params[0].keys():
                try:
                    ys.append(params[1][key]['gammagr'])
                    xs.append(params[0][key]['gamma'])
                except KeyError:
                    continue
            xs = nu.array(xs).reshape(len(xs))
            ys = nu.array(ys).reshape(len(ys))
        else:
            xs = nu.array([p['gamma'] for p in params[0].values()
                           ]).reshape(len(params[0]))
            ys = nu.array([p['gammagr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [0., 1.25]
        yrange = xrange
        xlabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'Ai':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].mags[3])
            except KeyError:
                continue
            if options.type == 'powerlawSFratios':
                ys.append(params[0][key]['logAr'])
            else:
                ys.append(params[0][key]['logA'])
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [15.0, 21.3]
        ylabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'gi':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gamma'])
            xs.append(qsos[qsoDict[key]].mags[3])
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [15.0, 21.3]
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'Az':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].z)
            except KeyError:
                continue
            if options.type == 'powerlawSFratios':
                ys.append(params[0][key]['logAr'])
            else:
                ys.append(params[0][key]['logA'])
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [0., 5.5]
        ylabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'sz':  #for KS11
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].z)
            except KeyError:
                continue
            if len(params) == 2:
                try:
                    ys.append(params[0][key]['s'] / params[1][key]['s'])
                except KeyError:
                    xs.pop()
                    continue
            else:
                ys.append(params[0][key]['s'])
        ys = nu.array(ys) - 1.
        xs = nu.array(xs)
        yrange = [-1.1, 0.4]
        xrange = [0., 5.5]
        ylabel = r'$s_{' + options.band + r'}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'scatterz':  #for KS11
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].z)
            except KeyError:
                continue
            ys.append(params[0][key]['logsigma'])
        ys = nu.array(ys) - 1.
        xs = nu.array(xs)
        yrange = [-10, 0.]
        xrange = [0., 5.5]
        ylabel = r'$\sigma^2_{' + options.band + r'}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'ss':
        ys, xs = [], []
        if options.band2 is None:
            for key in params[0].keys():
                try:
                    ys.append(params[1][key]['s'][0] - 1.)
                except KeyError:
                    continue
                xs.append(params[0][key]['s'][0] - 1.)
        else:
            for key in params[0].keys():
                try:
                    ys.append(params[1][key]['s' + options.band2][0] - 1.)
                except KeyError:
                    continue
                xs.append(params[0][key]['s' + options.band][0] - 1.)
        xs = nu.array(xs)
        ys = nu.array(ys)
        xrange = [-0.9, 0.4]
        yrange = [-0.9, 0.4]
        if options.band2 is None:
            xlabel = r'$s$'
            ylabel = r'$s$'
        else:
            xlabel = r'$s_{' + options.band + r'}$'
            ylabel = r'$s_{' + options.band2 + r'}$'
        ylabelnounits = ylabel
        xlabelnounits = xlabel
    elif options.plottype == 'gz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gamma'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [0., 5.5]
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'Aci':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['logAgr'])
            xs.append(qsos[qsoDict[key]].mags[3])
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [15.0, 21.3]
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'gci':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gammagr'])
            xs.append(qsos[qsoDict[key]].mags[3])
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [15.0, 21.3]
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'loglike2':
        ys = []
        xs = []
        for key in params[0].keys():
            if not params[1].has_key(key): continue
            ys.append(params[1][key]['loglike'])
            xs.append(params[0][key]['loglike'])
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 200.]
        xrange = [0., 200.]
        ylabel = r'$\log L_{\mathrm{DRW}}\ \mathrm{in}\ ' + options.band[
            0] + r'$'
        xlabel = r'$\log L_{\mathrm{PL}}\ \mathrm{in}\ ' + options.band[
            0] + r'$'
    elif options.plottype == 'loglike3z':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            if not params[1].has_key(key): continue
            ys.append(params[1][key]['loglike'] - params[0][key]['loglike'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [-15., 15.]
        xrange = [0., 5.5]
        ylabel = r'$\log L_{\mathrm{DRW}}\ \mathrm{in}\ ' + options.band[
            0] + r' - \log L_{\mathrm{PL}}\ \mathrm{in}\ ' + options.band[
                0] + r'$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'Acz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['logAgr'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [0., 5.5]
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'gcz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gammagr'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [0., 5.5]
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'AsAc':  #files: g, Ac, KS11
        xs = []
        ys = []
        if not options.imax is None:
            qsos = open_qsos()
            qsos = qsos[(qsos.mags[:, 3] < options.imax)]
            qsoDict = {}
            ii = 0
            for qso in qsos:
                qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
                ii += 1
        for key in params[0].keys():
            if not key in qsoDict.keys(): continue
            try:
                if options.type == 'powerlawSFratios':
                    Ac = params[1][key]['logAri'] / 2. + 0.14
                    A = params[0][key]['logA'] / 2.
                else:
                    Ac = params[1][key]['logAgr'] / 2.
                    A = params[0][key]['logA'] / 2.
                s = params[2][key]['s']
                ys.append(Ac)
                xs.append(A + nu.log(1. - s))
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(ys))
        xrange = [-9.21 / 2., 0.]
        yrange = [-9.21 / 2., 0.]
        xlabel = r'$\log [ (1-s ) A_{' + options.band + r'}]\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
    elif options.plottype == 'st':  #DRW
        ys = nu.array([p['logl']
                       for p in params[0].values()]).reshape(len(params[0]))
        ys /= nu.log(10.)
        ys += nu.log10(365.)
        xs = nu.array([p['loga2']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs /= nu.log(10.)
        xs += nu.log10(2.) - ys
        #print nu.amin(ys), nu.amax(ys)
        xrange = [-6., 0.]
        yrange = [-.5, 3.5]
        xlabel = r'$\log_{10} \sigma^2_{' + options.band + r'}\ \mathrm{(short-timescale\ variance)}$'
        ylabel = r'$\log_{10} \tau_{' + options.band + r'}\ \mathrm{(damping\ timescale\ in\ days)}$'
    elif options.plottype == 'a2l':  #DRW
        ys = nu.array([p['logl']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = nu.array([p['loga2']
                       for p in params[0].values()]).reshape(len(params[0]))
        xrange = [-2.5, 0.]
        yrange = [-10., 4.]
        xlabel = r'$\log a^2_{' + options.band + r'}\ \mathrm{(variance)}$'
        ylabel = r'$\log \tau_{' + options.band + r'}\ \mathrm{(damping\ timescale\ in\ yr)}$'
    elif options.plottype == 'Al':  #DRW
        ys = nu.array([p['logl']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = nu.array([p['loga2']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = (nu.log(2.) + xs + nu.log(1. - nu.exp(-1. / nu.exp(ys)))) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [-10., 4.]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log \tau_{' + options.band + r'}\ \mathrm{(damping\ timescale\ in\ yr)}$'
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(xs,
                          ys,
                          'k,',
                          onedhists=True,
                          yrange=yrange,
                          xrange=xrange,
                          bins=30,
                          xlabel=xlabel,
                          ylabel=ylabel)
    if options.plottype == 'AA' or options.plottype == 'gg' \
           or options.plottype == 'loglike2' \
           or options.plottype == 'AsAc' \
           or options.plottype == 'ss' \
           or options.plottype == 'AcAc':
        bovy_plot.bovy_plot(nu.array(xrange),
                            nu.array(xrange),
                            '0.5',
                            overplot=True)
    #also fit if desired
    if options.linearfit:
        indx= (xs > xrange[0])*(xs < xrange[1])\
            *(ys > yrange[0])*(ys < yrange[1])
        b = _fit_linear(xs[indx],
                        ys[indx],
                        removeoutliers=options.removeoutliers)
        bovy_plot.bovy_plot(nu.array(xrange),
                            nu.array(xrange) + b,
                            '0.25',
                            overplot=True)
        bovy_plot.bovy_text(ylabelnounits + r'$ = $' + xlabelnounits +
                            r'$ %4.2f$' % b,
                            bottom_right=True,
                            color='0.25')
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Exemplo n.º 42
0
def plot_rotcurve_samples(options=None, args=None):
    """Plot sample rotation curves"""
    options = set_options(options)
    params = numpy.random.permutation(load_samples(args[0]))
    rotcurves = []
    rs = numpy.linspace(3.5, 16., 1001)
    add = 0
    if options.nooutliermean: add -= 1
    if not options.dwarf: add -= 1
    for ii in range(options.nsamples):
        if options.rotcurve.lower() == 'flat':
            thisrc = params[ii][0] * rs**0. * _REFV0
        elif options.rotcurve.lower() == 'powerlaw':
            thisrc = params[ii][0] * (
                rs / _REFR0 / params[ii][1])**params[ii][6 + add] * _REFV0
        elif options.rotcurve.lower() == 'linear':
            thisrc = (params[ii][0] + params[ii][6 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.)) * _REFV0
        elif options.rotcurve.lower() == 'quadratic':
            thisrc = (params[ii][0] + params[ii][6 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.) +
                      params[ii][7 + add] *
                      (rs / _REFR0 / params[ii][1] - 1)**2.) * _REFV0
        elif options.rotcurve.lower() == 'cubic':
            thisrc = (params[ii][0] + params[ii][6 + add] *
                      (rs / _REFR0 / params[ii][1] - 1) + params[ii][7 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.)**2. +
                      params[ii][8 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.)**3.) * _REFV0
        rotcurves.append(thisrc)
    bovy_plot.bovy_print(fig_width=8.)
    ii = 0
    bovy_plot.bovy_plot(rs,
                        rotcurves[ii],
                        '-',
                        color='0.65',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$V_c\ [\mathrm{km\ s}^{-1}]$',
                        xrange=[0., 20.],
                        yrange=[150., 300.])
    for ii in range(1, options.nsamples):
        bovy_plot.bovy_plot(rs,
                            rotcurves[ii],
                            '-',
                            color='0.65',
                            overplot=True,
                            alpha=0.1)
    if _PLOTM31:
        #Read file
        m31data = numpy.loadtxt('../data/m31.dat', comments='#')
        rm31 = m31data[:, 0]
        vcm31 = m31data[:, 1]
        bovy_plot.bovy_plot(rm31,
                            vcm31,
                            'ks',
                            overplot=True,
                            mfc='none',
                            mew=2.)
        bovy_plot.bovy_text(17., 260., r'$\mathrm{M31}$', size=14.)
        indx = (rm31 > 15.2) * (rm31 <= 16.8)
        bovy_plot.bovy_plot([17., rm31[indx]], [260., vcm31[indx]],
                            'k-',
                            overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Exemplo n.º 43
0
def plot_distanceprior(parser):
    (options, args) = parser.parse_args()
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata)
    l = data['GLON'] * _DEGTORAD
    b = data['GLAT'] * _DEGTORAD
    sinl = numpy.sin(l)
    cosl = numpy.cos(l)
    sinb = numpy.sin(b)
    cosb = numpy.cos(b)
    jk = data['J0MAG'] - data['K0MAG']
    jk[(jk < 0.5)] = 0.5  #BOVY: FIX THIS HACK BY EMAILING GAIL
    h = data['H0MAG']
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
    #Set up polar grid
    res = 51
    xgrid = numpy.linspace(0., 2. * math.pi * (1. - 1. / res / 2.), 2 * res)
    ygrid = numpy.linspace(0.5, 2.8, res)
    plotxgrid = numpy.linspace(xgrid[0] - (xgrid[1] - xgrid[0]) / 2.,
                               xgrid[-1] + (xgrid[1] - xgrid[0]) / 2.,
                               len(xgrid) + 1)
    plotygrid = numpy.linspace(ygrid[0] - (ygrid[1] - ygrid[0]) / 2.,
                               ygrid[-1] + (ygrid[1] - ygrid[0]) / 2.,
                               len(ygrid) + 1)
    plotthis = numpy.zeros((2 * res, res, len(data))) - numpy.finfo(
        numpy.dtype(numpy.float64)).max
    #_BINTEGRATENBINS= 11 #For quick testing
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = h[ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          jk[ii], mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          jk[ii], mh)
        else:
            logpiso[ii, :] = iso(numpy.zeros(_BINTEGRATENBINS) + jk[ii], mh)
    for jj in range(_BINTEGRATENBINS):
        d = ds[jj] / _REFR0
        R = numpy.sqrt(1. + d**2. - 2. * d * cosl)
        indx = (R == 0.)
        R[indx] += 0.0001
        theta = numpy.arcsin(d / R * sinl)
        indx = (1. / cosl < d) * (cosl > 0.)
        theta[indx] = numpy.pi - theta[indx]
        indx = (theta < 0.)
        theta[indx] += 2. * math.pi
        thisout = _logpd([0., 1.], d, None, None, None, None, None, options, R,
                         theta, 1., 0., logpiso[:, jj])
        #Find bin to which these contribute
        thetabin = numpy.floor((theta - xgrid[0]) / (xgrid[1] - xgrid[0]) +
                               0.5)
        Rbin = numpy.floor((R - plotygrid[0]) / (plotygrid[1] - plotygrid[0]))
        indx = (thetabin < 0)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (thetabin >= 2 * res)
        thetabin[indx] = 0.  #Has to be
        #Rbin[indx]= 0
        #thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (Rbin < 0)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (Rbin >= res)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        thetabin = thetabin.astype('int')
        Rbin = Rbin.astype('int')
        for ii in range(len(data)):
            plotthis[thetabin, Rbin, ii] = thisout[ii]
    #Normalize
    for ii in range(2 * res):
        for jj in range(res):
            plotthis[ii, jj, 0] = logsumexp(plotthis[ii, jj, :])
    plotthis = plotthis[:, :, 0]
    plotthis -= numpy.amax(plotthis)
    plotthis = numpy.exp(plotthis)
    plotthis[(plotthis == 0.)] = numpy.nan
    #Get los
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
    bovy_plot.bovy_print()
    ax = pyplot.subplot(111, projection='galpolar')  #galpolar is in bovy_plot
    vmin, vmax = 0., 1.
    out = ax.pcolor(plotxgrid,
                    plotygrid,
                    plotthis.T,
                    cmap='gist_yarg',
                    vmin=vmin,
                    vmax=vmax,
                    zorder=2)
    #Overlay los
    for ii in range(nlocs):
        lds = numpy.linspace(0., 2.95, 501)
        lt = numpy.zeros(len(lds))
        lr = numpy.zeros(len(lds))
        lr = numpy.sqrt(1. + lds**2. -
                        2. * lds * numpy.cos(l_plate[ii] * _DEGTORAD))
        lt = numpy.arcsin(lds / lr * numpy.sin(l_plate[ii] * _DEGTORAD))
        indx = (1. / numpy.cos(l_plate[ii] * _DEGTORAD) < lds) * (numpy.cos(
            l_plate[ii] * _DEGTORAD) > 0.)
        lt[indx] = numpy.pi - lt[indx]
        ax.plot(lt, lr, ls='--', color='w', zorder=3)
    from matplotlib.patches import Arrow, FancyArrowPatch
    arr = FancyArrowPatch(posA=(-math.pi / 2., 1.8),
                          posB=(-math.pi / 4., 1.8),
                          arrowstyle='->',
                          connectionstyle='arc3,rad=%4.2f' % (-math.pi / 16.),
                          shrinkA=2.0,
                          shrinkB=2.0,
                          mutation_scale=20.0,
                          mutation_aspect=None,
                          fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(-math.pi / 2.,
                        1.97,
                        r'$\mathrm{Galactic\ rotation}$',
                        rotation=-22.5)
    radii = numpy.array([0.5, 1., 1.5, 2., 2.5])
    labels = []
    for r in radii:
        ax.plot(numpy.linspace(
            0.,
            2. * math.pi,
            501,
        ),
                numpy.zeros(501) + r,
                ls='-',
                color='0.65',
                zorder=1,
                lw=0.5)
        labels.append(r'$%i$' % int(r * 8.))
    pyplot.rgrids(radii, labels=labels, angle=-32.5)
    bovy_plot.bovy_text(5.785, 2.82, r'$\mathrm{kpc}$')
    azs = numpy.array([0., 45., 90., 135., 180., 225., 270., 315.]) * _DEGTORAD
    for az in azs:
        ax.plot(numpy.zeros(501) + az,
                numpy.linspace(0., 2.8, 501),
                '-',
                color='0.6',
                lw=0.5,
                zorder=1)
    #Sun
    bovy_plot.bovy_text(0.065, .9075, r'$\odot$')
    pyplot.ylim(0., 2.8)
    bovy_plot.bovy_end_print(options.plotfile)
Exemplo n.º 44
0
def plotMass(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        mass= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        mass= []
        ii, jj= 0, 0
    #parameters
    if os.path.exists(args[1]):#Load initial
        savefile= open(args[1],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    else:
        print "Error: must provide parameters of best fits"
        print "Returning ..."
        return None
    #Mass uncertainties are in savefile3
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        masssamples= pickle.load(savefile)
        savefile.close()
        masserrors= True
    else:
        masssamples= None
        masserrors= False
    if len(args) > 3 and os.path.exists(args[3]): #Load savefile
        savefile= open(args[3],'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
        denserrors= True
    else:
        denssamples= None
        denserrors= False
    if len(args) > 4 and os.path.exists(args[4]):#Load savefile
        savefile= open(args[4],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
        velfitsLoaded= True
    else:
        velfitsLoaded= False
    if len(args) > 5 and os.path.exists(args[5]):
        savefile= open(args[5],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
        velerrors= True
    else:
        velsamples= None            
        velerrors= False
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    if denserrors: errors= []
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(fits):
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            thismass= mass[afeindx+fehindx*binned.npixafe()]
            if masserrors:
                thismasssamples= masssamples[afeindx+fehindx*binned.npixafe()]
            else:
                thismasssamples= None
            thisfit= fits[afeindx+fehindx*binned.npixafe()]
            if denserrors:
                thisdenssamples= denssamples[afeindx+fehindx*binned.npixafe()]
            else:
                thisdenssamples= None
            if velfitsLoaded:
                thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            if velerrors:
                thisvelsamples= velsamples[afeindx+fehindx*binned.npixafe()]
            if thisfit is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if options.type == 'mass':
                if not options.distzmin is None or not options.distzmax is None:
                    if options.distzmin is None and not options.distzmax is None:
                        thismass*= (1.-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.))
                    elif not options.distzmin is None and options.distzmax is None:
                        thismass*= numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)
                    else:
                        thismass*= (numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.))
                if options.logmass:
                    plotthis[ii,jj]= numpy.log10(thismass/10**6.)
                else:
                    plotthis[ii,jj]= thismass/10**6.
            elif options.type == 'nstars':
                if options.logmass:
                    plotthis[ii,jj]= numpy.log10(len(data))
                else:
                    plotthis[ii,jj]= len(data)
            elif options.model.lower() == 'hwr':
                if options.type == 'hz':
                    plotthis[ii,jj]= numpy.exp(thisfit[0])*1000.
                elif options.type == 'hr':
                    plotthis[ii,jj]= numpy.exp(thisfit[1])
                elif options.type.lower() == 'afe' \
                        or options.type.lower() == 'feh' \
                        or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    plotthis.append([tightbinned.feh(ii),
                                         tightbinned.afe(jj),
                                     numpy.exp(thisfit[0])*1000.,
                                     numpy.exp(thisfit[1]),
                                     len(data),
                                     thismass/10.**6.,
                                     thismasssamples])
                    if denserrors:
                        theseerrors= []
                        thesesamples= denssamples[afeindx+fehindx*binned.npixafe()]
                        if options.model.lower() == 'hwr':
                            for kk in [0,1]:
                                xs= numpy.array([s[kk] for s in thesesamples])
                                theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                        errors.append(theseerrors)
                    if velfitsLoaded:
                        if options.velmodel.lower() == 'hwr':
                            plotthis[-1].extend([numpy.exp(thisvelfit[1]),
                                                 numpy.exp(thisvelfit[4]),
                                                 thisvelfit[2],
                                                 thisvelfit[3]])
                            if velerrors:
                                theseerrors= []
                                thesesamples= velsamples[afeindx+fehindx*binned.npixafe()]
                                for kk in [1,4]:
                                    xs= numpy.array([s[kk] for s in thesesamples])
                                    theseerrors.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                                xs= numpy.array([s[4] for s in thesesamples])
                                theseerrors.append(0.5*(numpy.exp(-numpy.mean(xs))-numpy.exp(numpy.mean(-xs)-numpy.std(-xs))-numpy.exp(numpy.mean(-xs))+numpy.exp(numpy.mean(-xs)+numpy.std(-xs))))
                                errors[-1].extend(theseerrors)
    #Set up plot
    #print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    if options.type == 'mass':
        if options.logmass:
            vmin, vmax= numpy.log10(0.01), numpy.log10(2.)
            zlabel=r'$\log_{10} \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
        else:
            vmin, vmax= 0.,1.
            zlabel=r'$\Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
            if not options.distzmin is None or not options.distzmax is None:
                vmin, vmax= None, None
        title=r'$\mathrm{mass\ weighted}$'
    elif options.type == 'nstars':
        if options.logmass:
            vmin, vmax= 2., 3.
            zlabel=r'$\log_{10} \mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$'
        else:
            vmin, vmax= 100.,1000.
            zlabel=r'$\mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$'
        title= r'$\mathrm{raw\ sample\ counts}$'
    elif options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.5,0.
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.6]
        yrange=[-0.1,0.6]
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        #Gather hR and hz
        sz_err, sz, hz_err, hr_err, mass_err, mass, hz, hr,afe, feh, ndata= [], [], [], [], [], [], [], [], [], [], []
        for ii in range(len(plotthis)):
            if denserrors:
                hz_err.append(errors[ii][0]*1000.)
                hr_err.append(errors[ii][1])
            mass.append(plotthis[ii][5])
            hz.append(plotthis[ii][2])
            hr.append(plotthis[ii][3])
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][4])
            if velfitsLoaded:
                sz.append(plotthis[ii][7])
            if velerrors:
                sz_err.append(errors[ii][2])
            if masserrors:
                mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.))
                
                """
                if options.logmass:
                    mass_err.append(numpy.std(numpy.log10(numpy.array(plotthis[ii][6])/10.**6.)))
                else:
                    mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.))
                """
        if denserrors:
            hz_err= numpy.array(hz_err)
            hr_err= numpy.array(hr_err)
        if velfitsLoaded:
            sz= numpy.array(sz)
        if velerrors:
            sz_err= numpy.array(sz_err)
        mass= numpy.array(mass)
        if masserrors:
            mass_err= numpy.array(mass_err)
        hz= numpy.array(hz)
        hr= numpy.array(hr)
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata))
        #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        xrange= [150,1200]
        if options.cumul:
            #Print total surface mass and uncertainty
            totmass= numpy.sum(mass)
            if options.ploterrors:
                toterr= numpy.sqrt(numpy.sum(mass_err**2.))
            else:
                toterr= 0.
            print "Total surface-mass density: %4.1f +/- %4.2f" %(totmass,toterr)
            ids= numpy.argsort(hz)
            plotc= plotc[ids]
            ndata= ndata[ids]
            mass= mass[ids]
            mass= numpy.cumsum(mass)
            hz.sort()
            ylabel=r'$\mathrm{cumulative}\ \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
            if options.logmass:
                yrange= [0.01,30.]
            else:
                yrange= [-0.1,30.]
        else:
            if options.logmass:
                yrange= [0.005*0.13/.07,10.*.13/.07]
            else:
                yrange= [-0.1,10.*.13/.07]
            ylabel=r'$\Sigma_{R_0}(h_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
        if not options.vstructure and not options.hzhr:
            if options.hr:
                ploth= hr
                plotherr= hr_err
                xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$'
                xrange= [1.2,4.]
                bins= 11
            elif options.sz:
                ploth= sz**2.
                plotherr= 2.*sz_err*sz
                xlabel=r'$\sigma_z^2\ \mathrm{[km}^2\ \mathrm{s}^{-2}]$'
                xrange= [12.**2.,50.**2.]
                ylabel=r'$\Sigma_{R_0}(\sigma^2_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
                bins= 9
            else:
                ploth= hz
                plotherr= hz_err
                xlabel=r'$\mathrm{vertical\ scale\ height}\ h_z\ \mathrm{[pc]}$'
                xrange= [165,1200]
                bins= 12
            bovy_plot.bovy_plot(ploth,mass*.13/0.07,
                                s=ndata,c=plotc,
                                cmap='jet',
                                xlabel=xlabel,
                                ylabel=ylabel,
                                clabel=zlabel,
                                xrange=xrange,yrange=yrange,
                                vmin=vmin,vmax=vmax,
                                scatter=True,edgecolors='none',
                                colorbar=True,zorder=2,
                                semilogy=options.logmass)
            if not options.cumul and masserrors and options.ploterrors:
                colormap = cm.jet
                for ii in range(len(hz)):
                    pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,
                                    yerr=mass_err[ii]*.13/0.07,
                                    color=colormap(_squeeze(plotc[ii],
                                                            numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                            numpy.amin([vmax,
                                                                        numpy.amax(plotc)]))),
                                    elinewidth=1.,capsize=3,zorder=0)
            if not options.cumul and denserrors and options.ploterrors:
                colormap = cm.jet
                for ii in range(len(hz)):
                    pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,xerr=plotherr[ii],
                                    color=colormap(_squeeze(plotc[ii],
                                                            numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                            numpy.amin([vmax,
                                                                        numpy.amax(plotc)]))),
                                    elinewidth=1.,capsize=3,zorder=0)
            #Add binsize label
            bovy_plot.bovy_text(r'$\mathrm{points\ use}\ \Delta [\mathrm{Fe/H}] = 0.1,$'+'\n'+r'$\Delta [\alpha/\mathrm{Fe}] = 0.05\ \mathrm{bins}$',
                                bottom_left=True)
            #Overplot histogram
            #ax2 = pyplot.twinx()
            pyplot.hist(ploth,range=xrange,weights=mass*0.13/0.07,color='k',histtype='step',
                        bins=bins,lw=3.,zorder=10)
            #Also XD?
            if options.xd:
                #Set up data
                ydata= numpy.zeros((len(hz),1))
                if options.sz:
                    ydata[:,0]= numpy.log(sz)
                else:
                    ydata[:,0]= numpy.log(hz)
                ycovar= numpy.zeros((len(hz),1))
                if options.sz:
                    ycovar[:,0]= sz_err**2./sz**2.
                else:
                    ycovar[:,0]= hz_err**2./hz**2.
                #Set up initial conditions
                xamp= numpy.ones(options.k)/float(options.k)
                xmean= numpy.zeros((options.k,1))
                for kk in range(options.k):
                    xmean[kk,:]= numpy.mean(ydata,axis=0)\
                        +numpy.random.normal()*numpy.std(ydata,axis=0)
                xcovar= numpy.zeros((options.k,1,1))
                for kk in range(options.k):
                    xcovar[kk,:,:]= numpy.cov(ydata.T)
                #Run XD
                print extreme_deconvolution(ydata,ycovar,xamp,xmean,xcovar,
                                      weight=mass)*len(hz)
                print xamp, xmean, xcovar
                #Plot
                xs= numpy.linspace(xrange[0],xrange[1],1001)
                xdys= numpy.zeros(len(xs))
                for kk in range(options.k):
                    xdys+= xamp[kk]/numpy.sqrt(2.*numpy.pi*xcovar[kk,0,0])\
                        *numpy.exp(-0.5*(numpy.log(xs)-xmean[kk,0])**2./xcovar[kk,0,0])
                xdys/= xs
                bovy_plot.bovy_plot(xs,xdys,'-',color='0.5',overplot=True)
#            ax2.set_yscale('log')
#            ax2.set_yticklabels('')        
#            if options.hr:
#                pyplot.ylim(10**-2.,10.**0.)
#            if options.sz:
#                pyplot.ylim(10**-5.,10.**-2.5)
#            else:
#                pyplot.ylim(10**-5.5,10.**-1.5)
#            pyplot.xlim(xrange[0],xrange[1])
            ax= pyplot.gca()
            if options.sz:
                def my_formatter(x, pos):
                    """s^2"""
                    xs= int(round(math.sqrt(x)))
                    return r'$%i^2$' % xs
                major_formatter = FuncFormatter(my_formatter)
                ax.xaxis.set_major_formatter(major_formatter)
            xstep= ax.xaxis.get_majorticklocs()
            xstep= xstep[1]-xstep[0]
            ax.xaxis.set_minor_locator(MultipleLocator(xstep/5.))
        elif options.hzhr:
            #Make density plot in hR and hz
            bovy_plot.scatterplot(hr,hz,'k,',
                                  levels=[1.01],#HACK such that outliers aren't plotted
                                  cmap='gist_yarg',
                                  bins=11,
                                  xrange=[1.,7.],
                                  yrange=[150.,1200.],
                                  ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$',
                                  xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$',
                                  onedhists=False,
                                  weights=mass)
        else:
            #Make an illustrative plot of the vertical structure
            nzs= 1001
            zs= numpy.linspace(200.,3000.,nzs)
            total= numpy.zeros(nzs)
            for ii in range(len(hz)):
                total+= mass[ii]/2./hz[ii]*numpy.exp(-zs/hz[ii])
            bovy_plot.bovy_plot(zs,total,color='k',ls='-',lw=3.,
                                semilogy=True,
                                xrange=[0.,3200.],
                                yrange=[0.000001,0.02],
                                xlabel=r'$\mathrm{vertical\ height}\ Z$',
                                ylabel=r'$\rho_*(R=R_0,Z)\ [\mathrm{M}_\odot\ \mathrm{pc}^{-3}]$',
                                zorder=10)
            if options.vbinned:
                #Bin
                mhist, edges= numpy.histogram(hz,range=xrange,
                                              weights=mass,bins=10)
                stotal= numpy.zeros(nzs)
                for ii in range(len(mhist)):
                    hz= (edges[ii+1]+edges[ii])/2.
                    if options.vcumul:
                        if ii == 0.:
                            pstotal= numpy.zeros(nzs)+0.0000001
                        else:
                            pstotal= copy.copy(stotal)
                        stotal+= mhist[ii]/2./hz*numpy.exp(-zs/hz)
                        pyplot.fill_between(zs,stotal,pstotal,
                                            color='%.6f' % (0.25+0.5/(len(mhist)-1)*ii))
                    else:
                        bovy_plot.bovy_plot([zs[0],zs[-1]],
                                            1.*numpy.array([mhist[ii]/2./hz*numpy.exp(-zs[0]/hz),
                                                            mhist[ii]/2./hz*numpy.exp(-zs[-1]/hz)]),
                                            color='0.5',ls='-',overplot=True,
                                            zorder=0)
            else:
                colormap = cm.jet
                for ii in range(len(hz)):
                    bovy_plot.bovy_plot([zs[0],zs[-1]],
                                        100.*numpy.array([mass[ii]/2./hz[ii]*numpy.exp(-zs[0]/hz[ii]),
                                                          mass[ii]/2./hz[ii]*numpy.exp(-zs[-1]/hz[ii])]),
                                        ls='-',overplot=True,alpha=0.5,
                                        zorder=0,
                                        color=colormap(_squeeze(plotc[ii],
                                                                numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                                numpy.amin([vmax,
                                                                            numpy.amax(plotc)]))))
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              onedhists=True,
                              contours=False)
        bovy_plot.bovy_text(title,top_right=True,fontsize=16)
        if not options.distzmin is None or not options.distzmax is None:
            if options.distzmin is None:
                distlabel= r'$|Z| < %i\ \mathrm{pc}$' % int(options.distzmax)
            elif options.distzmax is None:
                distlabel= r'$|Z| > %i\ \mathrm{pc}$' % int(options.distzmin)
            else:
                distlabel= r'$%i < |Z| < %i\ \mathrm{pc}$' % (int(options.distzmin),int(options.distzmax))
            bovy_plot.bovy_text(distlabel,bottom_left=True,fontsize=16)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
Exemplo n.º 45
0
def _label_lines(elem, wavemin, wavemax, thisax, lams, spec):
    if elem.lower() == 'fe':
        lines = _FEI_lines
    elif elem.lower() == 'mg':
        lines = _MGI_lines
    elif elem.lower() == 'al':
        lines = _ALI_lines
    elif elem.lower() == 'si':
        lines = _SII_lines
    elif elem.lower() == 'k':
        lines = _KI_lines
    elif elem.lower() == 'cr':
        lines = _CRI_lines
    elif elem.lower() == 'ca':
        lines = _CAI_lines
    elif elem.lower() == 'ti':
        lines = _TII_lines
    elif elem.lower() == 'ni':
        lines = _NII_lines
    elif elem.lower() == 'na':
        lines = _NAI_lines
    elif elem.lower() == 'mn':
        lines = _MNI_lines
    elif elem.lower() == 's':
        lines = _SI_lines
    elif elem.lower() == 'v':
        lines = _VI_lines
    elif elem.lower() == 'cu':
        lines = _CUI_lines
    elif elem.lower() == 'cob':
        lines = _COI_lines
    elif elem.lower() == 'oh':
        lines = _OH_lines
    elif elem.lower() == 'co':
        lines = _CO_lines
    elif elem.lower() == 'cn':
        lines = _CN_lines
    elif elem.lower() == '13co':
        lines = _13CO_lines
    elif elem.lower() == 'hbrpi':
        lines = _HBRPI_lines
    elif elem.lower() == 'hbrla':
        lines = _HBRLA_lines
    elif elem.lower() == 'hbr':
        lines = _HBR_lines
    fontsize = 5.5
    bbox = dict(facecolor='w', edgecolor='none')
    for line in lines:
        if line > wavemin and line < wavemax:
            spindx = numpy.argmin(numpy.fabs(line - lams))
            ylevel = numpy.nanmin(spec[spindx - 2:spindx + 3])
            if numpy.isnan(ylevel): continue
            if elem == 'ca' and line > 16154. and line < 16156.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.6 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB + 2,
                                    0.55 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'ca' and line > 16160. and line < 16162.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.55 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB + 2,
                                    0.5 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'fe' and line > 16156. and line < 16158.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.45 * ylevel, 0.95 * ylevel],
                            'k-',
                            zorder=1)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.4 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 's' and line > 15482. and line < 15483.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.6 * ylevel, 0.9 * ylevel], 'k-')
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.55 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 's' and line > 15470. and line < 15480.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.25 * ylevel, 0.9 * ylevel], 'k-')
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.25 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'cn' and line > 15485. and line < 15488.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.7 * ylevel, 0.9 * ylevel], 'k-')
                bovy_plot.bovy_text(line - _LAMBDASUB + 2.5,
                                    0.65 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'fe' and line > 15494. and line < 15495.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.6 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB + 2,
                                    0.55 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'fe' and line > 15198. and line < 15199.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.3 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.25 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'fe' and line > 15390. and line < 15410.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.4 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.35 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'ti' and line > 15703. and line < 15704.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.6 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.55 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'mn' and line > 15260. and line < 15280.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.35 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.3 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'ni' and line > 15600. and line < 15620.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.35 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.3 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            elif elem == 'ni' and line > 16818. and line < 16822.:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.45 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.4 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top')
            else:
                thisax.plot([line - _LAMBDASUB, line - _LAMBDASUB],
                            [0.7 * ylevel, 0.9 * ylevel],
                            'k-',
                            zorder=0)
                bovy_plot.bovy_text(line - _LAMBDASUB,
                                    0.65 * ylevel,
                                    line_labels[elem.lower()],
                                    size=fontsize,
                                    bbox=bbox,
                                    horizontalalignment='center',
                                    verticalalignment='top',
                                    zorder=1)
    return None
def plot_asymmetricdrift(outdir='../tex'):
    #First plot the fiducial model for vcva/sr2
    Ro = 8.
    hR = 3. / Ro
    hs = 8. / Ro
    vc = 1.
    #Zero-ish
    kinematicsFile = '../data/axi_va-kinematics_0.0.sav'
    kinematicsFile = open(kinematicsFile, 'rb')
    vas = pickle.load(kinematicsFile)  #vas has va/sigmaR^2(R_0)
    xs = pickle.load(kinematicsFile)
    kinematicsFile.close()
    vas = vas[15]  # dispersion = small
    nrs = 101
    rs = numpy.linspace(0.1, 2.2, nrs)
    vaInterp = interpolate.InterpolatedUnivariateSpline(rs, vas)
    #Plot
    rs = numpy.linspace(4., 20., 1001)
    so = 0.2
    #Hot
    sigmaR_hot = 0.2 * numpy.exp(-(rs / Ro - 1.) / hs)
    vas_fid = va(rs / Ro, 0.2, hR=hR, hs=hs)
    #Cold
    dlnnusR2dlnR_correct = dlnnusR2dlnR(hR_fid, hs_fid) - dlnnusR2dlnR(hR, hs)
    vas_cold = vaInterp(rs / Ro)
    sigmaR_cold = 0.1 * numpy.exp(-(rs / Ro - 1.) / hs)
    vas_cold = 0.1**2. / vc * (
        vas_cold + 0.5 * dlnnusR2dlnR_correct * numpy.exp(-2. *
                                                          (rs / Ro - 1.)))
    bovy_plot.bovy_print(fig_height=3.)
    lines = []
    lines.append(
        bovy_plot.bovy_plot(rs,
                            vas_fid / sigmaR_hot**2.,
                            'k-',
                            xlabel=r'$R\ [\mathrm{kpc}]$',
                            ylabel=r'$V_c\,V_a / \sigma_R^2$',
                            xrange=[0., 25.],
                            yrange=[0., 6.5]))
    lines.append(
        bovy_plot.bovy_plot(rs,
                            vas_cold / sigmaR_cold**2.,
                            '--',
                            color='0.4',
                            overplot=True))
    bovy_plot.bovy_text(r'$h_R = 3\, \mathrm{kpc}$' + '\n' +
                        r'$h_\sigma = 8\, \mathrm{kpc}$',
                        top_left=True)
    labels = [
        r'$\sigma_R(R_0) = 0.2\,V_c(R_0)$', r'$\sigma_R(R_0) = 0.1\,V_c(R_0)$'
    ]
    l1 = pyplot.legend(lines, labels, loc=4, frameon=False, numpoints=1)
    bovy_plot.bovy_end_print(os.path.join(outdir, 'vaR.ps'))

    #Now plot differences from fiducial
    vas_fid = va(rs / Ro, 0.14, hR=hR, hs=hs)  #different fiducial
    bovy_plot.bovy_print(fig_height=3.)
    bovy_plot.bovy_plot([rs[0], rs[-1]], [0., 0.],
                        'k-',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$(V_a - V_a^{\mathrm{fid}}) / V_c(R_0)$',
                        xrange=[0., 25.],
                        yrange=[-0.075, 0.075])
    #hR=2 kpc
    bovy_plot.bovy_plot(rs,
                        va(rs / Ro, 0.14, hR=2. / Ro, hs=hs) - vas_fid,
                        overplot=True,
                        ls='-.',
                        color='k')
    bovy_plot.bovy_text(0.5, 0.005, r'$h_R = 2\, \mathrm{kpc}$')
    bovy_plot.bovy_text(r'$\sigma_R(R_0) = 0.14\,V_c(R_0)$', bottom_right=True)
    bovy_plot.bovy_plot(rs,
                        va(rs / Ro, 0.14, hR=4. / Ro, hs=hs) - vas_fid,
                        overplot=True,
                        ls='--',
                        color='k')
    bovy_plot.bovy_text(0.5, -0.02, r'$h_R = 4\, \mathrm{kpc}$')
    #hs=6 kpc
    bovy_plot.bovy_plot(rs,
                        va(rs / Ro, 0.14, hR=hR, hs=6. / Ro) - vas_fid,
                        overplot=True,
                        ls=':',
                        color='k')
    bovy_plot.bovy_text(.5, 0.035, r'$h_\sigma = 6\, \mathrm{kpc}$')
    #hs=6 kpc
    bovy_plot.bovy_plot(rs,
                        va(rs / Ro, 0.14, hR=hR, hs=242. / Ro) - vas_fid,
                        overplot=True,
                        ls='-',
                        color='0.65')
    bovy_plot.bovy_text(17.5, 0.055, r'$R_0/h_\sigma = 0.034$')
    bovy_plot.bovy_end_print(os.path.join(outdir, 'vaR_diffs.ps'))
    #Now plot the actual model used in the bestfit
    bovy_plot.bovy_print(fig_height=3.)
    bovy_plot.bovy_plot(rs,
                        va(rs / Ro, 0.14, hR=hR, hs=242. / Ro),
                        'k-',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$V_a / V_c(R_0)$',
                        xrange=[0., 25.],
                        yrange=[0., 0.08])
    bovy_plot.bovy_plot(rs,
                        va(rs / Ro, 0.14, hR=hR, hs=1.),
                        'k--',
                        overplot=True)
    bovy_plot.bovy_text(r'$h_R = 3\, \mathrm{kpc}$' + '\n' +
                        r'$R_0/h_\sigma = 0.034$',
                        top_right=True)
    bovy_plot.bovy_text(r'$h_R = 3\, \mathrm{kpc}$' + '\n' +
                        r'$R_0/h_\sigma = 1$',
                        top_left=True)
    bovy_plot.bovy_text(7., 0.07125, r'$\sigma_R(R_0) = 0.14\,V_c(R_0)$')
    bovy_plot.bovy_end_print(os.path.join(outdir, 'vaR_used.ps'))
Exemplo n.º 47
0
def windows(*args, **kwargs):
    """
    NAME:
       windows
    PURPOSE:
       plot the spectral windows for a given element
    INPUT:
       Either:
          (a) wavelength, spectrum (\AA,spectrum units)
          (b) spectrum (assumed on standard APOGEE re-sampled wavelength grid)
          (c) location ID, APOGEE ID (default loads aspcapStar, loads extension ext(=1); apStar=True loads apStar spectrum)
          +element string (e.g., 'Al'); Adding 1 and 2 splits the windows into two
    KEYWORDS:
       plot_weights= (False) if True, also plot the weights for the windows (assumes that the spectrum is on the apStarWavegrid)
       markLines= mark the location of 'lines' (see apogee.spec.window.lines)
       apogee.spec.plot.waveregions keywords
    OUTPUT:
       plot to output
       The final axes allow one to put additional labels on the plot, e.g., for adding the APOGEE ID:
       bovy_plot.bovy_text(r'$\mathrm{%s}$' % '2M02420597+0837017',top_left=True)       
       Note that an ID (e.g., the apogee ID) and Teff, logg, metallicity, and alpha-enhancement labels can be added using the keywords label* above
    HISTORY:
       2015-01-26 - Written (based on older code) - Bovy (IAS)
    """
    pad = kwargs.pop('pad', 3)
    try:
        si, ei = apwindow.waveregions(args[2], pad=pad, asIndex=True)
    except IOError:
        try:
            si, ei = apwindow.waveregions(args[2][:-1], pad=pad, asIndex=True)
        except IOError:
            raise IOError(
                "Windows for element %s could not be loaded, please specify an existing APOGEE element"
                % ((args[2].lower().capitalize())))
        if args[2][-1] == '1':
            si = si[:len(si) // 2]
            ei = ei[:len(ei) // 2]
        else:
            si = si[len(si) // 2:]
            ei = ei[len(ei) // 2:]
        # Remove the number from the element
        newargs = (args[0], args[1], args[2][:-1])
        for ii in range(len(args) - 3):
            newargs = newargs + (args[ii + 3], )
        args = newargs
    # Also get the number and total width of all of the windows
    dlam = apwindow.total_dlambda(args[2], pad=pad)
    numw = apwindow.num(args[2])
    # Set spacing between windows
    if numw > 20:
        kwargs['skipdx'] = 0.003
        kwargs['_noskipdiags'] = True
    elif numw > 15:
        kwargs['skipdx'] = 0.01
    # Set initial space to zero
    kwargs['_startendskip'] = 0
    # Set initial figure width
    if not kwargs.get('overplot', False) and not 'fig_width' in kwargs:
        if dlam > 150.:
            kwargs['fig_width'] = 8.4
        else:
            kwargs['fig_width'] = 4.2
    # Don't tick x
    kwargs['_noxticks'] = True
    # Label the largest wavelength in angstrom
    kwargs['_labelwav'] = True
    # Don't label the lines unless explicitly asked for
    kwargs['labelLines'] = kwargs.get('labelLines', False)
    # Plot the weights as well
    if kwargs.pop('plot_weights', False):
        kwargs['_plotw'] = apwindow.read(args[2], apStarWavegrid=True)
        if kwargs.get('apStar', False):
            kwargs['yrange'] = kwargs.get('yrange',
                                          [0., 1.1 * numpy.nanmax(args[1])])
        else:
            kwargs['yrange'] = kwargs.get('yrange', [0., 1.2])
    # mark the 'lines'
    markLines = kwargs.get('markLines', not 'overplot' in kwargs)
    if markLines and not '_markwav' in kwargs:
        kwargs['_markwav'] = apwindow.lines(args[2])
    # Plot
    waveregions(args[0],
                args[1],
                startindxs=si,
                endindxs=ei,
                *args[3:],
                **kwargs)
    # Add label
    bovy_plot.bovy_text(r'$\mathrm{%s}$' % ((args[2].lower().capitalize())),
                        top_left=True,
                        fontsize=10,
                        backgroundcolor='w')
    return None
Exemplo n.º 48
0
def waveregions(*args, **kwargs):
    """
    NAME:
       waveregions
    PURPOSE:
       plot selected regions of the spectrum in one row
    INPUT:
       Either:
          (a) wavelength, spectrum (\AA,spectrum units)
          (b) spectrum (assumed on standard APOGEE re-sampled wavelength grid)
          (c) location ID, APOGEE ID (default loads aspcapStar, loads extension ext(=1); apStar=True loads apStar spectrum)
    KEYWORDS:
       File loading:
          ext= (1) extension to load
          apStar= (False) if True, load the apStar spectrum
          apStarIndx= (1) index in the apStar spectrum to load
       Chunks position:
          startlams, endlams= start and end wavelength in \AA of the various chunks (takes precedence over startindxs, endindxs)
          startindxs, endindxs= star and end index in the wavelength array of the various chunks
       Plotting-specific keywords
          labelLines= (True) label some lines
          noMolecLines= (False) don't label the molecules
          cleanZero= (True) replace <= zero entries with NaN
          labelID= A string ID that will be placed in the top-left corner
          labelTeff, labellogg, labelmetals, labelafe= parameter labels that will be placed in the top-right corner
          noxlabel= (False) if True, don't label the x axis
          pyplot.plot args and kwargs
    OUTPUT:
       plot to output
       The final axes allow one to put additional labels on the plot, e.g., for adding the APOGEE ID:
       bovy_plot.bovy_text(r'$\mathrm{%s}$' % '2M02420597+0837017',top_left=True)       
       Note that an ID (e.g., the apogee ID) and Teff, logg, metallicity, and alpha-enhancement labels can be added using the keywords label* above
    HISTORY:
       2015-01-18 - Written (based on older code) - Bovy (IAS)
    """
    # Grab non-pyplot.plot kwargs
    apStar = kwargs.pop('apStar', False)
    labelLines = kwargs.pop('labelLines', not 'overplot' in kwargs)
    noMolecLines = kwargs.pop('noMolecLines', False)
    cleanZero = kwargs.pop('cleanZero', True)
    noxticks = kwargs.pop('_noxticks', False)
    noxlabel = kwargs.pop('noxlabel', False)
    noskipdiags = kwargs.pop('_noskipdiags', False)
    labelwav = kwargs.pop('_labelwav', False)
    plotw = kwargs.pop('_plotw', None)
    markLines = kwargs.pop('markLines', False)
    markwav = kwargs.pop('_markwav', None)
    # Labels
    labelID = kwargs.pop('labelID', None)
    labelTeff = kwargs.pop('labelTeff', None)
    labellogg = kwargs.pop('labellogg', None)
    labelmetals = kwargs.pop('labelmetals', None)
    labelafe = kwargs.pop('labelafe', None)
    # Clean bad lines
    if cleanZero:
        args[1][args[1] <= 0.] = numpy.nan
    # Chunk parameters
    if 'startlams' in kwargs:
        # Turn startlams into a startindxs and similar for endlams
        startlams = kwargs.pop('startlams')
        endlams = kwargs.pop('endlams')
        startindxs = []
        endindxs = []
        for ii in range(len(startlams)):
            startindxs.append(numpy.argmin(numpy.fabs(startlams[ii] -
                                                      args[0])))
            endindxs.append(numpy.argmin(numpy.fabs(endlams[ii] - args[0])))
    else:
        startindxs = kwargs.pop('startindxs',
                                [322, 1794, 2707, 3850, 4740, 5820, 7185])
        endindxs = kwargs.pop('endindxs',
                              [590, 1940, 2857, 4025, 5070, 5955, 7400])
    nregions = len(startindxs)
    # Calculate the width of the plot
    dx= numpy.array([args[0][numpy.amin([len(args[0])-1,endindxs[ii]])]\
                         -args[0][numpy.amax([0,startindxs[ii]-1])] \
                         for ii in range(nregions)],
                    dtype='float')
    # Adjust 0 (and -1) to start (end) a little further
    startendskip = kwargs.pop('_startendskip', _STARTENDSKIP)
    dx[0]= args[0][numpy.amin([len(args[0])-1,endindxs[0]])]\
        -args[0][numpy.amax([0,startindxs[0]-startendskip])]
    dx[-1]= args[0][numpy.amin([len(args[0])-1,endindxs[-1]+startendskip])]\
        -args[0][numpy.amax([0,startindxs[-1]-1])]
    if nregions == 1:  #special case
        dx= [args[0][numpy.amin([len(args[0])-1,endindxs[0]+startendskip])]\
                 -args[0][numpy.amax([0,startindxs[0]-startendskip])]]
    # Determine a good step for the tickmarks
    tickStepTmp = numpy.log10(numpy.sum(dx) / 10.) % 1
    if tickStepTmp > numpy.log10(1.5) and tickStepTmp < numpy.log10(3.5):
        tickStep = 2. * 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    elif tickStepTmp > numpy.log10(3.5) and tickStepTmp < numpy.log10(7.5):
        tickStep = 5. * 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    else:
        tickStep = 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    dx /= numpy.sum(dx)
    if noxticks:
        totdx = 0.825
    else:
        totdx = 0.85
    skipdx = kwargs.pop('skipdx', 0.015)
    dx *= (totdx - (nregions - 1) * skipdx)
    # Setup plot
    overplot = kwargs.pop('overplot', False)
    if not overplot:
        bovy_plot.bovy_print(fig_width=kwargs.pop('fig_width', 8.4),
                             fig_height=kwargs.pop('fig_height', 2.5),
                             axes_labelsize=16,
                             text_fontsize=14,
                             legend_fontsize=12,
                             xtick_labelsize=12,
                             ytick_labelsize=12)
        pyplot.figure()
    if overplot:
        yrange = numpy.array(pyplot.gca().get_ylim())
        kwargs.pop('yrange', None)  # pop if there
    elif apStar:
        yrange = kwargs.pop('yrange', [0., 1.1 * numpy.nanmax(args[1])])
    else:
        yrange = kwargs.pop('yrange', [0.2, 1.2])
    # Deal with the label
    if apStar:
        ylabel = kwargs.pop(
            'ylabel',
            r'$f_\lambda(\lambda)\,(10^{-17}\,\mathrm{erg\, s}^{-1}\,\mathrm{cm}^{-2}\,\AA^{-1})$'
        )
    else:
        ylabel = kwargs.pop('ylabel', r'$f/f_c(\lambda)$')
    kwargs['zorder'] = kwargs.get('zorder', 10)
    for ii in range(nregions):
        # Setup the axes
        if ii == 0:
            left, bottom, width, height = 0.1 + (
                0.85 - totdx) * 2., 0.125, dx[ii], 0.8
        else:
            left, bottom, width, height= 0.1+(0.85-totdx)*2.+numpy.cumsum(dx)[ii-1]+skipdx*ii,\
                0.125, dx[ii], 0.8
        thisax = pyplot.axes([left, bottom, width, height])
        fig = pyplot.gcf()
        fig.sca(thisax)
        startindx, endindx = startindxs[ii], endindxs[ii]
        if ii == 0 and nregions == 1:
            xrange = [
                args[0][numpy.amax([0, startindx - startendskip])] -
                _LAMBDASUB, args[0][numpy.amin(
                    [len(args[0]) - 1, endindx + startendskip])] - _LAMBDASUB
            ]
        elif ii == 0:
            xrange = [
                args[0][numpy.amax([0, startindx - startendskip])] -
                _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx])] - _LAMBDASUB
            ]
        elif ii == (nregions - 1):
            xrange = [
                args[0][numpy.amax([0, startindx - 1])] - _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx + startendskip
                                    ])] - _LAMBDASUB
            ]
        else:
            xrange = [
                args[0][numpy.amax([0, startindx - 1])] - _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx])] - _LAMBDASUB
            ]
        thisax.plot(args[0][startindx:endindx] - _LAMBDASUB,
                    args[1][startindx:endindx], *args[2:], **kwargs)
        if not plotw is None:
            thisax.plot(args[0][startindx:endindx] - _LAMBDASUB,
                        plotw[startindx:endindx],
                        '-',
                        lw=2.,
                        color='0.65',
                        zorder=1)
        thisax.set_xlim(xrange[0], xrange[1])
        thisax.set_ylim(yrange[0], yrange[1])
        if noxticks:
            nullfmtx = NullFormatter()  # no labels, assume 1\AA
            thisax.xaxis.set_major_formatter(nullfmtx)
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(2.))
        else:
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(tickStep))
        bovy_plot._add_ticks(xticks=True - noxticks)
        if ii > 0:
            nullfmt = NullFormatter()  # no labels
            thisax.yaxis.set_major_formatter(nullfmt)
        elif not overplot:
            pyplot.ylabel(ylabel)
        # Remove spines between different wavelength regions
        if ii == 0 and not nregions == 1:
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(right=False, which='both')
        elif ii == (nregions - 1) and not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False, which='both')
        elif not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False, which='both')
            thisax.tick_params(right=False, which='both')
        # Plot cut-out markers
        cutOutkwargs = dict(transform=thisax.transAxes,
                            color='k',
                            clip_on=False)
        if not noskipdiags:
            d = .015  # how big to make the diagonal lines in axes coordinates
            slope = 1. / (dx[ii] + 0.2 * skipdx) / 3.
            if ii == 0 and not nregions == 1:
                thisax.plot((1 - slope * d, 1 + slope * d), (-d, +d),
                            **cutOutkwargs)
                thisax.plot((1 - slope * d, 1 + slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
            elif ii == (nregions - 1) and not nregions == 1:
                thisax.plot((-slope * d, +slope * d), (-d, +d), **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
            elif not nregions == 1:
                thisax.plot((1 - slope * d, 1 + slope * d), (-d, +d),
                            **cutOutkwargs)
                thisax.plot((1 - slope * d, 1 + slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (-d, +d), **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
        else:  #plot gray bands
            cutOutkwargs['color'] = '0.5'
            thisax.fill_between((1., 1. + skipdx), (0., 0.), (1., 1.),
                                **cutOutkwargs)
        # Label the lines
        if labelLines:
            _label_all_lines(args[0][startindx], args[0][endindx], thisax,
                             args[0], args[1], noMolecLines)
        # Mark the lines
        if markLines:
            _mark_lines(markwav, args[0][startindx], args[0][endindx], thisax,
                        args[0], args[1])
        # Label the largest round wavelength in angstrom for windows
        if labelwav:
            bovy_plot.bovy_text(
                2 * numpy.floor((xrange[1] - (nregions > 15)) / 2.),
                yrange[0] + 0.05 * (yrange[1] - yrange[0]),
                r'$\lambda\kern 0.1em%i,%03i$' %
                (15 + int(numpy.floor(xrange[1] / 1000.)),
                 int(2. * numpy.floor(
                     (xrange[1] - (nregions > 15)) / 2.) % 1000.)),
                horizontalalignment='center',
                verticalalignment='bottom',
                rotation='vertical',
                fontsize=10.)
    # Add the x-axis label
    if not nregions == 1:
        thisax = pyplot.axes([0.1 + (0.85 - totdx) * 2., 0.125, totdx, 0.8])
        pyplot.gcf().sca(thisax)
        thisax.set_ylim(yrange[0], yrange[1])
        thisax.spines['left'].set_visible(False)
        thisax.spines['right'].set_visible(False)
        thisax.spines['bottom'].set_visible(False)
        thisax.spines['top'].set_visible(False)
        thisax.tick_params(labelleft='off')
        thisax.tick_params(left=False, which='both')
        thisax.tick_params(right=False, which='both')
        thisax.tick_params(labelbottom='off')
        thisax.tick_params(bottom=False, which='both')
        thisax.tick_params(top=False, which='both')
    if not overplot and not noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda-%i,000\,(\AA)$' %
                          (int(_LAMBDASUB / 1000.)),
                          labelpad=10 - (nregions == 1) * 10)
    elif not overplot and noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda\,(\AA)$',
                          labelpad=3 - (nregions == 1) * 3)
    if not nregions == 1:
        thisax.set_zorder(-1)
        # Start another axis object for later labeling
        thisax = pyplot.axes([0.1 + (0.85 - totdx) * 2., 0.125, totdx, 0.8])
        pyplot.gcf().sca(thisax)
        thisax.patch.set_facecolor('None')
        thisax.set_zorder(10)
    # Labels
    if not labelID is None:
        bovy_plot.bovy_text(r'$\mathrm{%s}$' % labelID,
                            top_left=True,
                            fontsize=10)
    if not labelTeff is None or not labellogg is None \
            or not labelmetals is None or not labelafe is None:
        nParamLabels= int(not labelTeff is None)\
            +int(not labellogg is None)\
            +int(not labelmetals is None)\
            +int(not labelafe is None)
        # Label parameters
        paramStr = ''
        if not labelTeff is None:
            paramStr += r'T_\mathrm{eff}= %i\,\mathrm{K}' % (int(labelTeff))
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labellogg is None:
            paramStr += r'\log g= %.1f' % labellogg
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labelmetals is None:
            paramStr += r'[\mathrm{M/H}]= %.2f' % labelmetals
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labelafe is None:
            paramStr += r'[\alpha/\mathrm{M}]= %.2f' % labelafe
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        bovy_plot.bovy_text(r'$%s$' % paramStr, top_right=True, fontsize=10)
    return None
Exemplo n.º 49
0
def showExamplegr(filename='../data/SDSSJ203817.37+003029.8.fits',
                constraints=None,basefilename='SDSSJ203817.37+003029.8'):
    """
    NAME:
       showExamplegr
    PURPOSE:
       show an example of a power-law structure function GP covariance function
       fit to an SDSS quasar for g and r
    INPUT:
       filename - filename with the data
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
    OUTPUT:
       writes several plots
    HISTORY:
       2010-08-11 - Written - Bovy (NYU)
    """
    file= fu.table_fields(filename)
    mjd_g= nu.array(file.mjd_g)/365.25
    g= nu.array(file.g)
    err_g= nu.array(file.err_g)
    mjd_r= nu.array(file.mjd_r)/365.25
    r= nu.array(file.r)
    err_r= nu.array(file.err_r)

    mask= (mjd_g != 0)*(g < 20.6)*(g > 19.7)#Adjust for non-g
    g= g[mask]
    g-= nu.mean(g)
    err_g= err_g[mask]
    mjd_g= mjd_g[mask]
    mjd_g-= nu.amin(mjd_g)
    meanErr_g= nu.mean(err_g)

    r= r[mask]
    r-= nu.mean(r)
    err_r= err_r[mask]
    mjd_r= mjd_r[mask]
    mjd_r-= nu.amin(mjd_r)
    meanErr_r= nu.mean(err_r)
    
    meanErr_gr= nu.mean(nu.sqrt(err_r**2.+err_g**2.))

    nu.random.seed(4)
    nGP=5
    nx=201
    params_mean= ()
    from powerlawSFgr import covarFunc
    params= {'logGamma': array([-9.27821954]), 'logGammagr': array([-19.85172122]), 'gamma': array([ 0.45932629]), 'gammagr': array([ 0.29784021])}
    cf= covarFunc(**params)
    params_covar= (cf)
    ndata= len(g)
    if constraints is None:
        listx= [(t,'g') for t in mjd_g]
        listx.extend([(t,'r') for t in mjd_r])
        listy= [m for m in g]
        listy.extend([m for m in r])
        listy= nu.array(listy)
        noise= [m for m in err_g]
        noise.extend([m for m in err_r])
        noise= nu.array(noise)
        trainSet= trainingSet(listx=listx,listy=listy,noise=noise)
        constraints= trainSet
    else:
        constraints= nu.array([])

    useconstraints= constraints
    txs= nu.linspace(-0.1,6.5,nx)
    xs= [(txs[ii],'g') for ii in range(nx)]
    xs.extend([(txs[ii],'r') for ii in range(nx)])
    GPsamples= eval_gp(xs,mean,covar,(),params_covar,nGP=nGP,constraints=useconstraints,tiny_cholesky=.000001)
    thismean= calc_constrained_mean(xs,mean,params_mean,covar,params_covar,useconstraints)
    thiscovar= calc_constrained_covar(xs,covar,params_covar,useconstraints)
    plot.bovy_print()
    pyplot.plot(txs,GPsamples[0,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_g,g,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    pyplot.plot(txs,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_full.ps')


    plot.bovy_print()
    pyplot.figure()
    pyplot.plot(txs,GPsamples[0,nx-1:-1],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_r,r,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,nx-1:-1],'-',color=str(0.25+ii*.5/(nGP-1)))
    pyplot.plot(txs,thismean[nx-1:-1],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_r,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$r-\langle r\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_fullr.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 0
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    colors= colors-nu.mean(colors)
    pyplot.plot(txs,colors,'-',color='0.25')
    if isinstance(constraints,trainingSet):
        plot.bovy_plot(mjd_g,g-r,'k.',zorder=5,ms=10,overplot=True)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        colors= colors-nu.mean(colors)
        pyplot.plot(txs,colors,'-',color=str(0.25+ii*.5/(nGP-1)))
    plotthismean= nu.zeros(nx)
    for ii in range(nx):
        plotthismean[ii]= thismean[ii]-thismean[ii+nx]
    pyplot.plot(txs,plotthismean,'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.18,yerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-r- \langle g - r \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    if isinstance(constraints,trainingSet):
        pyplot.ylim(-0.25,.25)
    else:
        pass #pyplot.ylim(-10.,10.)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_color.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 2
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    pyplot.plot(colors,GPsamples[ii,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(g-r,g,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        pyplot.plot(colors,GPsamples[ii,0:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    colors= nu.array([thismean[jj]-thismean[jj+nx] for jj in range(nx)])
    pyplot.plot(colors,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(.13,-0.3,yerr=meanErr_g,xerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$g-r-\langle g-r\rangle\ [\mathrm{mag}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-.2,.2)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_ggr.ps')

    return

    plot.bovy_print()
    pyplot.plot(xs,GPsamples[0,:],'-',color='0.25')
    if not constraints == []:
        plot.bovy_plot(mjd_g,g,'k.',zorder=5,ms=10,overplot=True)
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(xs,GPsamples[ii,:],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints == []:
        pyplot.errorbar(6.15,-0.1,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$m-\langle m\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(3,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_zoom.ps')


    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        pyplot.loglog(sc.arange(1.,len(GPsamples[ii,:])/2)*(xs[1]-xs[0]),
                      2.*sc.var(GPsamples[ii,:])-2.*sc.correlate(GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),"same")[1:len(GPsamples[ii,:])/2][::-1]/len(GPsamples[ii,:]),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(xs[1]-xs[0]),xs[len(xs)/2]]
    pyplot.loglog(xline,nu.exp(-3.02045715)*nu.array(xline)**(0.5868293),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfunc.ps')
Exemplo n.º 50
0
def plot_fehafe(basefilename):
    #First read the sample
    data= apread.rcsample()
    data= data[data['SNR'] >= 70.]
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #R and z ranges to plot
    Rmins= [5.,7.,9.]
    Rmaxs= [7.,9.,11.]
    zmins= [0.,0.5,1.]
    zmaxs= [0.5,1.,2.]
    nRbins= len(Rmins)
    nzbins= len(zmins)
    for ii in range(nRbins):
        for jj in range(nzbins):
            #Cut data to relevant range
            tindx= (data['RC_GALR'] > Rmins[ii])\
                *(data['RC_GALR'] <= Rmaxs[ii])\
                *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\
                *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj])
            tdata= data[tindx]
            bovy_plot.bovy_print()
            if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX:
                bovy_plot.scatterplot(tdata['METALS'],
                                      tdata['ALPHAFE'],
                                      'k.',
                                      levels=[0.68,.90],
                                      #special.erf(numpy.arange(1,3)/numpy.sqrt(2.)),
                                      xrange=[-1.2,0.7],
                                      yrange=[-0.12,0.42],
                                      xlabel=r'$[\mathrm{Fe/H}]$',
                                      ylabel=r'$[\alpha/\mathrm{H}]$',
                                      onedhists=True,bins=31,onedhistsbins=21)
            else:
                axScatter,axHistx, axHisty=\
                    bovy_plot.bovy_plot(tdata['METALS'],
                                        tdata['ALPHAFE'],
                                        'k.',
                                        xrange=[-1.2,0.7],
                                        yrange=[-0.12,0.42],
                                        xlabel=r'$[\mathrm{Fe/H}]$',
                                        ylabel=r'$[\alpha/\mathrm{H}]$',
                                        onedhists=True,bins=21)
            if _ADDBOVYRIX:
                add_bovy_rix(axScatter,Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])
            if not _NOLINE:
                #Overplot ridge line
                bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)],
                                    '-',lw=2.,color='y',overplot=True)
            bovy_plot.bovy_text(r'$%i < R / \mathrm{kpc} \leq %i$' % (Rmins[ii],Rmaxs[ii]) +'\n'+r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]),
                                    top_left=True,size=16.)
            bovy_plot.bovy_end_print(basefilename+'_%iR%i_%.1fz%.1f.' % (Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])+_EXT)
    #Plot z bins only
    zmins= [0.,0.5,1.,2.]
    zmaxs= [0.5,1.,2.,4.]
    nzbins= len(zmins)
    for jj in range(nzbins):
        #Cut data to relevant range
        tindx= (data['RC_GALR'] > 4.)\
            *(data['RC_GALR'] <= 9.)\
                *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\
                *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj])
        tdata= data[tindx]
        bovy_plot.bovy_print()
        if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX:
            bovy_plot.scatterplot(tdata['METALS'],
                                  tdata['ALPHAFE'],
                                  'k.',
                                  levels=[0.68,.90],
                                  xrange=[-1.2,0.7],
                                  yrange=[-0.12,0.42],
                                  xlabel=r'$[\mathrm{Fe/H}]$',
                                  ylabel=r'$[\alpha/\mathrm{H}]$',
                                  onedhists=True,bins=31,onedhistsbins=31)
        else:
            axScatter,axHistx, axHisty=\
                bovy_plot.bovy_plot(tdata['METALS'],
                                    tdata['ALPHAFE'],
                                    'k.',
                                    xrange=[-1.2,0.7],
                                    yrange=[-0.12,0.42],
                                    xlabel=r'$[\mathrm{Fe/H}]$',
                                    ylabel=r'$[\alpha/\mathrm{H}]$',
                                    onedhists=True,bins=21)
        if _ADDBOVYRIX:
            add_bovy_rix(axScatter,4.,9.,zmins[jj],zmaxs[jj])
        #Overplot ridge line
        bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)],
                            '-',lw=2.,color='y',overplot=True)
        bovy_plot.bovy_text(r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]),
                                top_left=True,size=16.)
        bovy_plot.bovy_end_print(basefilename+'_%.1fz%.1f.' % (zmins[jj],zmaxs[jj])+_EXT)
    #Plot scatter in the high-alpha sequence
    #Histograms in 3 R bins
    bovy_plot.bovy_print(fig_width=7.)
    overplot= False
    colors= ['y','k','r']
    labelposx= 0.235
    labelposy= [13.,11.,9.]
    for ii in range(nRbins):
        tindx= (data['RC_GALR'] > Rmins[ii])\
            *(data['RC_GALR'] <= Rmaxs[ii])\
            *(numpy.fabs(data['RC_GALZ']) <= 3.)
        tdata= data[tindx]
        hindx= determine_highalpha(tdata)
        tdata= tdata[hindx]
        bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']),
                            color=colors[ii],histtype='step',
                            bins=28,range=[-0.275,0.25],yrange=[0.,15.],
                            weights=numpy.ones(len(tdata)),
                            xlabel=r'$\delta[\alpha\mathrm{/Fe}]$',
                            overplot=overplot,normed=True)
        dafe= tdata['ALPHAFE']-ridge1(tdata['METALS'])
        dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)]
        txa, txm, txc= run_xd(dafe)
        print txm.flatten(), numpy.sqrt(txc.flatten()), txa[0]*len(dafe)
        bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2.,
                            color=colors[ii],overplot=True)
        bovy_plot.bovy_text(labelposx,labelposy[ii],
                            r'$%i < R \leq %i: \sigma = %.3f$' % (Rmins[ii],Rmaxs[ii],numpy.sqrt(txc[0,0,0])),
                            size=16.,color=colors[ii],ha='right')
        overplot= True
    bovy_plot.bovy_end_print(basefilename+'_afefehhist.%s' % _EXT)
    #High SN
    bovy_plot.bovy_print(fig_width=7.)
    overplot= False
    for ii in range(nRbins):
        tindx= (data['RC_GALR'] > Rmins[ii])\
            *(data['RC_GALR'] <= Rmaxs[ii])\
            *(numpy.fabs(data['RC_GALZ']) <= 3.)\
            *(data['SNR'] >= 150.)
        tdata= data[tindx]
        hindx= determine_highalpha(tdata)
        tdata= tdata[hindx]
        bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']),
                            color=colors[ii],histtype='step',
                            bins=19,range=[-0.275,0.15],yrange=[0.,19.5],
                            weights=numpy.ones(len(tdata)),
                            xlabel=r'$\delta[\alpha\mathrm{/Fe}]$',
                            normed=True,
                            overplot=overplot)
        dafe= tdata['ALPHAFE']-ridge1(tdata['METALS'])
        dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)]
        txa, txm, txc= run_xd(dafe)
        print txm.flatten(), numpy.sqrt(txc.flatten())
        bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2.,
                            color=colors[ii],overplot=True)
        overplot= True
    bovy_plot.bovy_end_print(basefilename+'_afefehhist_highsn.%s' % _EXT)
    return None
Exemplo n.º 51
0
def map_vc_like_simple(parser):
    """
    NAME:
       map_vc_like_simple
    PURPOSE:
       map the vc likelihood assuming knowledge of the DF
    INPUT:
       parser - from optparse
    OUTPUT:
       stuff as specified by the options
    HISTORY:
       2011-04-20 - Written - Bovy (NYU)
    """
    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        sys.exit(-1)
    #Set up DF
    dfc = dehnendf(beta=0.,
                   profileParams=(options.rd, options.rs, options.so),
                   correct=True,
                   niter=20)
    #Load data
    picklefile = open(args[0], 'rb')
    out = pickle.load(picklefile)
    picklefile.close()
    ndata = len(out)
    if options.linearfit:
        plot_linear(out, options.los * _DEGTORAD, options, dfc)
        return None
    #Map likelihood
    vcirc = nu.linspace(options.vmin, options.vmax, options.nvcirc)
    if not options.nbeta is None:
        betas = nu.linspace(options.betamin, options.betamax, options.nbeta)
        like = nu.zeros((options.nvcirc, options.nbeta))
        for ii in range(options.nvcirc):
            for kk in range(options.nbeta):
                thislike = 0.
                for jj in range(ndata):
                    thislike += single_vlos_loglike(vcirc[ii],
                                                    out[jj],
                                                    dfc,
                                                    options,
                                                    options.los * _DEGTORAD,
                                                    beta=betas[kk])
                like[ii, kk] = thislike
        like -= logsumexp(like.flatten()) + m.log(vcirc[1] - vcirc[0])
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(nu.exp(like).T,
                              origin='lower',
                              xrange=[options.vmin,options.vmax],
                              yrange=[options.betamin,options.betamax],
                              aspect=(options.vmax-options.vmin)/\
                                  (options.betamax-options.betamin),
                              cmap='gist_yarg',
                              xlabel=r'$v_c / v_0$',
                              ylabel=r'$\beta$',
                              contours=True,cntrmass=True,
                              levels=[0.682,0.954,0.997])
        bovy_plot.bovy_text(r'$\sigma_R(R_0) = %4.2f \ v_0$' % options.so\
                                +'\n'+\
                                r'$l  = %i^\circ$' % round(options.los),
                            top_left=True)
        bovy_plot.bovy_end_print(options.plotfilename)
    else:
        like = nu.zeros(options.nvcirc)
        for ii in range(options.nvcirc):
            thislike = 0.
            for jj in range(ndata):
                thislike += single_vlos_loglike(vcirc[ii], out[jj], dfc,
                                                options,
                                                options.los * _DEGTORAD)
            like[ii] = thislike
        like -= logsumexp(like) + m.log(vcirc[1] - vcirc[0])
        #Calculate mean and sigma
        vcmean = nu.sum(vcirc * nu.exp(like) * (vcirc[1] - vcirc[0]))
        vc2mean = nu.sum(vcirc**2. * nu.exp(like) * (vcirc[1] - vcirc[0]))
        #Plot
        bovy_plot.bovy_print()
        bovy_plot.bovy_plot(vcirc,
                            nu.exp(like),
                            'k-',
                            xlabel=r'$v_c / v_0$',
                            ylabel=r'$p(\mathrm{data} | v_c)$')
        bovy_plot.bovy_text(r'$\langle v_c \rangle = %4.2f \ v_0$' % vcmean +'\n'+
                            r'$\sqrt{\langle v_c^2 \rangle - \langle v_c \rangle^2} = %4.2f \ v_0$' % (m.sqrt(vc2mean-vcmean**2.)) +'\n'+\
                                r'$\sigma_R(R_0) = %4.2f \ v_0$' % options.so+'\n'+\
                                r'$l  = %i^\circ$' % round(options.los),
                            top_left=True)
        bovy_plot.bovy_end_print(options.plotfilename)
Exemplo n.º 52
0
def plot_nonaxi(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        cutmultiples=options.cutmultiples,
        jkmax=options.jkmax)
    #data= data[0:20]
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    indx = (data['GLON'] <= 30.)
    data['GLON'][
        indx] = 30.05  #Hack because the non-axi models don't go below Ro/2
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
        if options.dwarf:
            iso = [
                iso,
                isomodel.isomodel(imfmodel=options.imfmodel,
                                  Z=options.Z,
                                  dwarf=True,
                                  expsfh=options.expsfh)
            ]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, 'wb')
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data['H0MAG'][ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) +
                                    (data['J0MAG'] - data['K0MAG'])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF,
                                 _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data['H0MAG'][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) +
                                         (data['J0MAG'] - data['K0MAG'])[ii],
                                         mh)
    else:
        logpisodwarf = None
    """ #Does not matter anyway
    #clean logpiso
    dataindx= []
    for ii in range(len(data)):
        thislogpiso= logpiso[ii,:]-logsumexp(logpiso[ii,:])
        if numpy.all(thislogpiso == 0.): dataindx.append(False)
        else: dataindx.append(True)
    dataindx= numpy.array(dataindx,dtype='bool')
    data= data[dataindx]
    logpiso= logpiso[dataindx,:]
    logpisodwarf= logpisodwarf[dataindx,:]
    """
    #Calculate data means etc.
    #Calculate means
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
        avg_plate[ii] = numpy.mean(data['VHELIO'][indx])
        sig_plate[ii] = numpy.std(data['VHELIO'][indx])
        siga_plate[ii] = numpy.std(data['VHELIO'][indx]) / numpy.sqrt(
            numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile = open(args[0], 'rb')
    params = pickle.load(savefile)
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf = None
    avg_plate_model_fid = calc_model(params, options, data, logpiso,
                                     logpisodwarf, df, nlocs, locations, iso)
    print l_plate, avg_plate_model_fid
    #Plot everything
    bovy_plot.bovy_print(fig_height=6., fig_width=7.)
    dx = 0.8 / 5.
    left, bottom, width, height = 0.1, 0.9 - dx, 0.8, dx
    axTop = pyplot.axes([left, bottom, width, height])
    allaxes = [axTop]
    fig = pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0., 360.], [0., 0.], '-', color='0.5', overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$', top_right=True, size=14.)
    thisax = pyplot.gca()
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Second is bar
    print "Reading bar file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 2. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{bar}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Third is spiral
    print "Reading spiral file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/spiral/spiral_rect_vr_51_101.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 3. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{spiral}$', top_right=True, size=14.)
    pyplot.ylabel(
        r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}} \ [\mathrm{km\ s}^{-1}]$'
    )
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    #Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 4. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{elliptical}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, -45. * _DEGTORAD)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 5. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{elliptical}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    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
Exemplo n.º 54
0
def plot_linear(out, l, options, dfc):
    #Calculate sin(phi+l) for each
    ndata = len(out)
    sinphil = nu.zeros(ndata)
    vloss = nu.zeros(ndata)
    for ii in range(ndata):
        o = out[ii]
        sinphil[ii] = m.sin(o.phi() + l)
        vloss[ii] = o.vlos(obs=[1., 0., 0., 0., 1., 0.], ro=1., vo=1.)
    #Perform linear fit
    vlosf = []
    sphilf = []
    syf = []
    nsphilbins, minobjs = 150, 5
    for ii in range(nsphilbins):
        if ii == 0.:
            sphilmin, sphilmax = -1., -1. + 1. / nsphilbins * 2.
        elif ii == (nsphilbins - 1):
            sphilmin, sphilmax = 1. - 1. / nsphilbins * 2., 1.
        else:
            sphilmin, sphilmax = -1. + float(
                ii) / nsphilbins * 2., -1. + 2. * (ii + 1.) / nsphilbins
        indx = (sinphil <= sphilmax) * (sinphil > sphilmin)
        if len(set(indx)) == 1: continue
        if len(vloss[indx]) < minobjs: continue
        sphilf.append(nu.mean(sinphil[indx]))
        vlosf.append(nu.mean(vloss[indx]))
        syf.append(nu.var(vloss[indx]) / len(vloss[indx]))
    pfit = _my_polyfit(sphilf, vlosf, sy=syf)
    #Get asymmetricdrift
    va = dfc.asymmetricdrift(1.)
    vsun = -m.sin(l)
    #Fit for sigma_R and sigma_T
    svlos = []
    sphil = []
    sy = []
    nsphilbins, minobjs = 50, 10
    for ii in range(nsphilbins):
        if ii == 0.:
            sphilmin, sphilmax = 0., 1. / nsphilbins
        elif ii == (nsphilbins - 1):
            sphilmin, sphilmax = 1. - 1. / nsphilbins, 1.
        else:
            sphilmin, sphilmax = float(ii) / nsphilbins, (ii + 1.) / nsphilbins
        indx = (sinphil**2. <= sphilmax) * (sinphil**2. > sphilmin)
        if len(set(indx)) == 1: continue
        if len(vloss[indx]) < minobjs: continue
        sphil.append(nu.mean(sinphil[indx]**2.))
        svlos.append(nu.var(vloss[indx]))
        sy.append(nu.var(vloss[indx])**2. / (len(vloss[indx] - 1)))
    #And fit that
    sfit = _my_polyfit(sphil, svlos, sy=sy)
    bovy_plot.bovy_print()
    fig = pyplot.figure()
    pyplot.subplot(211)
    bovy_plot.bovy_plot(sphilf, vlosf, 'k.', overplot=True)
    pyplot.xlim(0.5, 1.)
    pyplot.ylim(0., .6)
    pyplot.xlabel(r'$sin(\phi + l)$')
    pyplot.ylabel(r'$v_{los} / v_0$')
    bovy_plot.bovy_plot(nu.array([-1., 1.]),
                        nu.array([pfit[1] - pfit[0], pfit[1] + pfit[0]]),
                        'k-',
                        overplot=True)
    bovy_plot.bovy_text(r'$v_c - v_a = %4.2f \ v_0$' % pfit[0]\
                            +'\n'+
                        r'$\mathrm{expected}\ v_c - v_a = %4.2f\ v_0$' % (1.-va)\
                            +'\n'+
                        r'$v_{local}\,\sin l = %4.2f\ v_0$' % (-pfit[1])\
                            +'\n'+
                        r'$\mathrm{expected}\ v_{local}\,\sin l = %4.2f$'\
                            % (-vsun)\
                            +'\n'+
                        r'$\sigma_R(R_0) = %4.2f \ v_0$' % options.so+'\n'+\
                            r'$l  = %i^\circ$' % round(options.los),
                        top_left=True)
    fig.subplots_adjust(hspace=0.3)
    pyplot.subplot(210)
    bovy_plot.bovy_plot(sphil, svlos, 'k.', overplot=True)
    pyplot.xlabel(r'$sin^2(\phi + l)$')
    pyplot.ylabel(r'$\sigma^2_{v_{los}} / v_0^2$')
    bovy_plot.bovy_text(r'$\sigma_R = %4.2f \ v_0$' % (nu.sqrt(sfit[1]))\
                            +'\n'+
                        r'$\mathrm{expected}\ \sigma_R = %4.2f\ v_0$' % (options.so)\
                            +'\n'+
                        r'$\sigma_T = %4.2f \ v_0$' % (nu.sqrt(sfit[0]+sfit[1]))\
                            +'\n'+
                        r'$\mathrm{expected}\ \sigma_T = %4.2f\ v_0$' % (options.so/dfc._gamma),
                        top_left=True)
    pyplot.ylim(0., 0.1)
    bovy_plot.bovy_plot(nu.array([0., 1.]),
                        nu.array([sfit[1], sfit[1] + sfit[0]]),
                        'k-',
                        overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Exemplo n.º 55
0
def plot_effsel_location(location, plotname):
    # Setup selection function
    selectFile = '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile, 'rb') as savefile:
            apo = pickle.load(savefile)
    else:
        # Setup selection function
        apo = apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile, apo)
    effselFile = '../savs/effselfunc-%i.sav' % location
    if not os.path.exists(effselFile):
        # Distances at which to calculate the effective selection function
        distmods = numpy.linspace(7., 15.5, 301)
        ds = 10.**(distmods / 5 - 2.)
        # Setup default effective selection function
        do_samples = True
        gd = mwdust.Green15(filter='2MASS H', load_samples=do_samples)
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=gd)
        sf_default = apof(location, ds)
        # Also calculate for a sample of MH
        data = get_rcsample()
        MH = data['H0'] - data['RC_DM']
        MH = numpy.random.permutation(MH)[:1000]
        sf_jkz = apof(location, ds, MH=MH)
        # Go through the samples
        sf_samples = numpy.zeros((20, len(ds)))
        if do_samples:
            for ii in range(20):
                # Swap in a sample for bestfit in the Green et al. (2015) dmap
                gd.substitute_sample(ii)
                apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=gd)
                sf_samples[ii] = apof(location, ds)
        zerodust = mwdust.Zero(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=zerodust)
        sf_zero = apof(location, ds)
        drimmel = mwdust.Drimmel03(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=drimmel)
        sf_drimmel = apof(location, ds)
        marshall = mwdust.Marshall06(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=marshall)
        try:
            sf_marshall = apof(location, ds)
        except IndexError:
            sf_marshall = -numpy.ones_like(ds)
        sale = mwdust.Sale14(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=sale)
        try:
            sf_sale = apof(location, ds)
        except (TypeError, ValueError):
            sf_sale = -numpy.ones_like(ds)
        save_pickles(effselFile, distmods, sf_default, sf_jkz, sf_samples,
                     sf_zero, sf_drimmel, sf_marshall, sf_sale)
    else:
        with open(effselFile, 'rb') as savefile:
            distmods = pickle.load(savefile)
            sf_default = pickle.load(savefile)
            sf_jkz = pickle.load(savefile)
            sf_samples = pickle.load(savefile)
            sf_zero = pickle.load(savefile)
            sf_drimmel = pickle.load(savefile)
            sf_marshall = pickle.load(savefile)
            sf_sale = pickle.load(savefile)
    # Now plot
    bovy_plot.bovy_print(fig_height=3.)
    rc('text.latex',
       preamble=r'\usepackage{amsmath}' + '\n' + r'\usepackage{amssymb}' +
       '\n' + r'\usepackage{yfonts}')
    if _PLOTDIST:
        distmods = 10.**(distmods / 5 - 2.)
        xrange = [0., 12.]
        xlabel = r'$D\,(\mathrm{kpc})$'
        ylabel = r'$\textswab{S}(\mathrm{location},D)$'
    else:
        xrange = [7., 15.8],
        xlabel = r'$\mathrm{distance\ modulus}\ \mu$'
        ylabel = r'$\textswab{S}(\mathrm{location},\mu)$'
    line_default = bovy_plot.bovy_plot(distmods,
                                       sf_default,
                                       'b-',
                                       lw=_LW,
                                       zorder=12,
                                       xrange=xrange,
                                       xlabel=xlabel,
                                       yrange=[0., 1.2 * numpy.amax(sf_zero)],
                                       ylabel=ylabel)
    pyplot.fill_between(distmods,
                        sf_default-_EXAGGERATE_ERRORS\
                            *(sf_default-numpy.amin(sf_samples,axis=0)),
                        sf_default+_EXAGGERATE_ERRORS\
                            *(numpy.amax(sf_samples,axis=0)-sf_default),
                        color='0.65',zorder=0)
    line_jkz = bovy_plot.bovy_plot(distmods,
                                   sf_jkz,
                                   'g-.',
                                   lw=2. * _LW,
                                   overplot=True,
                                   zorder=13)
    line_zero = bovy_plot.bovy_plot(distmods,
                                    sf_zero,
                                    'k--',
                                    lw=_LW,
                                    overplot=True,
                                    zorder=7)
    line_drimmel = bovy_plot.bovy_plot(distmods,
                                       sf_drimmel,
                                       '-',
                                       color='gold',
                                       lw=_LW,
                                       overplot=True,
                                       zorder=8)
    line_marshall = bovy_plot.bovy_plot(distmods,
                                        sf_marshall,
                                        'r-',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=9)
    line_sale = bovy_plot.bovy_plot(distmods,
                                    sf_sale,
                                    'c-',
                                    lw=_LW,
                                    overplot=True,
                                    zorder=10)
    if location == 4378:
        pyplot.legend(
            (line_default[0], line_jkz[0], line_zero[0]),
            (r'$\mathrm{Green\ et\ al.\ (2015)}$',
             r'$\mathrm{Green\ et\ al.} + p(M_H)$',
             r'$\mathrm{zero\ extinction}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    elif location == 4312:
        pyplot.legend(
            (line_sale[0], line_marshall[0], line_drimmel[0]),
            (r'$\mathrm{Sale\ et\ al.\ (2014)}$',
             r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
             r'$\mathrm{Drimmel\ et\ al.\ (2003)}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    # Label
    lcen, bcen = apo.glonGlat(location)
    if numpy.fabs(bcen) < 0.1: bcen = 0.
    bovy_plot.bovy_text(r'$(l,b) = (%.1f,%.1f)$' % (lcen, bcen),
                        top_right=True,
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 56
0
pyplot.ylabel(r'$\mathrm{Heliocentric\ velocity}\ [\mathrm{km\ s}^{-1}]$')
if justSolar or noSolar or justData or dataMean:
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
pyplot.xlim(0.,360.)
pyplot.ylim(-200.,200.)
if not justData and not dataMean and not noSolar and not justSolar:
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
bovy_plot.bovy_plot(data['GLON'],data['VHELIO'],'k,',
                    yrange=[-200.,200.],
                    xrange=[0.,360.],overplot=True)
ndata_t= int(math.floor(len(data)/1000.))
ndata_h= len(data)-ndata_t*1000
if justData:
    bovy_plot.bovy_text(r'$|b|\ <\ 2^\circ,\ |l|\ >\ 35^\circ$'
                        +'\n'+r'$%i,%03i\ \mathrm{stars}$' % (ndata_t,ndata_h),
                        top_right=True)
    bovy_plot.bovy_end_print('apogee_vcirc_l_vhelio_justdata.'+ext)
    sys.exit(0)
bovy_plot.bovy_plot(l_plate,
                    avg_plate,
                    'o',overplot=True,mfc='0.5',mec='none')
if dataMean:
    bovy_plot.bovy_text(r'$|b|\ <\ 2^\circ,\ |l|\ >\ 35^\circ$'
                        +'\n'+r'$%i,%03i\ \mathrm{stars}$' % (ndata_t,ndata_h),
                        top_right=True)
    bovy_plot.bovy_end_print('apogee_vcirc_l_vhelio_datamean.'+ext)
    sys.exit(0)
#pyplot.errorbar(l_plate,avg_plate,yerr=sig_plate,marker='o',mfc='k',mec='w',
#                ls='none',color='0.75')
#Solar motion
Exemplo n.º 57
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
Exemplo n.º 58
0
def plot_liouville(plotfilename):
    E, Lz= -1.25, 0.6
    aAS= actionAngleStaeckel(pot=MWPotential2014,c=True,delta=0.5)
    #planarOrbit w/ the same energy
    o= Orbit([0.8,numpy.sqrt(2.*(E-evalPot(0.8,0.,MWPotential2014)-(Lz/0.8)**2./2.)),Lz/0.8,0.])
    #For the orbital period
    fo= Orbit([0.8,numpy.sqrt(2.*(E-evalPot(0.8,0.,MWPotential2014)-(Lz/0.8)**2./2.)),Lz/0.8,0.,0.001,0.])
    orbt= 2.*numpy.pi/aAS.actionsFreqs(fo)[4]
    norb= 200.
    nt= 20001
    ts= numpy.linspace(0.,norb*orbt,nt)
    start= time.time()
    integrator= 'dopr54_c'
    o.integrate_dxdv([1.,0.,0.,0.],ts,MWPotential2014,
                     method=integrator,
                     rectIn=True,rectOut=True)
    dx= o.getOrbit_dxdv()[:,:]
    o.integrate_dxdv([0.,1.,0.,0.],ts,MWPotential2014,
                     method=integrator,
                     rectIn=True,rectOut=True)
    dy= o.getOrbit_dxdv()[:,:]
    o.integrate_dxdv([0.,0.,1.,0.],ts,MWPotential2014,
                     method=integrator,
                     rectIn=True,rectOut=True)
    dvx= o.getOrbit_dxdv()[:,:]
    o.integrate_dxdv([0.,0.,0.,1.],ts,MWPotential2014,
                     method=integrator,
                     rectIn=True,rectOut=True)
    dvy= o.getOrbit_dxdv()[:,:]
    print integrator, time.time()-start
    #Calculate Jacobian
    jacs= numpy.array([numpy.linalg.det(numpy.array([dx[ii],dy[ii],
                                                     dvx[ii],dvy[ii]])) for ii in range(nt)])
    breakt= 8.
    pts= list(ts[ts < breakt])
    pts.extend(list((ts[ts >= breakt])[::10]))
    pts= numpy.array(pts)
    pjacs= list(jacs[ts < breakt])
    pjacs.extend(list((jacs[ts >= breakt])[::10]))
    pjacs= numpy.array(pjacs)
    print integrator, numpy.mean(jacs)-1.
    bovy_plot.bovy_print(fig_width=3.25,fig_height=4.5)
    pyplot.subplot(4,1,4)
    bovy_plot.bovy_plot(pts/orbt,numpy.fabs(pjacs-1.),color='k',
                        loglog=True,gcf=True,
                        xrange=[0.5,norb],
                        yrange=[10.**-12.,10.**0.],
                        xlabel=r'$\mathrm{Number\ of\ orbital\ periods}$')
    bovy_plot.bovy_text(r'$\texttt{dopr54\_c}$',
                        top_left=True,size=14.)
    bovy_plot.bovy_text(0.1,10.**44.5,
                        r'$|\mathrm{Determinant\ of\ volume\ transformation}-1|$',
                        fontsize=16.,
                        rotation='vertical')
    ax= pyplot.gca()
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter(r'$%0.f$'))
    ax.yaxis.set_ticks([10.**-12.,10.**-8.,10.**-4.,1.])
    nullfmt   = NullFormatter()         # no labels
    other_integrators= ['odeint',
                        'rk4_c','rk6_c']
    for ii,integrator in enumerate(other_integrators):
        start= time.time()
        o.integrate_dxdv([1.,0.,0.,0.],ts,MWPotential2014,
                         method=integrator,
                         rectIn=True,rectOut=True)
        dx= o.getOrbit_dxdv()[:,:]
        o.integrate_dxdv([0.,1.,0.,0.],ts,MWPotential2014,
                         method=integrator,
                         rectIn=True,rectOut=True)
        dy= o.getOrbit_dxdv()[:,:]
        o.integrate_dxdv([0.,0.,1.,0.],ts,MWPotential2014,
                         method=integrator,
                         rectIn=True,rectOut=True)
        dvx= o.getOrbit_dxdv()[:,:]
        o.integrate_dxdv([0.,0.,0.,1.],ts,MWPotential2014,
                         method=integrator,
                         rectIn=True,rectOut=True)
        dvy= o.getOrbit_dxdv()[:,:]
        print integrator, time.time()-start
        jacs= numpy.array([numpy.linalg.det(numpy.array([dx[jj],dy[jj],
                                                         dvx[jj],dvy[jj]])) for jj in range(nt)])
        pts= list(ts[ts < breakt])
        pts.extend(list((ts[ts >= breakt])[::10]))
        pts= numpy.array(pts)
        pjacs= list(jacs[ts < breakt])
        pjacs.extend(list((jacs[ts >= breakt])[::10]))
        pjacs= numpy.array(pjacs)
        print integrator, numpy.mean(jacs)-1.
        pyplot.subplot(4,1,ii+1)
        if integrator == 'odeint':
            yrange=[10.**-8.,10.**4.]
            yticks= [10.**-8.,10.**-4.,1.,10.**4.]
        else:
            yrange=[10.**-12.,10.**0.]
            yticks= [10.**-12.,10.**-8.,10.**-4.,1.]
        bovy_plot.bovy_plot(pts/orbt,numpy.fabs(pjacs-1.),color='k',
                            loglog=True,gcf=True,
                            xrange=[0.5,norb],
                            yrange=yrange)
        thisax= pyplot.gca()
        thisax.xaxis.set_major_formatter(nullfmt)
        thisax.yaxis.set_ticks(yticks)
        bovy_plot.bovy_text(r'$\texttt{%s}$' % (integrator.replace('_','\_')),
                            top_left=True,size=14.)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def plot_mapsurfdens(plotname):
    with open('../mapfits/tribrokenexpflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp = numpy.array(pickle.load(savefile))
    plotmaps = [19, 26, 32, 39, 45]
    bovy_plot.bovy_print(fig_width=8., fig_height=3.)
    maps = define_rcsample.MAPs()
    cmap = cm.coolwarm
    overplot = False
    Rs = numpy.linspace(4., 14., 1001)
    # Setup for saving the profiles
    csvfile = open(os.path.join('..', 'out', 'mapsurfdens_highalpha.csv'), 'w')
    writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
    writer.writerow(
        ['# Surface density profile for MAPs (Figure 11 in Bovy et al. 2016)'])
    writer.writerow([
        '# The first line lists the radii at which the surface density profiles'
    ])
    writer.writerow(['# are evaluated'])
    writer.writerow(
        ['# The rest of the file are the log surface profiles; the 0.025'])
    writer.writerow(['# lower limit and the 0.0975 upper limit (each 1 line)'])
    writer.writerow(['# Different MAPs are separated by a comment line'])
    writer.writerow(['{:.2f}'.format(x) for x in Rs])
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        # Create all density profiles
        samples = samples_brexp[ii, :, ::_SKIP]
        nsamples = len(samples[0])
        tRs = numpy.tile(Rs, (nsamples, 1)).T
        ldp = numpy.empty((len(Rs), nsamples))
        Rb = numpy.tile(numpy.exp(samples[3]), (len(Rs), 1))
        ihRin = numpy.tile(samples[0], (len(Rs), 1))
        ihRout = numpy.tile(samples[2], (len(Rs), 1))
        # Rb >= R0
        leRb = (tRs <= Rb) * (Rb >= densprofiles._R0)
        ldp[leRb] = ihRin[leRb] * (tRs[leRb] - densprofiles._R0)
        gtRb = (tRs > Rb) * (Rb >= densprofiles._R0)
        ldp[gtRb]= -ihRout[gtRb]*(tRs[gtRb]-densprofiles._R0)\
            +ihRout[gtRb]*(Rb[gtRb]-densprofiles._R0)\
            +ihRin[gtRb]*(Rb[gtRb]-densprofiles._R0)
        # Rb < R0, normalize outer at R0
        leRb = (tRs <= Rb) * (Rb < densprofiles._R0)
        ldp[leRb]= ihRin[leRb]*(tRs[leRb]-densprofiles._R0)\
            -ihRout[leRb]*(Rb[leRb]-densprofiles._R0)\
            -ihRin[leRb]*(Rb[leRb]-densprofiles._R0)
        gtRb = (tRs > Rb) * (Rb < densprofiles._R0)
        ldp[gtRb] = -ihRout[gtRb] * (tRs[gtRb] - densprofiles._R0)
        # Label and relative normalization
        tfeh = round(numpy.median(map['FE_H']) * 20.) / 20.
        if tfeh == 0.25: tfeh = 0.3
        if tfeh == -0.1: tfeh = -0.1
        print ii, tfeh, len(map)
        anorm = 10**(-10. * (-tfeh - 0.5))
        #if (-tfeh-0.4) > 0.3: anorm= 10**(-12.*(-tfeh+0.4))
        if (-tfeh - 0.5) == -0.2: anorm = 10**(-11. * (-tfeh - 0.5))
        anorm = 1. / anorm  # re-order
        anorm /= 3.
        norm = numpy.exp(numpy.median(ldp, axis=1))[numpy.argmin(
            numpy.fabs(Rs - densprofiles._R0))] / anorm
        bovy_plot.bovy_plot(Rs,
                            numpy.exp(numpy.median(ldp, axis=1)) / norm,
                            '-',
                            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05),
                            lw=2.,
                            overplot=overplot,
                            ylabel=r'$\Sigma(R)\times\mathrm{constant}$',
                            xrange=[0., 16.],
                            yrange=[0.000001, 90.],
                            semilogy=True)
        pyplot.fill_between(
            Rs,
            numpy.exp(
                numpy.sort(ldp, axis=1)[:, int(round(_SIGNIF * nsamples))]) /
            norm,
            numpy.exp(
                numpy.sort(ldp,
                           axis=1)[:, int(round(
                               (1. - _SIGNIF) * nsamples))]) / norm,
            color=cmap((tfeh + 0.5) / 0.4),
            lw=0.)
        overplot = True
        if ii == 19:
            bovy_plot.bovy_text(2.,
                                10.**1.,
                                r'$[\mathrm{Fe/H}]$',
                                size=16.,
                                color='k')
        bovy_plot.bovy_text(2.,
                            (numpy.exp(numpy.median(ldp, axis=1)) / norm)[0],
                            r'$%+.1f$' % tfeh,
                            size=16.,
                            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05))
        writer.writerow(['# High-alpha MAP w/ [Fe/H]=%g' % tfeh])
        writer.writerow(
            ['{:.3f}'.format(x) for x in list(numpy.median(ldp, axis=1))])
        writer.writerow([
            '{:.3f}'.format(x) for x in list(
                numpy.sort(ldp, axis=1)[:, int(round(_SIGNIF * nsamples))])
        ])
        writer.writerow([
            '{:.3f}'.format(x) for x in list(
                numpy.sort(ldp, axis=1)[:,
                                        int(round((1. - _SIGNIF) * nsamples))])
        ])
    csvfile.close()
    bovy_plot.bovy_text(10.,
                        10.**1.,
                        r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                        size=16.)
    pyplot.gca().tick_params(axis='y', which='minor', left='off', right='off')
    bovy_plot.bovy_end_print(plotname)