def create_mock_sample(data,dfc,trueVsolar,spiral=False):
    if spiral:
        #Read spiral vlos field
        spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav')
        potscale= 0.85
        xgrid= numpy.linspace(_RCXMIN,_RCXMAX-_RCDX,19)
        ygrid= numpy.linspace(_RCYMIN,_RCYMAX-_RCDX,19)
    ndata= len(data)
    mockvel= numpy.empty(ndata)
    dphil= data['RC_GALPHI']+data['GLON']/180.*numpy.pi
    cosdphil= numpy.cos(dphil)
    sindphil= numpy.sin(dphil)
    cosl= numpy.cos(data['GLON']/180.*numpy.pi)
    sinl= numpy.sin(data['GLON']/180.*numpy.pi)
    for ii in range(ndata):
        vrvt= dfc.sampleVRVT(data['RC_GALR'][ii]/8.,n=1.)
        mockvel[ii]= -vrvt[0,0]*cosdphil[ii]\
            +vrvt[0,1]*sindphil[ii]\
            -10.5*cosl[ii]/220.\
            -(1.+trueVsolar)*sinl[ii]
        if spiral:
            #Find which pixel this sample is in
            pixIndxX= numpy.argmin(numpy.fabs(data['RC_GALR'][ii]\
                                                  *numpy.cos(data['RC_GALPHI'][ii])\
                                                  -xgrid))
            pixIndxY= numpy.argmin(numpy.fabs(data['RC_GALR'][ii]\
                                                  *numpy.sin(data['RC_GALPHI'][ii])\
                                                  -ygrid))
            spiraldev= spvlos[pixIndxX,pixIndxY]
            mockvel[ii]+= spiraldev*potscale
    data['VHELIO_AVG']= mockvel*220.
    return data
Example #2
0
def determine_kxky_error():
    #Load fiducial bar model
    spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR)[1::2,1::2]
    #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR)[1::2,1::2]*0.85
    #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-7%s.sav' % _HIVRESSTR)[1::2,1::2]*0.25
    psd2d= bovy_psd.psd2d(spvlos)
    kmax= 1./_RCDX
    #Calculate maximum
    psd2d[psd2d.shape[0]/2-1:psd2d.shape[0]/2+2,psd2d.shape[1]/2-1:psd2d.shape[1]/2+2]= 0.
    tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape)
    tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2
    tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2
    print tmax0*kmax, tmax1*kmax
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xrange=[-kmax,kmax],
                          yrange=[-kmax,kmax],
                          xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$',
                          ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$')
    bovy_plot.bovy_end_print('/Users/bovy/Desktop/test.png')
    #Read the data for the noise
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
    data= data[indx]
    #Get residuals
    dx= _RCDX
    pix= pixelize_sample.pixelXY(data,
                                 xmin=_RCXMIN,xmax=_RCXMAX,
                                 ymin=_RCYMIN,ymax=_RCYMAX,
                                 dx=dx,dy=dx)
    resvunc= pix.plot('VHELIO_AVG',
                      func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                      returnz=True,justcalc=True)
    #Now do 1000 MC simulations to determine the error on kmax
    nmc= 1000
    kxmax= numpy.zeros(nmc)
    kymax= numpy.zeros(nmc)
    for ii in range(nmc):
        newresv= spvlos+numpy.random.normal(size=spvlos.shape)*resvunc/220.
        simpsd2d= bovy_psd.psd2d(newresv*220.)
        simpsd2d[simpsd2d.shape[0]/2-1:simpsd2d.shape[0]/2+2,simpsd2d.shape[1]/2-1:simpsd2d.shape[1]/2+2]= 0.
        tmax= numpy.unravel_index(numpy.argmax(simpsd2d),psd2d.shape)
        tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2
        tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2
        kmax= 1./_RCDX
        kxmax[ii]= tmax0*kmax
        kymax[ii]= tmax1*kmax
    print numpy.mean(kxmax), numpy.std(kxmax)
    print numpy.mean(kymax), numpy.std(kymax)
    return None
Example #3
0
def plot_psd2d(plotfilename):
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
    data= data[indx]
    #Get residuals
    dx= _RCDX
    binsize= .8#.765
    pix= pixelize_sample.pixelXY(data,
                                 xmin=_RCXMIN,xmax=_RCXMAX,
                                 ymin=_RCYMIN,ymax=_RCYMAX,
                                 dx=dx,dy=dx)
    resv= pix.plot(lambda x: dvlosgal(x,vtsun=220.+22.6),
                   returnz=True,justcalc=True)
    resvunc= pix.plot('VHELIO_AVG',
                      func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                      returnz=True,justcalc=True)
    psd2d= bovy_psd.psd2d(resv)
    tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape)
    tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2
    tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2
    kmax= 1./_RCDX
    print tmax0*kmax, tmax1*kmax
    #kmax= numpy.amax(numpy.fft.fftfreq(resv.shape[0]*2,_RCDX))
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xrange=[-kmax,kmax],
                          yrange=[-kmax,kmax],
                          xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$',
                          ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$')
    bovy_plot.bovy_end_print(plotfilename)
    if True:
        spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav')[1::2,1::2]
        potscale= 1.
Example #4
0
def plot_psd(plotfilename):
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
    data= data[indx]
    #Get residuals
    dx= _RCDX
    binsize= .8#.765
    pix= pixelize_sample.pixelXY(data,
                                 xmin=_RCXMIN,xmax=_RCXMAX,
                                 ymin=_RCYMIN,ymax=_RCYMAX,
                                 dx=dx,dy=dx)
    resv= pix.plot(lambda x: dvlosgal(x,vtsun=220.+22.5),
                   returnz=True,justcalc=True)
    resvunc= pix.plot('VHELIO_AVG',
                      func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                      returnz=True,justcalc=True)
    psd1d= bovy_psd.psd1d(resv,dx,binsize=binsize)
    print psd1d
    #Simulations for constant 3.25 km/s
    nnoise= _NNOISE
    noisepsd= numpy.empty((nnoise,len(psd1d[0])-4))
    for ii in range(nnoise):
        newresv= numpy.random.normal(size=resv.shape)*3.25
        noisepsd[ii,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1][1:-3]
    scale= 4.*numpy.pi#3.25/numpy.median(numpy.sqrt(noisepsd))
    print scale
    #Simulations for the actual noise
    nnoise= _NNOISE
    noisepsd= numpy.empty((nnoise,len(psd1d[0])-4))
    for ii in range(nnoise):
        newresv= numpy.random.normal(size=resv.shape)*resvunc
        noisepsd[ii,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1][1:-3]
    ks= psd1d[0][1:-3]
    if _ADDGCS:
        xrange=[.03,110.]
    else:
        xrange= [0.,1.]
    yrange= [0.,11.9]
    if _PROPOSAL:
        bovy_plot.bovy_print(fig_width=7.5,fig_height=3.)
    else:
        bovy_plot.bovy_print(fig_width=7.5,fig_height=4.5)
    apop= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psd1d[1][1:-3]
                                            -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)),
                        'ko',lw=2.,
                        zorder=12,
                        xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                        ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$',
                        semilogx=_ADDGCS,
                        xrange=xrange,yrange=yrange)
    if _DUMP2FILE:
        with open('bovy-apogee-psd.dat','w') as csvfile:
            writer= csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
            csvfile.write('#APOGEE\n')
            for ii in range(len(ks)):
                writer.writerow([ks[ii],
                                 (scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)))[ii],
                                 (scale*0.5*(psd1d[2][1:-3]**2.+_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)**2.)**0.5/numpy.sqrt(psd1d[1][1:-3]))[ii]])
    if _PROPOSAL:
        pyplot.gcf().subplots_adjust(bottom=0.15)
    pyplot.errorbar(ks,scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)),
                    yerr=scale*0.5*(psd1d[2][1:-3]**2.
                                    +_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)**2.)**0.5/numpy.sqrt(psd1d[1][1:-3]),
                    marker='None',ls='none',color='k')
    if _PLOTBAND:
#        bovy_plot.bovy_plot(ks,
#                            scale*numpy.median(numpy.sqrt(noisepsd),axis=0),
#                            '--',lw=2.,zorder=10,
#                            color='0.85',overplot=True)
#        bovy_plot.bovy_plot(ks,
#                            scale*numpy.sqrt(numpy.sort(noisepsd
#                                                        -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0),axis=0)[int(numpy.floor(0.99*_NNOISE)),:]),
#                            zorder=1,ls='--',overplot=True,
#                            color='0.65')
        pyplot.fill_between(ks,
                            scale*numpy.sqrt(numpy.sort(noisepsd
                                                        -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0),axis=0)[int(numpy.floor(_SIGNIF*_NNOISE)),:]),
                            zorder=0,
                            color='0.65')
    #Add a simple model of a spiral potential
    if _ADDSIMPLESPIRAL:
        if False:
            alpha= -12.5
            spvlos= simulate_vlos_spiral(alpha=alpha,
                                         gamma=1.2,
                                         xmin=_RCXMIN,xmax=_RCXMAX,
                                         ymin=_RCYMIN,ymax=_RCYMAX,
                                         dx=0.01)
            potscale= 1.35*1.2
            print numpy.arctan(2./alpha)/numpy.pi*180., numpy.sqrt(0.035/numpy.fabs(alpha)/2.)*potscale*220., numpy.sqrt(0.035/numpy.fabs(alpha))*potscale*220.
            simpsd1d= bovy_psd.psd1d(spvlos*220.*potscale,0.01,binsize=binsize)
            tks= simpsd1d[0][1:-3]
            bovy_plot.bovy_plot(tks,
                                scale*numpy.sqrt(simpsd1d[1][1:-3]),
                                'k--',lw=2.,overplot=True)
        #A better simulation
#        spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14.sav')
        spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav')
        potscale= 1.
        simpsd1d= bovy_psd.psd1d(spvlos*220.*potscale,0.33333333,binsize=binsize)
        tks= simpsd1d[0][1:-3]
#        alpha=-14.
#        print numpy.arctan(2./-14.)/numpy.pi*180., numpy.sqrt(0.075/numpy.fabs(alpha)/2.)*potscale*220., numpy.sqrt(0.075/numpy.fabs(alpha))*potscale*220.
        line1= bovy_plot.bovy_plot(tks,
                                   scale*numpy.sqrt(simpsd1d[1][1:-3]),
                                   'k--',lw=2.,overplot=True)
        if _DUMP2FILE:
            with open('bovy-bar-psd.dat','w') as csvfile:
                writer= csv.writer(csvfile, delimiter=',',
                                   quotechar='|', quoting=csv.QUOTE_MINIMAL)
                for ii in range(len(ks)):
                    writer.writerow([tks[ii],(scale*numpy.sqrt(simpsd1d[1][1:-3]))[ii]])
        #bovy_plot.bovy_plot(tks[tks > 0.7],
        #                    scale*numpy.sqrt(simpsd1d[1][1:-3][tks > 0.7]+4./scale**2.*(1.-numpy.tanh(-(tks[tks > 0.7]-0.9)/0.1))/2.),
        #                    'k-.',lw=2.,overplot=True)
        #line2= bovy_plot.bovy_plot(tks,
        #                           scale*numpy.sqrt(simpsd1d[1][1:-3]+4./scale**2.),
        #                           'k-.',lw=2.,overplot=True,dashes=(10,5,3,5))
        l1= pyplot.legend((line1[0],),
#                      (r'$\mathrm{Spiral}:\ \delta \phi_{\mathrm{rms}} = (10\,\mathrm{km\,s}^{-1})^2,$'+'\n'+r'$\mathrm{pitch\ angle} = 8^\circ$'+'\n'+r'$\mathrm{Sun\ near\ 2\!:\!1\ Lindblad\ resonance}$',),
                      (r'$\mathrm{Bar}:\ F_{R,\mathrm{bar}} / F_{R,\mathrm{axi}} = 1.5\%,$'+'\n'+r'$\mathrm{angle} = 25^\circ,$'+'\n'+r'$\mathrm{Sun\ near\ 2\!:\!1\ Lindblad\ resonance}$',),
                      loc='upper right',#bbox_to_anchor=(.91,.375),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False)
    #Add the lopsided and ellipticity constraints from Rix/Zaritsky
    if _ADDRIX:
        pyplot.errorbar([1./16.],[5.6],
                        yerr=[5.6/2.],
                        marker='d',color='0.6',
                        mew=1.5,mfc='none',mec='0.6')
        pyplot.errorbar([1./8./numpy.sqrt(2.)],[6.4],
                        yerr=numpy.reshape(numpy.array([6.4/0.045*0.02,6.4/0.045*0.03]),(2,1)),
                        marker='d',color='0.6',mec='0.6',
                        mew=1.5,mfc='none')
    if _ADDGCS:
        ks_gcs, psd_gcs, e_psd_gcs, gcsp= plot_psd_gcs()
    if _ADDRAVE:
        ks_rave, psd_rave, e_psd_rave, ravep= plot_psd_rave()
    if _ADDRED:
        plot_psd_red()
    l2= pyplot.legend((apop[0],ravep[0],gcsp[0]),
                      (r'$\mathrm{APOGEE}$',
                       r'$\mathrm{RAVE}$',
                       r'$\mathrm{GCS}$'),
                      loc='upper right',bbox_to_anchor=(.95,.750),
                      numpoints=1,
                      prop={'size':14},
                      frameon=False)
    pyplot.gca().add_artist(l1)
    pyplot.gca().add_artist(l2)
    #Plot an estimate of the noise, based on looking at the bands
    nks= numpy.linspace(2.,120.,2)
    if not 'mba23' in socket.gethostname():
        pyplot.fill_between(nks,[2.,2.],hatch='/',color='k',facecolor=(0,0,0,0),
                            lw=0.)
    #                        edgecolor=(0,0,0,0))
    pyplot.plot(nks,[2.,2.],color='k',lw=1.5)
    nks= numpy.linspace(0.17,2.,2)
    def linsp(x):
        return .8/(numpy.log(0.17)-numpy.log(2.))*(numpy.log(x)-numpy.log(0.17))+2.8
    if not 'mba23' in socket.gethostname():
        pyplot.fill_between(nks,linsp(nks),hatch='/',color='k',facecolor=(0,0,0,0),
                            lw=0.)
    #                        edgecolor=(0,0,0,0))   
    #Plot lines
    pyplot.plot([0.17,0.17],[0.,2.8],color='k',lw=1.5)
    pyplot.plot(nks,linsp(nks)+0.01,color='k',lw=1.5)
    bovy_plot.bovy_text(0.19,.5,r'$95\,\%\,\mathrm{noise\ range}$',
                        bbox=dict(facecolor='w',edgecolor='w'),fontsize=14.)
    if _INTERP:
        interpks= list(ks[:-5])
        interppsd= list((scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)))[:-5])
        interppsd_w= (scale*0.5*psd1d[2][1:-3]/numpy.sqrt(psd1d[1][1:-3]))[:-5]
        interppsd_w[:8]*= 0.025 #fiddling to get a decent fit
        interppsd_w[3:5]*= 0.001
        interppsd_w= list(interppsd_w)
        interpks.append(0.025)
        interppsd.append(10.**-5.)
        interppsd_w.append(0.00001)
        interpks.append(110.)
        interppsd.append(1.)
        interppsd_w.append(0.00001)
        if _ADDGCS:
            interpks.extend(ks_gcs)
            interppsd.extend(psd_gcs)
            interppsd_w.extend(e_psd_gcs)
        if _ADDRAVE:
            interpks.extend(ks_rave[5:])
            interppsd.extend(psd_rave[5:])
            interppsd_w.extend(e_psd_rave[5:])
        interpks= numpy.array(interpks)
        sortindx= numpy.argsort(interpks)
        interpks= interpks[sortindx]
        interppsd= numpy.array(interppsd)[sortindx]
        interppsd_w= interppsd/numpy.array(interppsd_w)[sortindx]
        interpindx= True-numpy.isnan(interppsd)
    #interpspec= interpolate.InterpolatedUnivariateSpline(interpks[interpindx],
        interpspec= interpolate.UnivariateSpline(numpy.log(interpks[interpindx]),
                                                 numpy.log(interppsd[interpindx]/3.),
                                                 w=interppsd_w,
                                                 k=3,s=len(interppsd_w)*0.8)
        pks= numpy.linspace(interpks[0],interpks[-1],201)
        #bovy_plot.bovy_plot(pks,
        #                    3.*numpy.exp(interpspec(numpy.log(pks))),
#                    'k-',overplot=True)
    def my_formatter(x, pos):
        return r'$%g$' % x
    def my_formatter2(x, pos):
        return r'$%g$' % (1./x)
    major_formatter = FuncFormatter(my_formatter)
    major_formatter2 = FuncFormatter(my_formatter2)
    ax= pyplot.gca()
    ax.xaxis.set_major_formatter(major_formatter)
    if not _PROPOSAL:
        ax2= pyplot.twiny()
        xmin, xmax= ax.xaxis.get_view_interval()
        ax2.set_xscale('log')
        ax2.xaxis.set_view_interval(1./xmin,1./xmax,ignore=True)
        ax2.set_xlabel('$\mathrm{Approximate\ scale}\,(\mathrm{kpc})$',
                       fontsize=12.,ha='center',x=0.5)
        ax2.xaxis.set_major_formatter(major_formatter)
    bovy_plot.bovy_end_print(plotfilename,dpi=300)
    return None
Example #5
0
def plot_psd_model(plotfilename,type):
    #Load fiducial
#    spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR)
    spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR)
    potscale= 1.
    simpsd1d= bovy_psd.psd1d(spvlos*potscale,0.33333333,binsize=0.8)
    tks= simpsd1d[0][1:-3]
    xrange=[.08,4.]
    if type.lower() == 'elliptical':
        eres= 31
        p= 0.
        vloscp= galpy_simulations.vlos_elliptical(res=eres,cp=0.02,sp=0.,p=p)
        vlossp= galpy_simulations.vlos_elliptical(res=eres,sp=0.02,cp=0.,p=p)
        vloscpsp= galpy_simulations.vlos_elliptical(res=eres,p=p,
                                                    sp=0.02/numpy.sqrt(2.),
                                                    cp=0.02/numpy.sqrt(2.))
        p=2.
        vloscpp2= galpy_simulations.vlos_elliptical(res=eres,cp=0.01,sp=0.,p=p)
        vlosspp2= galpy_simulations.vlos_elliptical(res=eres,sp=0.01,cp=0.,p=p)
        vloscpspp2= galpy_simulations.vlos_elliptical(res=eres,p=p,
                                                      sp=0.01/numpy.sqrt(2.),
                                                      cp=0.01/numpy.sqrt(2.))
        p=-3.
        vloscppm3= galpy_simulations.vlos_elliptical(res=eres,cp=0.05,sp=0.,p=p)
        vlossppm3= galpy_simulations.vlos_elliptical(res=eres,sp=0.05,cp=0.,p=p)
        vloscpsppm3= galpy_simulations.vlos_elliptical(res=eres,p=p,
                                                       sp=0.05/numpy.sqrt(2.),
                                                       cp=0.05/numpy.sqrt(2.))
        xgrid= numpy.linspace((_RCXMIN-8.)/8.+_RCDX/8./2.,
                              (_RCXMAX-8.)/8.-_RCDX/8./2.,
                              eres)
        dx= (xgrid[1]-xgrid[0])*8.
        psdcp= bovy_psd.psd1d(vloscp,dx,binsize=0.8)
        psdsp= bovy_psd.psd1d(vlossp,dx,binsize=0.8)
        psdcpsp= bovy_psd.psd1d(vloscpsp,dx,binsize=0.8)
        psdcpp2= bovy_psd.psd1d(vloscpp2,dx,binsize=0.8)
        psdspp2= bovy_psd.psd1d(vlosspp2,dx,binsize=0.8)
        psdcpspp2= bovy_psd.psd1d(vloscpspp2,dx,binsize=0.8)
        psdcppm3= bovy_psd.psd1d(vloscppm3,dx,binsize=0.8)
        psdsppm3= bovy_psd.psd1d(vlossppm3,dx,binsize=0.8)
        psdcpsppm3= bovy_psd.psd1d(vloscpsppm3,dx,binsize=0.8)
        ks= psdcp[0][1:-3]
        scale= 4.*numpy.pi*220.
        bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20)
        line1= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcp[1][1:-3]),
                                   'k-',lw=2.,
                                   semilogx=True,
#                                   xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                                   ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$',
                                   xrange=xrange,
                                   yrange=[0.,11.9],zorder=1)
        line2= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsp[1][1:-3]),
                                   'k--',lw=2.,
                                   overplot=True,zorder=1)
        line3= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpsp[1][1:-3]),
                                   'k-.',lw=2.,zorder=1,
                                   overplot=True)
        line4= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpp2[1][1:-3]),
                                   '-',lw=2.,color='c',zorder=1,
                                   overplot=True)
        line5= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdspp2[1][1:-3]),
                                   '--',lw=2.,color='c',zorder=1,
                                   overplot=True)
        line6= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpspp2[1][1:-3]),
                                   '-.',lw=2.,color='c',zorder=1,
                                   overplot=True)
        line7= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcppm3[1][1:-3]),
                                   '-',lw=2.,color='r',zorder=1,
                                   overplot=True)
        line8= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsppm3[1][1:-3]),
                                   '--',lw=2.,color='r',zorder=1,
                                   overplot=True)
        line9= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpsppm3[1][1:-3]),
                                   '-.',lw=2.,color='r',zorder=1,
                                   overplot=True)
        pyplot.annotate(r'$\mathrm{Elliptical\ perturbation}\ (m=2\ \mathrm{mode})$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=20.)
        l1= pyplot.legend((line1[0],line2[0],line3[0]),
                          (r'$\phi_b = 0^\circ$',
                           r'$\phi_b = 45^\circ$',
                           r'$\phi_b = 90^\circ$'),
                          loc='lower left',#bbox_to_anchor=(.91,.375),
                          numpoints=8,
                          prop={'size':16},
                          frameon=False)
        l2= pyplot.legend((line1[0],line4[0],line7[0]),
                          (r'$\epsilon(R) = 0.02$',
                           r'$\epsilon(R) = 0.01\,\left(\frac{R}{R_0}\right)^2$',
                           r'$\epsilon(R) = 0.05\,\left(\frac{R}{R_0}\right)^{-3}$'),
                          loc='upper right',#bbox_to_anchor=(.91,.375),
                          numpoints=8,
                          prop={'size':16},
                          frameon=False)
        pyplot.gca().add_artist(l1)
        pyplot.gca().add_artist(l2)
    elif type.lower() == 'bar':
        vlosbar= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR)
        vlosslowbar= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_slow%s.sav' % _HIVRESSTR)
        vlosbarsmallangle= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_angle10%s.sav' % _HIVRESSTR)
        vlosbarlargeangle= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_angle40%s.sav' % _HIVRESSTR)
        vlosbarsmallrolr= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_rolr0.85%s.sav' % _HIVRESSTR)
        vlosbarlargerolr= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_rolr0.95%s.sav' % _HIVRESSTR)
        eres= 19
        xgrid= numpy.linspace((_RCXMIN-8.)/8.+_RCDX/8./2.,
                              (_RCXMAX-8.)/8.-_RCDX/8./2.,
                              eres)
        dx= (xgrid[1]-xgrid[0])*8.
        psdbar= bovy_psd.psd1d(vlosbar,dx,binsize=0.8)
        psdslowbar= bovy_psd.psd1d(vlosslowbar,dx,binsize=0.8)
        psdsbarsmallangle= bovy_psd.psd1d(vlosbarsmallangle,dx,binsize=0.8)
        psdsbarlargeangle= bovy_psd.psd1d(vlosbarlargeangle,dx,binsize=0.8)
        psdsbarsmallrolr= bovy_psd.psd1d(vlosbarsmallrolr,dx,binsize=0.8)
        psdsbarlargerolr= bovy_psd.psd1d(vlosbarlargerolr,dx,binsize=0.8)
        ks= psdbar[0][1:-3]
        scale= 4.*numpy.pi*220.
        bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20)
        line1= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdbar[1][1:-3]),
                                   '-',lw=2.,color='0.65',
                                   semilogx=True,
#                                   xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                                   ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$',
                                   xrange=xrange,
                                   yrange=[0.,11.9],zorder=1)
        line2= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdslowbar[1][1:-3]),
                                   'r-',lw=2.,
                                   overplot=True,zorder=1)
        line3= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarsmallangle[1][1:-3])*0.9,
                                   '-',lw=2.,color='gold',
                                   overplot=True,zorder=1)
        line4= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarlargeangle[1][1:-3])*1.1,
                                   'b-',lw=2.,
                                   overplot=True,zorder=1)
        line5= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarsmallrolr[1][1:-3])*0.9,
                                   'g-',lw=2.,
                                   overplot=True,zorder=1)
        line6= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarlargerolr[1][1:-3]),
                                   'c-',lw=2.,
                                   overplot=True,zorder=1)
        pyplot.annotate(r'$\mathrm{Bar\ perturbation\ (rotating}\ m=2\ \mathrm{mode})$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=20.)
        l1= pyplot.legend((line1[0],line2[0]),
                          (r'$\mathrm{Fast\ bar\ growth}$',
                           r'$\mathrm{Slow\ bar\ growth}$'),
                          loc='upper right',#bbox_to_anchor=(.91,.375),
                          numpoints=8,
                          prop={'size':16},
                          frameon=False)    
        l2= pyplot.legend((line3[0],line4[0],line5[0],line6[0]),
                          (r'$\mathrm{Fast}\ \&\ \mathrm{bar\ angle} = 10^\circ$',
                           r'$\mathrm{Fast}\ \&\ \mathrm{bar\ angle} = 40^\circ$',
                           r'$\mathrm{Fast}\ \&\ R_{\mathrm{OLR}} = 0.85\,R_0$',
                           r'$\mathrm{Fast}\ \&\ R_{\mathrm{OLR}} = 0.95\,R_0$'),
                          loc='lower left',#bbox_to_anchor=(.91,.375),
                          numpoints=8,
                          prop={'size':16},
                          frameon=False)    
        pyplot.gca().add_artist(l1)
        pyplot.gca().add_artist(l2)
    elif type.lower() == 'spiral':
        vlosfid= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR)
        vloslpitch= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-7%s.sav' % _HIVRESSTR)
        vlosdiffgamma= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_gamma0.3%s.sav' % _HIVRESSTR)
        vlosdiffomegas= galpy_simulations.vlos('../sim/spiral_rect_alpha-14%s.sav' % _HIVRESSTR)
        vlosdiffm= galpy_simulations.vlos('../sim/spiral_rect_m4_alpha-14%s.sav' % _HIVRESSTR)
        vlosdiffm2= galpy_simulations.vlos('../sim/spiral_rect_m4_alpha-14_gamma0.4%s.sav' % _HIVRESSTR)
        potscale= 0.85
        eres= 19
        xgrid= numpy.linspace((_RCXMIN-8.)/8.+_RCDX/8./2.,
                              (_RCXMAX-8.)/8.-_RCDX/8./2.,
                              eres)
        dx= (xgrid[1]-xgrid[0])*8.
        psdfid= bovy_psd.psd1d(vlosfid,dx,binsize=0.8)
        psdlpitch= bovy_psd.psd1d(vloslpitch,dx,binsize=0.8)
        psddiffgamma= bovy_psd.psd1d(vlosdiffgamma,dx,binsize=0.8)
        psddiffomegas= bovy_psd.psd1d(vlosdiffomegas,dx,binsize=0.8)
        psddiffm= bovy_psd.psd1d(vlosdiffm,dx,binsize=0.8)
        psddiffm2= bovy_psd.psd1d(vlosdiffm2,dx,binsize=0.8)
        ks= psdfid[0][1:-3]
        scale= 4.*numpy.pi*220.
        bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20)
        line1= bovy_plot.bovy_plot(ks,potscale*scale*numpy.sqrt(psdfid[1][1:-3]),
                                   'k-',lw=2,
                                   semilogx=True,
#                                   xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                                   ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$',
                                   xrange=xrange,
                                   yrange=[0.,11.9],zorder=1)
        potscale= 0.25
        line2= bovy_plot.bovy_plot(ks,potscale*scale*numpy.sqrt(psdlpitch[1][1:-3]),
                                   '-',lw=2.,zorder=1,color='gold',
                                   overplot=True)
        potscale= 0.5
        line3= bovy_plot.bovy_plot(ks,potscale*scale*numpy.sqrt(psddiffgamma[1][1:-3]),
                                   'r-',lw=2.,zorder=1,
                                   overplot=True)
        line4= bovy_plot.bovy_plot(ks,4.*scale*numpy.sqrt(psddiffomegas[1][1:-3]),
                                   'b-',lw=2.,zorder=1,
                                   overplot=True)
        line5= bovy_plot.bovy_plot(ks,10./7.*scale*numpy.sqrt(psddiffm[1][1:-3]),
                                   'g-',lw=2.,zorder=1,
                                   overplot=True)
        line6= bovy_plot.bovy_plot(ks,10./6.*scale*numpy.sqrt(psddiffm2[1][1:-3]),
                                   'c-',lw=2.,zorder=1,
                                   overplot=True)
        pyplot.annotate(r'$\mathrm{Spiral\ perturbation}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=20.)
        l1= pyplot.legend((line1[0],line2[0],line3[0],
                           line4[0],line5[0],line6[0]),
                          (r'$\mathrm{Fiducial\ spiral}$',
                           r'$\mathrm{Pitch\ angle} = 16^\circ$',
                           r'$\gamma = 17^\circ$'),
                          loc='upper right',#bbox_to_anchor=(.91,.375),
                          numpoints=8,
                          prop={'size':16},
                          frameon=False)    
        l2= pyplot.legend((line4[0],line5[0],line6[0]),
                          (r'$\Omega_s = 0.65\,\Omega_0$',
                           r'$\Omega_s = 0.65\,\Omega_0\  \&\ m=4$',
                           r'$\Omega_s = 0.65\,\Omega_0\ \&\ m=4\ \&\ \gamma = 23^\circ$'),
                          loc='lower left',#bbox_to_anchor=(.91,.375),
                          numpoints=8,
                          prop={'size':16},
                          frameon=False) 
        pyplot.gca().add_artist(l1)
        pyplot.gca().add_artist(l2)
    elif type.lower() == 'bird':
        _nSims= 8
        #Read the Bird data
        birdData= numpy.load('../pecvel/dr12_1_5gyr_8pos.npz')
        #Get residuals for all simulations
        dx= _RCDX
        binsize= .8#.765
        scale= 4.*numpy.pi
        tmp= bovy_psd.psd1d(birdData['dVlos1'],dx,binsize=binsize) #just to get the size
        ks= tmp[0][1:-3]
        psds= numpy.zeros((len(tmp[1]),_nSims))
        if True:
            import apogee.tools.read as apread
            import pixelize_sample
            data= apread.rcsample()
            data= data[data['ADDL_LOGG_CUT'] == 1]
            #Cut
            indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
            print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
            data= data[indx]
            #Get residuals
            dx= _RCDX
            pix= pixelize_sample.pixelXY(data,
                                         xmin=_RCXMIN,xmax=_RCXMAX,
                                         ymin=_RCYMIN,ymax=_RCYMAX,
                                         dx=dx,dy=dx)
            resv= pix.plot('VHELIO_AVG',returnz=True,justcalc=True)
            rc_mask= numpy.ones(resv.shape,dtype='bool')
            rc_mask[True-numpy.isnan(resv)]= False       
        if _SUBTRACTERRORS:
            for ii in range(_nSims):
                sim= ii+1
                tmpPsd= bovy_psd.psd1d(birdData['dVlos%i' % sim],
                                       dx,binsize=binsize)[1]
                #Simulations for the noise
                nnoise= _NNOISE
                noisepsd= numpy.empty((nnoise,len(tmpPsd)))
                for jj in range(nnoise):
                    newresv= \
                        numpy.random.normal(size=birdData['dVlos%i' % sim].shape)\
                        *birdData['sig_dVlos%i' % sim].reshape((9,9))\
                        *(True-rc_mask)
#                        *(True-birdData['rc_mask'])
                    noisepsd[jj,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1]
                psds[:,ii]= tmpPsd-numpy.median(noisepsd,axis=0)
         #Calculate median PSD and spread around this
        medPsd= scale*numpy.median(numpy.sqrt(psds),axis=1)[1:-3]
        flucPsd=\
            1.4826*scale*numpy.median(numpy.fabs(numpy.sqrt(psds)[1:-3]
                                                 -numpy.tile(medPsd/scale,
                                                             (psds.shape[1],1)).T),axis=1)
        bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20)
        def my_formatter(x, pos):
            return r'$%g$' % x
        major_formatter = FuncFormatter(my_formatter)
        line1= bovy_plot.bovy_plot(ks,medPsd,
                                   'k-',lw=2,
                                   semilogx=True,
                                   xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                                   ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$',
                                   xrange=xrange,
                                   yrange=[0.,11.9],zorder=1)
        pyplot.gca().xaxis.set_major_formatter(major_formatter)
        goodIndx= True-numpy.isnan(flucPsd)
        pyplot.fill_between(ks[goodIndx],(medPsd-flucPsd)[goodIndx],
                            y2=(medPsd+flucPsd)[goodIndx],
                            color='0.45',zorder=-1)       
        pyplot.annotate(r'$\mathrm{Cosmological\ simulation}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=20.)
        bovy_plot.bovy_text(r'$\mathrm{Median\ and\ range\ from}$'+'\n'
                            +r'$\mathrm{8\ APOGEE\!-\!like\ volumes}$',
                            top_right=True,size=16.)
        bovy_plot.bovy_plot([0.4,0.65],[7.55,10.],'k-',overplot=True)
    #Also plot fiducial
    scale= 4.*numpy.pi*220.
    bovy_plot.bovy_plot(tks,
                        scale*numpy.sqrt(simpsd1d[1][1:-3]),
                        '-',color='0.65',lw=4.,overplot=True,zorder=0)
    if not type.lower() == 'bird':
        nullfmt   = NullFormatter()         # no labels
        pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotfilename)
    return None