def plotKz(pot,plotfilename,surfrs,kzs,kzerrs):
    krs= numpy.linspace(4./_REFR0,10./_REFR0,1001)
    modelkz= numpy.array([-potential.evaluatezforces(kr,1.1/_REFR0,pot)\
                               *bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0) for kr in krs])
    bovy_plot.bovy_print(fig_height=3.5)
    bovy_plot.bovy_plot(krs*_REFR0,modelkz,'-',color='0.6',lw=2.,
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$F_{Z}(R,|Z| = 1.1\,\mathrm{kpc})\ (2\pi G\,M_\odot\,\mathrm{pc}^{-2})$',
                        semilogy=True,
                        yrange=[10.,1000.],
                        xrange=[4.,10.],
                        zorder=0)
    pyplot.errorbar(surfrs,
                    kzs,
                    yerr=kzerrs,
                    marker='o',
                    elinewidth=1.,capsize=3,zorder=1,
                    color='k',linestyle='none')  
    pyplot.errorbar([_REFR0],[69.],yerr=[6.],marker='d',ms=10.,
                    elinewidth=1.,capsize=3,zorder=10,
                    color='0.4',linestyle='none')
    bovy_plot.bovy_end_print(plotfilename)
    #Do an exponential fit to the model Kz and return the scale length
    indx= krs < 9./_REFR0
    p= numpy.polyfit(krs[indx],numpy.log(modelkz[indx]),1)
    return -1./p[0]
Example #2
0
def plot_maphz(plotname):
    # Load the two fit
    with open('../mapfits/tribrokentwoexp.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
    maps= define_rcsample.MAPs()
    plotthisz1= numpy.zeros(len(bf))+numpy.nan
    plotthisz1e= numpy.zeros(len(bf))+numpy.nan
    plotthisz2= numpy.zeros(len(bf))+numpy.nan
    plotthisz2e= numpy.zeros(len(bf))+numpy.nan
    for ii, map in enumerate(maps.map()):
        hzindx= (True-numpy.isnan(samples[ii,4]))\
            *(True-numpy.isnan(samples[ii,5]))\
            *(densprofiles.ilogit(samples[ii,4]) > 0.15)
        tmed= numpy.median(1./samples[ii,1,hzindx])
        terr= numpy.std(1./samples[ii,1,hzindx])
        plotthisz1[ii]= tmed
        plotthisz1e[ii]= terr
        tmed= numpy.median(1./samples[ii,5,hzindx])
        terr= numpy.std(1./samples[ii,5,hzindx])
        plotthisz2[ii]= tmed
        plotthisz2e[ii]= terr
    plotthisz1[plotthisz1e/plotthisz1 > 0.5]= numpy.nan
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(plotthisz2*1000.,plotthisz1*1000.,'ko',
                        xrange=[0.,1200.],yrange=[0.,1200.],
                        xlabel=r'$2^\mathrm{nd}\ \mathrm{scale\ height\,(pc)}$',
                        ylabel=r'$1^\mathrm{st}\ \mathrm{scale\ height\,(pc)}$',zorder=2)
    bovy_plot.bovy_plot([0,1200],[0,1200],'k--',overplot=True,lw=2.)
    pyplot.errorbar(plotthisz2*1000.,plotthisz1*1000.,
                    yerr=plotthisz1e*1000.,
                    marker='o',color='k',ls='none',zorder=1)
    bovy_plot.bovy_end_print(plotname)
    return None
Example #3
0
def plot_rcdistancecomparison(plotfilename):
    # Get the sample
    rcdata = define_rcsample.get_rcsample()
    # Now plot the differece
    bovy_plot.bovy_print()
    levels = special.erf(numpy.arange(1, 3) / numpy.sqrt(2.))
    bovy_plot.scatterplot(
        rcdata['RC_DIST'],
        (rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
        conditional=True,
        levels=levels,
        linestyle='none',
        color='k',
        marker=',',
        xrange=[0., 7.49],
        yrange=[-0.075, 0.075],
        xlabel=r'$M_{K_s}\!-\!\mathrm{based\ distance\,(kpc)}$',
        ylabel=
        r'$\mathrm{Fractional\ difference\ of}\ M_H\ \mathrm{vs.}\ M_{K_s}$',
        onedhistx=True,
        bins=31)
    bovy_plot.bovy_plot([0., 10.], [0., 0.],
                        '--',
                        lw=2.,
                        color='0.75',
                        overplot=True)
    # Plot lowess
    lowess = sm.nonparametric.lowess
    z = lowess((rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
               rcdata['RC_DIST'],
               frac=.3)
    bovy_plot.bovy_plot(z[:, 0], z[:, 1], 'w--', lw=2., overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Example #4
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))
Example #5
0
def plot_age(plotfilename,massfile,omegafile):
    if os.path.exists(massfile):
        savefile= open(massfile,'rb')
        mass= pickle.load(savefile)
        zs= pickle.load(savefile)
        lages= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("file %s has to exist ..." % massfile)
    if os.path.exists(omegafile):
        savefile= open(omegafile,'rb')
        omega= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("file %s has to exist ..." % omegafile)
    agezdist= omega/mass
    pz= numpy.exp(numpy.array([localzdist(z,zsolar=0.017) for z in zs]))
    pz/= numpy.sum(pz)
    page= 1.
    #Tile
    pz= numpy.tile(pz,(len(lages),1)).T
    #Build age pdfs
    postage= page*numpy.nansum(pz*agezdist,axis=0)/numpy.nansum(pz,axis=0)/10.**lages
    postage= postage[lages > numpy.log10(0.8)]
    postage/= numpy.nanmax(postage)
    #Interpolate
    lages= lages[lages > numpy.log10(0.8)]
    postage_spline= interpolate.InterpolatedUnivariateSpline(lages,
                                                             numpy.log(postage),
                                                             k=3)
    plages= numpy.linspace(0.8,10.,1001)
    plpostage= numpy.exp(postage_spline(numpy.log10(plages)))
    plpostage/= numpy.nansum(plpostage)*(plages[1]-plages[0])
    bovy_plot.bovy_print(fig_width=7.)
    yrange=[0.,0.4]
#    yrange=[0.,0.7]
    bovy_plot.bovy_plot(plages,plpostage,
                        'k-',lw=2.,
                        xlabel=r'$\mathrm{Age}\,(\mathrm{Gyr})$',
                        ylabel=r'$p(\mathrm{RC | population\ Age})$',
                        xrange=[0.,10.],
                        yrange=yrange,
                        zorder=10,loglog=False)
    #Baseline
    bovy_plot.bovy_plot(plages,1./9.2*numpy.ones(len(plages)),
                        '-',color='0.4',overplot=True,zorder=3,lw=2.)
    #Fit the dependence
    if _FIT:
        opt= optimize.fmin_powell(chi2,[-1.,0.,0.,0.,-1.,0.,0.,0.],#[-4.,0.,0.25,0.,0.,1.],
                                  args=(numpy.log10(plages),
                                        numpy.log(plpostage)))
        print opt
        bovy_plot.bovy_plot(plages,numpy.exp(_fit_func(opt,numpy.log10(plages))),
                            'r-',overplot=True,zorder=11)
        a= numpy.log10(plages)
        bovy_plot.bovy_plot(plages[a <= 0.23],numpy.exp(polyfit1(a[a <= 0.23])),'b-',overplot=True,zorder=12)
        bovy_plot.bovy_plot(plages[a > 0.23],numpy.exp(polyfit2(a[a > 0.23])),'b-',overplot=True,zorder=12)
    bovy_plot.bovy_end_print(plotfilename)
    return None
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
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 plot_pdfs_l(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                  leading=True,nTrackChunks=_NTRACKCHUNKS,
                  vsun=[0.,30.24*8.,0.],
                  tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                  multi=_NTRACKCHUNKS)
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    #Sample from sdf
    llbd= sdf.sample(n=40000,lb=True)
    tlbd= sdft.sample(n=50000,lb=True)
    b,e= numpy.histogram(llbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    lspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=1.)
    lls= numpy.linspace(t[0],t[-1],_NLS)
    lps= numpy.exp(lspl(lls))
    lps/= numpy.sum(lps)*(lls[1]-lls[0])*2.
    b,e= numpy.histogram(tlbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    tspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=0.5)
    tls= numpy.linspace(t[0],t[-1],_NLS)
    tps= numpy.exp(tspl(tls))
    tps/= numpy.sum(tps)*(tls[1]-tls[0])*2.
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    bovy_plot.bovy_plot(lls,lps,'k-',lw=1.5,
                        xlabel=r'$\mathrm{Galactic\ longitude}\,(\mathrm{deg})$',
                        ylabel=r'$p(l)$',
                        xrange=[65.,250.],
                        yrange=[0.,1.2*numpy.nanmax(numpy.hstack((lps,tps)))])
    bovy_plot.bovy_plot(tls,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    #Transform to (l,b)
    XYZ= bovy_coords.galcenrect_to_XYZ(data[:,1],data[:,3],data[:,2],Xsun=8.)
    lbd= bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2],degree=True)
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    lbd= lbd[indx,:]
    bovy_plot.bovy_hist(lbd[:,0],bins=40,range=[65.,250.],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
Example #9
0
def plot_maprmax(savefilename, plotname):
    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))
    maps = define_rcsample.MAPs()
    plotthis = numpy.zeros(len(bf)) + numpy.nan
    for ii, map in enumerate(maps.map()):
        tmed = numpy.median(
            numpy.exp(samples[ii, 3])[True -
                                      numpy.isnan(numpy.exp(samples[ii, 3]))])
        if tmed < 5.:
            tmed = 0.
        plotthis[ii] = tmed
    bovy_plot.bovy_print()
    maps.plot(plotthis,
              vmin=5.,
              vmax=13.,
              minnstar=15,
              zlabel=r'$R_{\mathrm{peak}}\,(\mathrm{kpc})$',
              shrink=0.68,
              cmap='coolwarm_r')
    # Sequences
    haloc = define_rcsample.highalphalocus()
    bovy_plot.bovy_plot(haloc[:, 0],
                        haloc[:, 1],
                        '-',
                        color='0.75',
                        lw=2.5,
                        overplot=True)
    haloc = define_rcsample.lowalphalocus()
    haloc = haloc[(haloc[:, 0] > -0.55) * (haloc[:, 0] < 0.225)]
    bovy_plot.bovy_plot(haloc[:, 0],
                        haloc[:, 1],
                        '-',
                        color='0.75',
                        lw=2.5,
                        overplot=True)
    # Label
    #t= pyplot.text(-0.51,0.235,r'$\mathrm{single}$',
    #                size=16.,color='w')
    #t.set_bbox(dict(alpha=0.5,color=cm.coolwarm(0.),
    #                edgecolor='none'))
    #t= pyplot.text(-0.475,0.195,r'$\mathrm{exponential}$',
    #                size=16.,color='w')
    t = pyplot.text(-0.625,
                    0.195,
                    r'$R_{\mathrm{peak}} < 5\,\mathrm{kpc}$',
                    size=16.,
                    color='w')
    t.set_bbox(dict(alpha=0.5, color=cm.coolwarm_r(0.), edgecolor='none'))
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotname, dpi=300)
    return None
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)
Example #11
0
 def plotE(self,*args,**kwargs):
     """
     NAME:
        plotE
     PURPOSE:
        plot E(.) along the orbit
     INPUT:
        pot - Potential instance or list of instances in which the orbit was
              integrated
        d1= - plot Ez vs d1: e.g., 't', 'R', 'vR', 'vT', 'phi'
        +bovy_plot.bovy_plot inputs
     OUTPUT:
        figure to output device
     HISTORY:
        2010-07-10 - Written - Bovy (NYU)
     """
     labeldict= {'t':r'$t$','R':r'$R$','vR':r'$v_R$','vT':r'$v_T$',
                 'z':r'$z$','vz':r'$v_z$','phi':r'$\phi$',
                 'x':r'$x$','y':r'$y$','vx':r'$v_x$','vy':r'$v_y$'}
     if not kwargs.has_key('pot'):
         try:
             pot= self._pot
         except AttributeError:
             raise AttributeError("Integrate orbit first or specify pot=")
     else:
         pot= kwargs['pot']
         kwargs.pop('pot')
     if kwargs.has_key('d1'):
         d1= kwargs['d1']
         kwargs.pop('d1')
     else:
         d1= 't'
     self.Es= [evaluateplanarPotentials(self.orbit[ii,0],pot,
                                        phi=self.orbit[ii,3])+
               self.orbit[ii,1]**2./2.+self.orbit[ii,2]**2./2.
               for ii in range(len(self.t))]
     if not kwargs.has_key('xlabel'):
         kwargs['xlabel']= labeldict[d1]
     if not kwargs.has_key('ylabel'):
         kwargs['ylabel']= r'$E$'
     if d1 == 't':
         plot.bovy_plot(nu.array(self.t),nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
     elif d1 == 'R':
         plot.bovy_plot(self.orbit[:,0],nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
     elif d1 == 'vR':
         plot.bovy_plot(self.orbit[:,1],nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
     elif d1 == 'vT':
         plot.bovy_plot(self.orbit[:,2],nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
     elif d1 == 'phi':
         plot.bovy_plot(self.orbit[:,3],nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
Example #12
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
Example #13
0
def plotRbestvsRmean(savefilename,plotfilename):
    #Read surface densities
    #First read the surface densities
    if os.path.exists(savefilename):
        surffile= open(savefilename,'rb')
        surfrs= pickle.load(surffile)
        surfs= pickle.load(surffile)
        surferrs= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    if True:#options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif False:#options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    #Load g orbits
    orbitsfile= 'gOrbitsNew.sav'
    savefile= open(orbitsfile,'rb')
    orbits= pickle.load(savefile)
    savefile.close()
    #Cut to S/N, logg, and EBV
    indx= (orbits.sna > 15.)*(orbits.logga > 4.2)*(orbits.ebv < 0.3)
    orbits= orbits[indx]
    #Load the orbits into the pixel structure
    pix= pixelAfeFeh(orbits,dfeh=0.1,dafe=0.05)
    #Now calculate meanr
    rmean= numpy.zeros_like(surfrs)
    for ii in range(len(surfrs)):
        data= pix(fehs[ii],afes[ii])
        vals= data.densrmean*8.
        if False:#True:
            rmean[ii]= numpy.mean(vals)
        else:
            rmean[ii]= numpy.median(vals)
    #Plot
    indx= numpy.isnan(surfrs)
    indx[50]= True
    indx[57]= True
    indx= True - indx
    surfrs= surfrs[indx]
    rmean= rmean[indx]
    fehs= fehs[indx]
    afes= afes[indx]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(rmean,surfrs,c=afes,marker='o',scatter=True,
                        xlabel=r'$\mathrm{mean\ orbital\ radius\ of\ MAP}\,(\mathrm{kpc})$',
                        ylabel=r'$\mathrm{radius\ at\ which\ MAP\ measures}\ \Sigma_{1.1}\,(\mathrm{kpc})$',
                        xrange=[4.,10.],
                        yrange=[4.,10.],
                        edgecolor='none',zorder=10,s=50.)
    bovy_plot.bovy_plot([4.5,9.],[4.5,9.],'-',color='0.50',overplot=True,lw=1.)
    bovy_plot.bovy_end_print(plotfilename)
Example #14
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
Example #15
0
def plotSkew(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    savefilename= args[0]
    if os.path.exists(savefilename):
        savefile= open(savefilename,'rb')
        skews= pickle.load(savefile)
        gaussskews= pickle.load(savefile)
        type= pickle.load(savefile)
        band= pickle.load(savefile)
        mean= pickle.load(savefile)
        taus= pickle.load(savefile)      
        savefile.close()
    else:
        parser.print_help()
        return
    #Accumulate
    keys= skews.keys()
    allskews= numpy.zeros((len(keys),len(taus)))
    allgaussskews= numpy.zeros((len(keys),gaussskews[keys[0]].shape[0],
                                len(taus)))
    for ii, key in enumerate(keys):
        allskews[ii,:]= -skews[key] #go to regular definition
        allgaussskews[ii,:]= -gaussskews[key]
    #Statistic
    q= 0.99
    statistic= numpy.median
    if not options.indx is None:
        print "indx option not allowed"
        return None
    indx= numpy.all(numpy.isnan(allskews),axis=1)
    allskews= allskews[True-indx,:]
    allgaussskews= allgaussskews[True-indx,:,:]
    #Median
    medianskew= statistic(allskews,axis=0)
    mediangaussskew= statistic(allgaussskews,axis=0)
    #Determine 1-sigma
    sigma= quantile(mediangaussskew,q=q)
    #Plot
    tauindx= 5
    print "Showing tau %f" % (taus[tauindx]*365.25)
    bovy_plot.bovy_print(fig_width=7.)
    bovy_plot.bovy_hist(allskews[:,tauindx],bins=31,
                        color='k',normed=True,histtype='step',
                        xlabel=r'$\mathrm{skew}(\tau = %i\ \mathrm{days})$' % (int(taus[tauindx]*365.25)))
    bovy_plot.bovy_plot([numpy.median(allskews[:,tauindx]),numpy.median(allskews[:,tauindx])],
                        [0.,10.],'k-',overplot=True)
    bovy_plot.bovy_plot([numpy.mean(allskews[:,tauindx]),numpy.mean(allskews[:,tauindx])],
                        [0.,10.],'k--',overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
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
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
Example #18
0
def plot_maphz(plotname):
    # Load the three fits
    with open('../mapfits/tribrokenexpflare.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexp.sav','rb') as savefile:
        bfnf= numpy.array(pickle.load(savefile))
        samplesnf= numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexpfixedflare.sav','rb') as savefile:
        bfff= numpy.array(pickle.load(savefile))
        samplesff= numpy.array(pickle.load(savefile))
    maps= define_rcsample.MAPs()
    plotthisz= numpy.zeros(len(bf))+numpy.nan
    plotthisze= numpy.zeros(len(bf))+numpy.nan
    for ii, map in enumerate(maps.map()):
        if numpy.median(numpy.exp(samples[ii,3])[True-numpy.isnan(numpy.exp(samples[ii,3]))]) < 5.:
            tmed= numpy.median((1./samplesnf[ii,1])[True-numpy.isnan(1./samplesnf[ii,1])])
            terr= numpy.std((1./samplesnf[ii,1])[True-numpy.isnan(1./samplesnf[ii,1])])
        else:
            tmed= numpy.median((1./samplesff[ii,1])[True-numpy.isnan(1./samplesff[ii,1])])
            terr= numpy.std((1./samplesff[ii,1])[True-numpy.isnan(1./samplesff[ii,1])])
        plotthisz[ii]= tmed
        plotthisze[ii]= terr
    plotthisz[plotthisze/plotthisz > 0.2]= numpy.nan
    bovy_plot.bovy_print()
    maps.plot(plotthisz*1000.,
              vmin=200.,vmax=1000.,
              minnstar=15,
              zlabel=r'$h_Z\,(\mathrm{pc})$',
              shrink=0.655)
    # Sequences
    haloc= define_rcsample.highalphalocus()
    bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'-',color='0.75',
                        lw=2.5,overplot=True)
    haloc= define_rcsample.lowalphalocus()
    haloc= haloc[(haloc[:,0] > -0.55)*(haloc[:,0] < 0.225)]
    bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'-',color='0.75',
                        lw=2.5,overplot=True)
    # Label
    #t= pyplot.text(-0.51,0.235,r'$\mathrm{single}$',
    #                size=16.,color='w')
    #t.set_bbox(dict(alpha=0.5,color=cm.coolwarm(0.),
    #                edgecolor='none'))
    #t= pyplot.text(-0.475,0.195,r'$\mathrm{exponential}$',
    #                size=16.,color='w')
    #t.set_bbox(dict(alpha=0.5,color=cm.coolwarm(0.),
    #                edgecolor='none'))
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotname,dpi=300)
    return None
Example #19
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)
Example #20
0
def plot_seguem10(plotfilename):
    savefile= open('../potential-fits/fitall_10ksamples_derived_whalomass.sav','rb')
    data= pickle.load(savefile)
    savefile.close()
    mh= numpy.array([x[8] for x in data])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(mh,range=[0.,10.],
                        bins=71,histtype='step',color='k',
                        xlabel=r'$M_{\mathrm{halo}}(<10\,\mathrm{kpc})\,(10^{10}\,M_\odot)$',
                        normed=True)
    xs= numpy.linspace(0.,10.,1001)
    bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi*numpy.var(mh[True-numpy.isnan(mh)]))*numpy.exp(-0.5*(xs-numpy.mean(mh[True-numpy.isnan(mh)]))**2./numpy.var(mh[True-numpy.isnan(mh)])),
                        'k-',lw=2,overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
Example #21
0
 def _determine_ngauss(self,fitlogg=False,loofrac=0.1):
     """Determine the optimal number of Gaussians"""
     ngauss_s= range(1,15)
     #First do loo
     perm= numpy.random.permutation(len(self._weights))
     tperm= perm[0:int(numpy.ceil(loofrac*len(self._weights)))]
     tsample= self._sample[tperm,:]
     tweights= self._weights[tperm]
     tloggs= self._loggs[tperm]
     #loo sample
     lperm= perm[int(numpy.ceil(loofrac*len(self._weights))):len(self._weights)]
     lsample= self._sample[lperm,:]
     lweights= self._weights[lperm]
     lloggs= self._loggs[lperm]
     #!!LOO!!
     loos= numpy.zeros(len(ngauss_s))
     xamps= []
     xmeans= []
     xcovars= []
     for ii, ngauss in enumerate(ngauss_s):
         print ngauss
         #First run XD
         l, xamp, xmean, xcovar= self._run_xd(ngauss=ngauss,fitlogg=fitlogg,
                                              _sample=tsample,
                                              _weights=tweights,
                                              _loggs=tloggs)
         tl, xamp, xmean, xcovar= self._run_xd(ngauss=ngauss,
                                               fitlogg=fitlogg,
                                               likeonly=True,
                                              _sample=lsample,
                                              _weights=lweights,
                                              _loggs=lloggs,
                                               _xamp=xamp,
                                               _xmean=xmean,
                                               _xcovar=xcovar)
         loos[ii]= tl*len(lweights)
         xamps.append(xamp)
         xmeans.append(xmean)
         xcovars.append(xcovar)
     bovy_plot.bovy_plot(ngauss_s,loos,'ko',
                         yrange=[0.9*numpy.amin(loos),1.1*numpy.amax(loos)],
                         xlabel=r'$\#\ \mathrm{Gaussian\ components}$',
                         ylabel=r'$\mathrm{loo\ log\ likelihood}$')
     indx= numpy.argmax(loos)
     print ngauss_s[indx]
     return (ngauss_s[numpy.argmax(loos)],
             xamps[indx],
             xmeans[indx],
             xcovars[indx])
Example #22
0
def plotDensz(data,sf,xrange=[0.,2.],normed=True,overplot=False,bins=20,
              log=True,dR=1.,db=None,noweights=False,color='k'):
    """
    NAME:
       plotDensz
    PURPOSE:
       Plot a 'smart' representation of the data
    INPUT:
       data - data structure (recarray)
       sf - segueSelect instance with selection function
       xrange= the x range
       normed= if False, don't normalize (*not* what you want)
       bins= number of bins
       log= if False, plot density, otherwise plot log density
       dR= range/2. in Galactocentric radius to consider
       db= range/2. from pole to consider
       noweights= if True, don't reweight
       color= color to plot
    OUTPUT:
       plot to output
    HISTORY:
       2011-07-13 - Written - Bovy (NYU)
    """
    if not overplot:
        bovy_plot.bovy_print()
    dx= (xrange[1]-xrange[0])/(bins+1)
    xs= numpy.linspace(xrange[0]+dx,xrange[1]-dx,bins)
    hist= numpy.zeros(bins)
    R= ((8.-data.xc)**2.+data.yc**2.)**(0.5)
    for ii in range(len(data.ra)):
        if math.fabs(R[ii] - 8.) > dR: continue
        if not db is None \
                and data[ii].b < (90.-db) and data[ii].b > (-90.+db): continue
        if noweights:
            thissf= 1.
        else:
            #Get the weight
            thissf= sf(data[ii].plate)
        jac= data[ii].dist**2. #*numpy.fabs(numpy.cos(data[ii].b*_DEGTORAD))
        jac/= numpy.fabs(numpy.sin(data[ii].b*_DEGTORAD))
        jac*= numpy.exp(-(R[ii]-8.)/2.75)
        #bin number
        thisbin= int(math.floor((numpy.fabs(data[ii].zc-xrange[0]))/dx))
        if thisbin > (bins-1): continue
        hist[thisbin]+= 1./jac/thissf
    #Normalize
    hist/= numpy.sum(hist)*dx
    if log: hist= numpy.log(hist)
    bovy_plot.bovy_plot(xs,hist,color+'D',overplot=overplot)
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
Example #24
0
 def plot_pdf(self, jk, **kwargs):
     """
     NAME:
        plot_pdf
     PURPOSE:
        plot the conditioned PDF
     INPUT:
        jk - J-Ks
        +bovy_plot.bovy_plot kwargs
     OUTPUT:
        plot to output
     HISTORY:
        2012-11-09 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     xs, lnpdf = self.calc_pdf(jk)
     if self._band == 'J':
         xlabel = r'$M_J$'
     elif self._band == 'H':
         xlabel = r'$M_H$'
     elif self._band == 'K':
         xlabel = r'$M_K$'
     elif self._band == 'Ks':
         xlabel = r'$M_{K_s}$'
     xlim = [self._hmax, self._hmin]
     return bovy_plot.bovy_plot(
         xs,
         numpy.exp(lnpdf),
         'k-',
         xrange=xlim,
         yrange=[0., 1.1 * numpy.amax(numpy.exp(lnpdf))],
         xlabel=xlabel,
         **kwargs)
Example #25
0
def plotRotcurve(Pot, *args, **kwargs):
    """
    NAME:
       plotRotcurve
    PURPOSE:
       plot the rotation curve for this potential (in the z=0 plane for
       non-spherical potentials)
    INPUT:
       Pot - Potential or list of Potential instances

       Rrange - 

       grid - grid in R

       savefilename - save to or restore from this savefile (pickle)
       +bovy_plot.bovy_plot args and kwargs
    OUTPUT:
       plot to output device
    HISTORY:
       2010-07-10 - Written - Bovy (NYU)
    """
    if kwargs.has_key('Rrange'):
        Rrange = kwargs['Rrange']
        kwargs.pop('Rrange')
    else:
        Rrange = [0.01, 5.]
    if kwargs.has_key('grid'):
        grid = kwargs['grid']
        kwargs.pop('grid')
    else:
        grid = 1001
    if kwargs.has_key('savefilename'):
        savefilename = kwargs['savefilename']
        kwargs.pop('savefilename')
    else:
        savefilename = None
    if not savefilename == None and os.path.exists(savefilename):
        print "Restoring savefile " + savefilename + " ..."
        savefile = open(savefilename, 'rb')
        rotcurve = pickle.load(savefile)
        Rs = pickle.load(savefile)
        savefile.close()
    else:
        Rs = nu.linspace(Rrange[0], Rrange[1], grid)
        rotcurve = calcRotcurve(Pot, Rs)
        if not savefilename == None:
            print "Writing savefile " + savefilename + " ..."
            savefile = open(savefilename, 'wb')
            pickle.dump(rotcurve, savefile)
            pickle.dump(Rs, savefile)
            savefile.close()
    if not kwargs.has_key('xlabel'):
        kwargs['xlabel'] = r"$R/R_0$"
    if not kwargs.has_key('ylabel'):
        kwargs['ylabel'] = r"$v_c(R)/v_c(R_0)$"
    if not kwargs.has_key('xrange'):
        kwargs['xrange'] = Rrange
    if not kwargs.has_key('yrange'):
        kwargs['yrange'] = [0., 1.2 * nu.amax(rotcurve)]
    return plot.bovy_plot(Rs, rotcurve, *args, **kwargs)
Example #26
0
 def plotData(self,l,b,*args,**kwargs):
     """
     NAME:
        plotData
     PURPOSE:
        plot the Marshall et al. (2006) extinction values 
        along a given line of sight as a function of 
        distance
     INPUT:
        l,b - Galactic longitude and latitude (degree)
        bovy_plot.bovy_plot args and kwargs
     OUTPUT:
        plot to output device
     HISTORY:
        2013-12-15 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise NotImplementedError("galpy.util.bovy_plot could not be loaded, so there is no plotting; might have to install galpy (http://github.com/jobovy/galpy) for plotting")
     #First get the data
     tdata= self.lbData(l,b)
     #Filter
     if self._filter is None:
         filterFac= 1./aebv('2MASS Ks',sf10=self._sf10)
     else:
         filterFac= 1./aebv('2MASS Ks',sf10=self._sf10)\
             *aebv(self._filter,sf10=self._sf10)
     #Plot
     out= bovy_plot.bovy_plot(tdata['dist'],tdata['aks']*filterFac,
                         *args,**kwargs)
     #uncertainties
     pyplot.errorbar(tdata['dist'],tdata['aks']*filterFac,
                     xerr=tdata['e_dist'],
                     yerr=tdata['e_aks']*filterFac,
                     ls='none',marker=None,color='k')
     return out
Example #27
0
 def plot_pdf(self,jk,**kwargs):
     """
     NAME:
        plot_pdf
     PURPOSE:
        plot the conditioned PDF
     INPUT:
        jk - J-Ks
        +bovy_plot.bovy_plot kwargs
     OUTPUT:
        plot to output
     HISTORY:
        2012-11-09 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     xs, lnpdf= self.calc_pdf(jk)
     if self._band == 'J':
         xlabel= r'$M_J$'
     elif self._band == 'H':
         xlabel= r'$M_H$'
     elif self._band == 'K':
         xlabel= r'$M_K$'
     elif self._band == 'Ks':
         xlabel= r'$M_{K_s}$'
     xlim=[self._hmax,self._hmin]
     return bovy_plot.bovy_plot(xs,numpy.exp(lnpdf),'k-',
                                xrange=xlim,
                                yrange=[0.,
                                        1.1*numpy.amax(numpy.exp(lnpdf))],
                                xlabel=xlabel,**kwargs)       
Example #28
0
 def plot_samples(self):
     """
     NAME:
        plot_samples
     PURPOSE:
        plot the samples that the histogramming is based on 
     INPUT:
     OUTPUT:
        plot to output device
     HISTORY:
        2012-06-15 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("'galpy.util.bovy_plot' plotting package not found")
     if self._band == 'J':
         ylabel= r'$M_J$'
     elif self._band == 'H':
         ylabel= r'$M_H$'
     elif self._band == 'K':
         ylabel= r'$M_K$'
     elif self._band == 'Ks':
         ylabel= r'$M_{K_s}$'
     ylim=[self._hmax,self._hmin]
     return bovy_plot.bovy_plot(self._sample[:,0],self._sample[:,1],
                                xrange=[self._jkmin,self._jkmax],
                                yrange=ylim,
                                xlabel=r'$(J-K_s)_0$',
                                ylabel=ylabel,
                                scatter=True,
                                c=self._weights,
                                edgecolors='none',
                                s=numpy.ones(len(self._weights))*10.,
                                alpha=0.5,
                                marker='o',
                                colorbar=True)
def plotEscapecurve(Pot,*args,**kwargs):
    """
    NAME:

       plotEscapecurve

    PURPOSE:

       plot the escape velocity curve for this potential (in the z=0 plane for
       non-spherical potentials)

    INPUT:

       Pot - Potential or list of Potential instances

       Rrange= Range in R to consider

       grid= grid in R

       savefilename= save to or restore from this savefile (pickle)

       +bovy_plot.bovy_plot args and kwargs

    OUTPUT:

       plot to output device

    HISTORY:

       2010-08-08 - Written - Bovy (NYU)

    """
    Rrange= kwargs.pop('Rrange',[0.01,5.])
    grid= kwargs.pop('grid',1001)
    savefilename= kwargs.pop('savefilename',None)
    if not savefilename == None and os.path.exists(savefilename):
        print("Restoring savefile "+savefilename+" ...")
        savefile= open(savefilename,'rb')
        esccurve= pickle.load(savefile)
        Rs= pickle.load(savefile)
        savefile.close()
    else:
        Rs= nu.linspace(Rrange[0],Rrange[1],grid)
        esccurve= calcEscapecurve(Pot,Rs)
        if not savefilename == None:
            print("Writing savefile "+savefilename+" ...")
            savefile= open(savefilename,'wb')
            pickle.dump(esccurve,savefile)
            pickle.dump(Rs,savefile)
            savefile.close()
    if not 'xlabel' in kwargs:
        kwargs['xlabel']= r"$R/R_0$"
    if not 'ylabel' in kwargs:
        kwargs['ylabel']= r"$v_e(R)/v_c(R_0)$"
    if not 'xrange' in kwargs:
        kwargs['xrange']= Rrange
    if not 'yrange' in kwargs:
        kwargs['yrange']= [0.,1.2*nu.amax(esccurve)]
    return plot.bovy_plot(Rs,esccurve,*args,
                          **kwargs)
Example #30
0
 def plotData(self,l,b,*args,**kwargs):
     """
     NAME:
        plotData
     PURPOSE:
        plot the Marshall et al. (2006) extinction values 
        along a given line of sight as a function of 
        distance
     INPUT:
        l,b - Galactic longitude and latitude (degree)
        bovy_plot.bovy_plot args and kwargs
     OUTPUT:
        plot to output device
     HISTORY:
        2013-12-15 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise NotImplementedError("galpy.util.bovy_plot could not be loaded, so there is no plotting; might have to install galpy (http://github.com/jobovy/galpy) for plotting")
     #First get the data
     tdata= self.lbData(l,b)
     #Filter
     if self._filter is None:
         filterFac= 1./aebv('2MASS Ks',sf10=self._sf10)
     else:
         filterFac= 1./aebv('2MASS Ks',sf10=self._sf10)\
             *aebv(self._filter,sf10=self._sf10)
     #Plot
     out= bovy_plot.bovy_plot(tdata['dist'],tdata['aks']*filterFac,
                         *args,**kwargs)
     #uncertainties
     pyplot.errorbar(tdata['dist'],tdata['aks']*filterFac,
                     xerr=tdata['e_dist'],
                     yerr=tdata['e_aks']*filterFac,
                     ls='none',marker=None,color='k')
     return out
Example #31
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
Example #32
0
def plotlinearPotentials(Pot,
                         t=0.,
                         min=-15.,
                         max=15,
                         ns=21,
                         savefilename=None):
    """
    NAME:

       plotlinearPotentials

    PURPOSE:

       plot a combination of potentials

    INPUT:

       t - time to evaluate potential at

       min - minimum x

       max - maximum x

       ns - grid in x

       savefilename - save to or restore from this savefile (pickle)

    OUTPUT:

       plot to output device

    HISTORY:

       2010-07-13 - Written - Bovy (NYU)

    """
    Pot = flatten(Pot)
    if not savefilename == None and os.path.exists(savefilename):
        print("Restoring savefile " + savefilename + " ...")
        savefile = open(savefilename, 'rb')
        potx = pickle.load(savefile)
        xs = pickle.load(savefile)
        savefile.close()
    else:
        xs = nu.linspace(min, max, ns)
        potx = nu.zeros(ns)
        for ii in range(ns):
            potx[ii] = evaluatelinearPotentials(Pot, xs[ii], t=t)
        if not savefilename == None:
            print("Writing savefile " + savefilename + " ...")
            savefile = open(savefilename, 'wb')
            pickle.dump(potx, savefile)
            pickle.dump(xs, savefile)
            savefile.close()
    return plot.bovy_plot(xs,
                          potx,
                          xlabel=r"$x/x_0$",
                          ylabel=r"$\Phi(x)$",
                          xrange=[min, max])
Example #33
0
 def plot(self,y,log=None,**kwargs):
     """
     NAME:
        plot
     PURPOSE:
        plot the structure of the model atmosphere
     INPUT:
        y= Atmospheric parameter to plot vs. Rossland optical depth
        galpy.util.bovy_plot plotting kwargs
     OUTPUT:
        plot to output device
     HISTORY:
        2015-03-20 - Written - Bovy (IAS)
     """
     # Load atmospheric quantity
     if y.upper() == 'RHOX':
         indx= 0
         ylabel= r'$\rho\,x$'
         log= True
     elif y.upper() == 'T':
         indx= 1
         ylabel= r'$T\,(\mathrm{K})$'
     elif y.upper() == 'P':
         indx= 2
         ylabel= r'$P\,(\mathrm{dyne\,cm}^{-2})$'
         log= True
     elif y.upper() == 'XNE':
         indx= 3
         ylabel= r'$\mathrm{XNE}$'
         log= True
     elif y.upper() == 'ABROSS':
         indx= 4
         ylabel= r'$\kappa_{\mathrm{Rossland}}$'
         log= True
     elif y.upper() == 'ACCRAD':
         indx= 5 
         ylabel= r'$\mathrm{ACCRAD}$'
         log= True
     elif y.upper() == 'VTURB':
         indx= 6
         ylabel= r'$v_{\mathrm{turb}}\,(\mathrm{cm\,s}^{-1})$'
     elif y.upper() == 'FLXCNV':
         indx= 7
         ylabel= r'$\mathrm{FLXCONV}$'
     elif y.upper() == 'VCONV':
         indx= 8
         ylabel= r'$\mathrm{VCONV}$'
     elif y.upper() == 'VELSND':
         indx= 9
         ylabel= r'$\mathrm{VELSND}$'
     y= self._deck[:,indx]
     if log:
         y= numpy.log10(y)
         ylabel= r'$\log_{10}$'+ylabel
     x= numpy.log10(self.rosslandtau)
     return bovy_plot.bovy_plot(x,y,
                                xlabel=r'$\log_{10}\tau_{\mathrm{Rossland}}$',
                                ylabel=ylabel,
                                **kwargs)
Example #34
0
def plotEscapecurve(Pot, *args, **kwargs):
    """
    NAME:

       plotEscapecurve

    PURPOSE:

       plot the escape velocity curve for this potential (in the z=0 plane for
       non-spherical potentials)

    INPUT:

       Pot - Potential or list of Potential instances

       Rrange= Range in R to consider

       grid= grid in R

       savefilename= save to or restore from this savefile (pickle)

       +bovy_plot.bovy_plot args and kwargs

    OUTPUT:

       plot to output device

    HISTORY:

       2010-08-08 - Written - Bovy (NYU)

    """
    Rrange = kwargs.pop('Rrange', [0.01, 5.])
    grid = kwargs.pop('grid', 1001)
    savefilename = kwargs.pop('savefilename', None)
    if not savefilename == None and os.path.exists(savefilename):
        print("Restoring savefile " + savefilename + " ...")
        savefile = open(savefilename, 'rb')
        esccurve = pickle.load(savefile)
        Rs = pickle.load(savefile)
        savefile.close()
    else:
        Rs = nu.linspace(Rrange[0], Rrange[1], grid)
        esccurve = calcEscapecurve(Pot, Rs)
        if not savefilename == None:
            print("Writing savefile " + savefilename + " ...")
            savefile = open(savefilename, 'wb')
            pickle.dump(esccurve, savefile)
            pickle.dump(Rs, savefile)
            savefile.close()
    if not 'xlabel' in kwargs:
        kwargs['xlabel'] = r"$R/R_0$"
    if not 'ylabel' in kwargs:
        kwargs['ylabel'] = r"$v_e(R)/v_c(R_0)$"
    if not 'xrange' in kwargs:
        kwargs['xrange'] = Rrange
    if not 'yrange' in kwargs:
        kwargs['yrange'] = [0., 1.2 * nu.amax(esccurve)]
    return plot.bovy_plot(Rs, esccurve, *args, **kwargs)
Example #35
0
def _overplot_model(data,xrange=None,yrange=None,fehrange=None,
                    colorrange=None):
    #Load model distributions
    #FeH
    fehdist= DistSpline(*numpy.histogram(data.feh,bins=11,range=fehrange),
                         xrange=fehrange)
    nfehs= 1001
    fehs= numpy.linspace(yrange[0],yrange[1],nfehs)
    mfehs= numpy.zeros(nfehs)
    for ii in range(nfehs):
        mfehs[ii]= fehdist(fehs[ii])
    mfehs/= numpy.nansum(mfehs)*(fehs[1]-fehs[0])    
    #Color
    cdist= DistSpline(*numpy.histogram(data.dered_g-data.dered_r,
                                       bins=9,range=colorrange),
                       xrange=colorrange)
    ncs= 1001
    cs= numpy.linspace(xrange[0],xrange[1],ncs)
    mcs= numpy.zeros(nfehs)
    for ii in range(nfehs):
        mcs[ii]= cdist(cs[ii])
    mcs/= numpy.nansum(mcs)*(cs[1]-cs[0])    
    #Overplot model FeH
    from matplotlib.ticker import NullFormatter
    fig= pyplot.gcf()
    nullfmt   = NullFormatter()         # no labels
    # definitions for the axes
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left+width
    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]
    axScatter = pyplot.axes(rect_scatter)
    axHistx = pyplot.axes(rect_histx)
    axHisty = pyplot.axes(rect_histy)
    # no labels
    axHistx.xaxis.set_major_formatter(nullfmt)
    axHistx.yaxis.set_major_formatter(nullfmt)
    axHisty.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)
    fig.sca(axHisty)
    bovy_plot.bovy_plot(mfehs,fehs,'k-',overplot=True)
    fig.sca(axHistx)
    bovy_plot.bovy_plot(cs,mcs,'k-',overplot=True)
    return None
Example #36
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
def plot_pdfs_x(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    txs= numpy.linspace(3.,12.4,_NLS)
    tlogps= multi.parallel_map((lambda x: sdft.callMarg([txs[x]/8.,None,None,None,None,None],
                                                        interp=True,ngl=_NGL,
                                                        nsigma=3)),
                              range(_NLS),
                              numcores=numpy.amin([_NLS,
                                                   multiprocessing.cpu_count()]))
    tlogps= numpy.array(tlogps)
    tlogps[numpy.isnan(tlogps)]= -100000000000000000.
    tps= numpy.exp(tlogps-logsumexp(tlogps))
    tps/= numpy.nansum(tps)*(txs[1]-txs[0])
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(txs,tps,'k-',lw=1.5,
                        xlabel=r'$X\,(\mathrm{kpc})$',
                        ylabel=r'$p(X)$',
                        xrange=[3.,12.4],
                        yrange=[0.,1.2*numpy.nanmax(tps)])
    bovy_plot.bovy_plot(txs,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= thetar-numpy.pi < -(5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    data= data[indx,:]
    bovy_plot.bovy_hist(data[:,1],bins=20,range=[3.,12.4],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
Example #38
0
def plot_poincare(o1,o2,plotfilename):
    ts= numpy.linspace(0.,1000.,20001)
    o1.integrate(ts,MWPotential2014)
    o2.integrate(ts,MWPotential2014)
    #First orbit
    Rs= o1.R(ts); zs= o1.z(ts); vRs= o1.vR(ts)
    sect1Rs, sect1vRs= surface_section(Rs,zs,vRs)
    #Second orbit
    Rs= o2.R(ts); zs= o2.z(ts); vRs= o2.vR(ts)
    sect2Rs, sect2vRs= surface_section(Rs,zs,vRs)
    bovy_plot.bovy_print(fig_height=3.5)
    bovy_plot.bovy_plot(sect1Rs,sect1vRs,'bo',mec='none',
                        xlabel=r'$R$',ylabel=r'$v_R$',
                        xrange=[0.3,1.],
                        yrange=[-0.69,0.69])
    bovy_plot.bovy_plot(sect2Rs,sect2vRs,'yo',mec='none',overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Example #39
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)
Example #40
0
    def scatterplot(self,d1,d2,*args,**kwargs):
        """
        NAME:
        
           scatterplot

        PURPOSE:

           make a scatterplot of the data

        INPUT:

           d1, d2 - x and y dimension to plot

           hoggscatter - if True, hogg_scatterplot

           +bovy_plot.plot or bovy_plot.scatterplot args and kwargs

        OUTPUT:

           plot to output device

        HISTORY:

           2010-08-09 - Written - Bovy (NYU)

        """
        if kwargs.has_key('hoggscatter'):
            hoggscatter= kwargs['hoggscatter']
            kwargs.pop('hoggscatter')
        else:
            hoggscatter= False
        if not kwargs.has_key('xlabel'):
            kwargs['xlabel']= str(d1)
        if not kwargs.has_key('ylabel'):
            kwargs['ylabel']= str(d2)
        if hoggscatter:
            if hasattr(self,'weight'):
                kwargs['weights']= self.weight
            bovy_plot.scatterplot(self.a[:,d1],self.a[:,d2],
                                  *args,**kwargs)
        else:
            bovy_plot.bovy_plot(self.a[:,d1],self.a[:,d2],
                                *args,**kwargs)
Example #41
0
 def plot_age_pdf(self, fehdist='casagrande', **kwargs):
     """
     NAME:
        plot_age_pdf
     PURPOSE:
        plot the age PDF for a uniform SFH for a given metallicity 
        distribution
     INPUT:
        fehdist= either:
           1) a single metallicity 
           2) 'casagrande': local metallicity distribution following Casagrande et al. (2011)
           3) a function giving
         bovy_plot.bovy_plot **kwargs
     OUTPUT:
        bovy_plot.bovy_plot output
     HISTORY:
        2014-02-27 - Written in this form - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     page = self.calc_age_pdf(fehdist)
     plages = numpy.linspace(0.8, 10., 1001)
     plpostage = page(plages)
     plpostage /= numpy.nansum(plpostage) * (plages[1] - plages[0])
     kwargs['color'] = kwargs.get('color', "k")
     out = bovy_plot.bovy_plot(plages,
                               plpostage,
                               '-',
                               lw=2.,
                               xlabel=r'$\mathrm{Age}\,(\mathrm{Gyr})$',
                               ylabel=r'$p(\mathrm{RC | population\ Age})$',
                               xrange=[0., 10.],
                               yrange=[0., 0.4],
                               **kwargs)
     #Baseline
     bovy_plot.bovy_plot(plages,
                         1. / 9.2 * numpy.ones(len(plages)),
                         '-',
                         color='0.4',
                         overplot=True,
                         zorder=3,
                         lw=2.)
     return out
Example #42
0
def plot_maprmax(savefilename,plotname):
    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))
    maps= define_rcsample.MAPs()
    plotthis= numpy.zeros(len(bf))+numpy.nan
    for ii, map in enumerate(maps.map()):
        tmed= numpy.median(numpy.exp(samples[ii,3])[True-numpy.isnan(numpy.exp(samples[ii,3]))])
        if tmed < 5.:
            tmed= 0.
        plotthis[ii]= tmed
    bovy_plot.bovy_print()
    maps.plot(plotthis,
              vmin=5.,vmax=13.,
              minnstar=15,
              zlabel=r'$R_{\mathrm{peak}}\,(\mathrm{kpc})$',
              shrink=0.68,cmap='coolwarm_r')
    # Sequences
    haloc= define_rcsample.highalphalocus()
    bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'-',color='0.75',
                        lw=2.5,overplot=True)
    haloc= define_rcsample.lowalphalocus()
    haloc= haloc[(haloc[:,0] > -0.55)*(haloc[:,0] < 0.225)]
    bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'-',color='0.75',
                        lw=2.5,overplot=True)
    # Label
    #t= pyplot.text(-0.51,0.235,r'$\mathrm{single}$',
    #                size=16.,color='w')
    #t.set_bbox(dict(alpha=0.5,color=cm.coolwarm(0.),
    #                edgecolor='none'))
    #t= pyplot.text(-0.475,0.195,r'$\mathrm{exponential}$',
    #                size=16.,color='w')
    t= pyplot.text(-0.625,0.195,r'$R_{\mathrm{peak}} < 5\,\mathrm{kpc}$',
                    size=16.,color='w')
    t.set_bbox(dict(alpha=0.5,color=cm.coolwarm_r(0.),
                    edgecolor='none'))
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotname,dpi=300)
    return None
Example #43
0
def plot_maphz(plotname):
    # Load the two fit
    with open('../mapfits/tribrokentwoexp.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples = numpy.array(pickle.load(savefile))
    maps = define_rcsample.MAPs()
    plotthisz1 = numpy.zeros(len(bf)) + numpy.nan
    plotthisz1e = numpy.zeros(len(bf)) + numpy.nan
    plotthisz2 = numpy.zeros(len(bf)) + numpy.nan
    plotthisz2e = numpy.zeros(len(bf)) + numpy.nan
    for ii, map in enumerate(maps.map()):
        hzindx= (True-numpy.isnan(samples[ii,4]))\
            *(True-numpy.isnan(samples[ii,5]))\
            *(densprofiles.ilogit(samples[ii,4]) > 0.15)
        tmed = numpy.median(1. / samples[ii, 1, hzindx])
        terr = numpy.std(1. / samples[ii, 1, hzindx])
        plotthisz1[ii] = tmed
        plotthisz1e[ii] = terr
        tmed = numpy.median(1. / samples[ii, 5, hzindx])
        terr = numpy.std(1. / samples[ii, 5, hzindx])
        plotthisz2[ii] = tmed
        plotthisz2e[ii] = terr
    plotthisz1[plotthisz1e / plotthisz1 > 0.5] = numpy.nan
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(
        plotthisz2 * 1000.,
        plotthisz1 * 1000.,
        'ko',
        xrange=[0., 1200.],
        yrange=[0., 1200.],
        xlabel=r'$2^\mathrm{nd}\ \mathrm{scale\ height\,(pc)}$',
        ylabel=r'$1^\mathrm{st}\ \mathrm{scale\ height\,(pc)}$',
        zorder=2)
    bovy_plot.bovy_plot([0, 1200], [0, 1200], 'k--', overplot=True, lw=2.)
    pyplot.errorbar(plotthisz2 * 1000.,
                    plotthisz1 * 1000.,
                    yerr=plotthisz1e * 1000.,
                    marker='o',
                    color='k',
                    ls='none',
                    zorder=1)
    bovy_plot.bovy_end_print(plotname)
    return None
Example #44
0
 def plotJacobi(self, *args, **kwargs):
     """
     NAME:
        plotJacobi
     PURPOSE:
        plot Jacobi integratl(.) along the orbit
     INPUT:
        OmegaP= pattern speed
        pot= Potential instance or list of instances in which the orbit was
              integrated
        d1= - plot Jacobi vs d1: e.g., 't', 'R', 'vR', 'vT'
        +bovy_plot.bovy_plot inputs
     OUTPUT:
        figure to output device
     HISTORY:
        2011-10-09 - Written - Bovy (IAS)
     """
     labeldict = {
         't': r'$t$',
         'R': r'$R$',
         'vR': r'$v_R$',
         'vT': r'$v_T$',
         'z': r'$z$',
         'vz': r'$v_z$',
         'phi': r'$\phi$',
         'x': r'$x$',
         'y': r'$y$',
         'vx': r'$v_x$',
         'vy': r'$v_y$'
     }
     Js = self.Jacobi(self.t, **kwargs)
     if kwargs.has_key('OmegaP'): kwargs.pop('OmegaP')
     if kwargs.has_key('pot'): kwargs.pop('pot')
     if kwargs.has_key('d1'):
         d1 = kwargs['d1']
         kwargs.pop('d1')
     else:
         d1 = 't'
     if not kwargs.has_key('xlabel'):
         kwargs['xlabel'] = labeldict[d1]
     if not kwargs.has_key('ylabel'):
         kwargs['ylabel'] = r'$E-\Omega_p\,L$'
     if d1 == 't':
         plot.bovy_plot(nu.array(self.t), Js / Js[0], *args, **kwargs)
     elif d1 == 'R':
         plot.bovy_plot(self.orbit[:, 0], Js / Js[0], *args, **kwargs)
     elif d1 == 'vR':
         plot.bovy_plot(self.orbit[:, 1], Js / Js[0], *args, **kwargs)
     elif d1 == 'vT':
         plot.bovy_plot(self.orbit[:, 2], Js / Js[0], *args, **kwargs)
def plotTerm(
    pot: PotentialType,
    termdata: Sequence,
    ro: float = REFR0,
    vo: float = REFV0,
) -> None:
    """Plot Terminal Velocity.

    Parameters
    ----------
    pot: potential
    termdata: tuple
        cl_glon, cl_vterm, cl_corr, mc_glon, mc_vterm, mc_corr

    Other Parameters
    ----------------
    ro: float
    vo: float

    """
    mglons = np.linspace(-90.0, -20.0, 1001)
    pglons = np.linspace(20.0, 90.0, 1001)
    mterms = np.array([potential.vterm(pot, mgl) * vo for mgl in mglons])
    pterms = np.array([potential.vterm(pot, pgl) * vo for pgl in pglons])
    bovy_plot.bovy_plot(
        mglons,
        mterms,
        "-",
        color="0.6",
        lw=2.0,
        zorder=0,
        xlabel=r"$\mathrm{Galactic\ longitude\, (deg)}$",
        ylabel=r"$\mathrm{Terminal\ velocity}\, (\mathrm{km\,s}^{-1})$",
        xrange=[-100.0, 100.0],
        yrange=[-150.0, 150.0],
        gcf=True,
    )
    bovy_plot.bovy_plot(pglons,
                        pterms,
                        "-",
                        color="0.6",
                        lw=2.0,
                        zorder=0,
                        overplot=True)
    cl_glon, cl_vterm, cl_corr, mc_glon, mc_vterm, mc_corr = termdata
    bovy_plot.bovy_plot(cl_glon, cl_vterm, "ko", overplot=True)
    bovy_plot.bovy_plot(mc_glon - 360.0, mc_vterm, "ko", overplot=True)

    return None
Example #46
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
def plotTerm(pot,termdata,_REFR0,_REFV0):
    mglons= numpy.linspace(-90.,-20.,1001)
    pglons= numpy.linspace(20.,90.,1001)
    mterms= numpy.array([potential.vterm(pot,mgl)*_REFV0 for mgl in mglons])
    pterms= numpy.array([potential.vterm(pot,pgl)*_REFV0 for pgl in pglons])
    bovy_plot.bovy_plot(mglons,mterms,'-',color='0.6',lw=2.,zorder=0,
                        xlabel=r'$\mathrm{Galactic\ longitude\, (deg)}$',
                        ylabel=r'$\mathrm{Terminal\ velocity}\, (\mathrm{km\,s}^{-1})$',
                        xrange=[-100.,100.],
                        yrange=[-150.,150.],
                        gcf=True)
    bovy_plot.bovy_plot(pglons,pterms,'-',color='0.6',lw=2.,zorder=0,
                        overplot=True)
    cl_glon,cl_vterm,cl_corr,mc_glon,mc_vterm,mc_corr= termdata
    bovy_plot.bovy_plot(cl_glon,cl_vterm,'ko',overplot=True)
    bovy_plot.bovy_plot(mc_glon-360.,mc_vterm,'ko',overplot=True)
    return None
def plotKz(pot,surfrs,kzs,kzerrs,_REFR0,_REFV0):
    krs= numpy.linspace(4./_REFR0,10./_REFR0,1001)
    modelkz= numpy.array([-potential.evaluatezforces(pot,kr,1.1/_REFR0)\
                               *bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0) for kr in krs])
    bovy_plot.bovy_plot(krs*_REFR0,modelkz,'-',color='0.6',lw=2.,
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$F_{Z}(R,|Z| = 1.1\,\mathrm{kpc})\ (2\pi G\,M_\odot\,\mathrm{pc}^{-2})$',
                        semilogy=True,
                        yrange=[10.,1000.],
                        xrange=[4.,10.],
                        zorder=0,gcf=True)
    pyplot.errorbar(_REFR0-8.+surfrs,
                    kzs,
                    yerr=kzerrs,
                    marker='o',
                    elinewidth=1.,capsize=3,zorder=1,
                    color='k',linestyle='none')  
    pyplot.errorbar([_REFR0],[69.],yerr=[6.],marker='d',ms=10.,
                    elinewidth=1.,capsize=3,zorder=10,
                    color='0.4',linestyle='none')
    #Do an exponential fit to the model Kz and return the scale length
    indx= krs < 9./_REFR0
    p= numpy.polyfit(krs[indx],numpy.log(modelkz[indx]),1)
    return -1./p[0]
Example #49
0
def model_stream_struct_vary_c():

    # ----------------------------------------------------------
    # Varying the flattening $c$ of the halo
    # We compute the stream structure for a fiducial set of parameters, to get
    # a sense of where the track lies and how the width and length vary

    pal5varyc, cs = _get_pal5varyc()

    # -------------------------------------------

    plt.figure(figsize=(12, 4))
    for ii, c in enumerate(cs):
        tc = cmap((c - np.amin(cs)) / (np.amax(cs) - np.amin(cs)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varyc[0][ii, :, 0],
            pal5varyc[0][ii, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyc[1][ii, :, 0],
            pal5varyc[1][ii, :, 1],
            color=tc,
            overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varyc[2][ii, :, 0],
            pal5varyc[2][ii, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyc[3][ii, :, 0],
            pal5varyc[3][ii, :, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varyc.pdf")

    return
Example #50
0
def model_stream_struct_vary_d():

    pal5varyc, cs = _get_pal5varyc()
    pal5varyd, ds = _get_pal5varyd()

    # ----------------------------------------------------------
    # Varying the distance to the Pal 5 cluster

    plt.figure(figsize=(12, 4))

    for ii, d in enumerate(ds):
        tc = cmap((d - np.amin(ds)) / (np.amax(ds) - np.amin(ds)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varyd[ii, 0, :, 0],
            pal5varyd[ii, 0, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyd[ii, 1, :, 0],
            pal5varyd[ii, 1, :, 1],
            color=tc,
            overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varyd[ii, 2, :, 0],
            pal5varyd[ii, 2, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyd[ii, 3, :500, 0],
            pal5varyd[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varyd.pdf")
Example #51
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
Example #52
0
def model_stream_struct_vary_pm():

    pal5varyc, cs = _get_pal5varyc()
    pal5varypm, pms = _get_pal5varypm()

    # ----------------------------------------------------------
    # Varying the proper motion of the Pal 5 cluster

    plt.figure(figsize=(12, 4))

    for ii, pm in enumerate(pms):
        tc = cmap((pm - np.amin(pms)) / (np.amax(pms) - np.amin(pms)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varypm[ii, 0, :, 0],
            pal5varypm[ii, 0, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varypm[ii, 1, :, 0],
            pal5varypm[ii, 1, :, 1],
            color=tc,
            overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varypm[ii, 2, :, 0],
            pal5varypm[ii, 2, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varypm[ii, 3, :500, 0],
            pal5varypm[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varypm.pdf")
Example #53
0
 def plot(self,l,b,*args,**kwargs):
     """
     NAME:
        plot
     PURPOSE:
        plot the extinction along a given line of sight as a function of 
        distance
     INPUT:
        l,b - Galactic longitude and latitude (degree)
        range= distance range in kpc
        distmod= (False) if True, plot as a function of distance modulus (range is distmod range)
        bovy_plot.bovy_plot args and kwargs
     OUTPUT:
        plot to output device
     HISTORY:
        2013-12-11 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise NotImplementedError("galpy.util.bovy_plot could not be loaded, so there is no plotting; might have to install galpy (http://github.com/jobovy/galpy) for plotting")
     distmod= kwargs.pop('distmod',False)
     range= kwargs.pop('range',None)
     if range is None and distmod:
         range= [4.,19.]
     else:
         range= [0.,12.]
     nds= kwargs.get('nds',101)
     #First evaluate the dust map
     ds= numpy.linspace(range[0],range[1],nds)
     if distmod:
         adust= self(l,b,10.**(ds/5.-2.))
     else:
         adust= self(l,b,ds)
     #Add labels
     if distmod:
         kwargs['xlabel']= r'$\mathrm{Distance\ modulus}$'
     else:
         kwargs['xlabel']= r'$D\,(\mathrm{kpc})$'
     if not self._filter is None:
         kwargs['ylabel']= r'$A_{%s}\,(\mathrm{mag})$' % (self._filter.split(' ')[-1])
     else:
         kwargs['ylabel']= r'$E(B-V)\,(\mathrm{mag})$'
     return bovy_plot.bovy_plot(ds,adust,*args,**kwargs)
Example #54
0
def model_stream_struct_vary_vcirc():
    # ----------------------------------------------------------
    # Varying the circular velocity $V_c(R_0)$ to change the normalization of the potential

    pal5varyvc, vcs = _get_pal5varyc()

    plt.figure(figsize=(12, 4))

    for ii, vc in enumerate(vcs):
        tc = cmap((vc - np.amin(vcs)) / (np.amax(vcs) - np.amin(vcs)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 0, :, 0],
            pal5varyvc[ii, 0, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 1, :, 0],
            pal5varyvc[ii, 1, :, 1],
            color=tc,
            overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 2, :, 0],
            pal5varyvc[ii, 2, :, 1],
            color=tc,
            overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 3, :500, 0],
            pal5varyvc[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varyvc.pdf")
Example #55
0
 def plotE(self,*args,**kwargs):
     """
     NAME:
        plotE
     PURPOSE:
        plot E(.) along the orbit
     INPUT:
        pot - Potential instance or list of instances in which the orbit was
              integrated
        d1= - plot Ez vs d1: e.g., 't', 'x', 'vx'
        +bovy_plot.bovy_plot inputs
     OUTPUT:
        figure to output device
     HISTORY:
        2010-07-10 - Written - Bovy (NYU)
     """
     labeldict= {'t':r'$t$','R':r'$R$','vR':r'$v_R$','vT':r'$v_T$',
                 'z':r'$z$','vz':r'$v_z$','phi':r'$\phi$',
                 'x':r'$x$','y':r'$y$','vx':r'$v_x$','vy':r'$v_y$'}
     if not kwargs.has_key('pot'):
         try:
             pot= self._pot
         except AttributeError:
             raise AttributeError("Integrate orbit first or specify pot=")
     else:
         pot= kwargs['pot']
         kwargs.pop('pot')
     if kwargs.has_key('d1'):
         d1= kwargs['d1']
         kwargs.pop('d1')
     else:
         d1= 't'
     self.Es= [evaluatelinearPotentials(self.orbit[ii,0],pot,t=self.t[ii])+
              self.orbit[ii,1]**2./2.
              for ii in range(len(self.t))]
     if not kwargs.has_key('xlabel'):
         kwargs['xlabel']= labeldict[d1]
     if not kwargs.has_key('ylabel'):
         kwargs['ylabel']= r'$E$'
     if d1 == 't':
         plot.bovy_plot(nu.array(self.t),nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
     elif d1 == 'x':
         plot.bovy_plot(self.orbit[:,0],nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
     elif d1 == 'vx':
         plot.bovy_plot(self.orbit[:,1],nu.array(self.Es)/self.Es[0],
                        *args,**kwargs)
Example #56
0
 def plot_samples(self):
     """
     NAME:
        plot_samples
     PURPOSE:
        plot the samples that the histogramming is based on 
     INPUT:
     OUTPUT:
        plot to output device
     HISTORY:
        2012-06-15 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError(
             "'galpy.util.bovy_plot' plotting package not found")
     return bovy_plot.bovy_plot(self._sample[:, 0],
                                self._sample[:, 1],
                                'k,',
                                xrange=[self._jkmin, self._jkmax],
                                yrange=[self._hmax, self._hmin],
                                xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                                ylabel=r'$M_H\ [\mathrm{mag}]$')
Example #57
0
 def plot_samples(self):
     """
     NAME:
        plot_samples
     PURPOSE:
        plot the samples that the histogramming is based on 
     INPUT:
     OUTPUT:
        plot to output device
     HISTORY:
        2012-06-15 - Written - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError(
             "'galpy.util.bovy_plot' plotting package not found")
     if self._band == 'J':
         ylabel = r'$M_J$'
     elif self._band == 'H':
         ylabel = r'$M_H$'
     elif self._band == 'K':
         ylabel = r'$M_K$'
     elif self._band == 'Ks':
         ylabel = r'$M_{K_s}$'
     ylim = [self._hmax, self._hmin]
     return bovy_plot.bovy_plot(self._sample[:, 0],
                                self._sample[:, 1],
                                xrange=[self._jkmin, self._jkmax],
                                yrange=ylim,
                                xlabel=r'$(J-K_s)_0$',
                                ylabel=ylabel,
                                scatter=True,
                                c=self._weights,
                                edgecolors='none',
                                s=numpy.ones(len(self._weights)) * 10.,
                                alpha=0.5,
                                marker='o',
                                colorbar=True)
Example #58
0
    def plot(self, *args, **kwargs):
        """
        NAME:

           plot

        PURPOSE:

           plot the snapshot (with reasonable defaults)

        INPUT:

           d1= first dimension to plot ('x', 'y', 'R', 'vR', 'vT', 'z', 'vz', ...)

           d2= second dimension to plot

           matplotlib.plot inputs+bovy_plot.plot inputs

        OUTPUT:

           sends plot to output device

        HISTORY:

           2011-02-06 - Written based on Orbit's plot

        """
        labeldict = {
            't': r'$t$',
            'R': r'$R$',
            'vR': r'$v_R$',
            'vT': r'$v_T$',
            'z': r'$z$',
            'vz': r'$v_z$',
            'phi': r'$\phi$',
            'x': r'$x$',
            'y': r'$y$',
            'vx': r'$v_x$',
            'vy': r'$v_y$'
        }
        #Defaults
        if not kwargs.has_key('d1') and not kwargs.has_key('d2'):
            if len(self.orbits[0].vxvv) == 3:
                d1 = 'R'
                d2 = 'vR'
            elif len(self.orbits[0].vxvv) == 4:
                d1 = 'x'
                d2 = 'y'
            elif len(self.orbits[0].vxvv) == 2:
                d1 = 'x'
                d2 = 'vx'
            elif len(self.orbits[0].vxvv) == 5 \
                    or len(self.orbits[0].vxvv) == 6:
                d1 = 'R'
                d2 = 'z'
        elif not kwargs.has_key('d1'):
            d2 = kwargs['d2']
            kwargs.pop('d2')
            d1 = 't'
        elif not kwargs.has_key('d2'):
            d1 = kwargs['d1']
            kwargs.pop('d1')
            d2 = 't'
        else:
            d1 = kwargs['d1']
            kwargs.pop('d1')
            d2 = kwargs['d2']
            kwargs.pop('d2')
        #Get x and y
        if d1 == 'R':
            x = [o.R() for o in self.orbits]
        elif d1 == 'z':
            x = [o.z() for o in self.orbits]
        elif d1 == 'vz':
            x = [o.vz() for o in self.orbits]
        elif d1 == 'vR':
            x = [o.vR() for o in self.orbits]
        elif d1 == 'vT':
            x = [o.vT() for o in self.orbits]
        elif d1 == 'x':
            x = [o.x() for o in self.orbits]
        elif d1 == 'y':
            x = [o.y() for o in self.orbits]
        elif d1 == 'vx':
            x = [o.vx() for o in self.orbits]
        elif d1 == 'vy':
            x = [o.vy() for o in self.orbits]
        elif d1 == 'phi':
            x = [o.phi() for o in self.orbits]
        if d2 == 'R':
            y = [o.R() for o in self.orbits]
        elif d2 == 'z':
            y = [o.z() for o in self.orbits]
        elif d2 == 'vz':
            y = [o.vz() for o in self.orbits]
        elif d2 == 'vR':
            y = [o.vR() for o in self.orbits]
        elif d2 == 'vT':
            y = [o.vT() for o in self.orbits]
        elif d2 == 'x':
            y = [o.x() for o in self.orbits]
        elif d2 == 'y':
            y = [o.y() for o in self.orbits]
        elif d2 == 'vx':
            y = [o.vx() for o in self.orbits]
        elif d2 == 'vy':
            y = [o.vy() for o in self.orbits]
        elif d2 == 'phi':
            y = [o.phi() for o in self.orbits]

        #Plot
        if not kwargs.has_key('xlabel'):
            kwargs['xlabel'] = labeldict[d1]
        if not kwargs.has_key('ylabel'):
            kwargs['ylabel'] = labeldict[d2]
        if len(args) == 0:
            args = (',', )
        plot.bovy_plot(x, y, *args, **kwargs)
 def plot(self,*args,**kwargs):
     """
     NAME:
        plot
     PURPOSE:
        plot the angles vs. each other, to check whether the isochrone
        approximation is good
     INPUT:
        Either:
           a) R,vR,vT,z,vz:
              floats: phase-space value for single object
           b) Orbit instance
        type= ('araz') type of plot to make
           a) 'araz': az vs. ar, with color-coded aphi
           b) 'araphi': aphi vs. ar, with color-coded az
           c) 'azaphi': aphi vs. az, with color-coded ar
           d) 'jr': cumulative average of jr with time, to assess convergence
           e) 'lz': same as 'jr' but for lz
           f) 'jz': same as 'jr' but for jz
        deperiod= (False), if True, de-period the angles
        downsample= (False) if True, downsample what's plotted to 400 points
         +plot kwargs
     OUTPUT:
        plot to output
     HISTORY:
        2013-09-10 - Written - Bovy (IAS)
     """
     #Kwargs
     type= kwargs.pop('type','araz')
     deperiod= kwargs.pop('deperiod',False)
     downsample= kwargs.pop('downsample',False)
     #Parse input
     R,vR,vT,z,vz,phi= self._parse_args('a' in type,False,*args)
     #Use self._aAI to calculate the actions and angles in the isochrone potential
     acfs= self._aAI.actionsFreqsAngles(R.flatten(),
                                        vR.flatten(),
                                        vT.flatten(),
                                        z.flatten(),
                                        vz.flatten(),
                                        phi.flatten())
     if type == 'jr' or type == 'lz' or type == 'jz':
         jrI= nu.reshape(acfs[0],R.shape)[:,:-1]
         jzI= nu.reshape(acfs[2],R.shape)[:,:-1]
         anglerI= nu.reshape(acfs[6],R.shape)
         anglezI= nu.reshape(acfs[8],R.shape)
         danglerI= ((nu.roll(anglerI,-1,axis=1)-anglerI) % _TWOPI)[:,:-1]
         danglezI= ((nu.roll(anglezI,-1,axis=1)-anglezI) % _TWOPI)[:,:-1]
         if True:
             sumFunc= nu.cumsum
         jr= sumFunc(jrI*danglerI,axis=1)/sumFunc(danglerI,axis=1)
         jz= sumFunc(jzI*danglezI,axis=1)/sumFunc(danglezI,axis=1)
         lzI= nu.reshape(acfs[1],R.shape)[:,:-1]
         anglephiI= nu.reshape(acfs[7],R.shape)
         danglephiI= ((nu.roll(anglephiI,-1,axis=1)-anglephiI) % _TWOPI)[:,:-1]
         lz= sumFunc(lzI*danglephiI,axis=1)/sumFunc(danglephiI,axis=1)
         from galpy.orbit import Orbit
         if isinstance(args[0],Orbit) and hasattr(args[0]._orb,'t'):
             ts= args[0]._orb.t[:-1]
         else:
             ts= self._tsJ[:-1]
         if type == 'jr':
             if downsample:
                 plotx= ts[::int(round(self._ntintJ//400))]
                 ploty= jr[0,::int(round(self._ntintJ//400))]/jr[0,-1]
                 plotz= anglerI[0,:-1:int(round(self._ntintJ//400))]
             else:
                 plotx= ts
                 ploty= jr[0,:]/jr[0,-1]
                 plotz= anglerI[0,:-1]
             bovy_plot.bovy_plot(plotx,ploty,
                                 c=plotz,
                                 s=20.,
                                 scatter=True,
                                 edgecolor='none',
                                 xlabel=r'$t$',
                                 ylabel=r'$J^A_R / \langle J^A_R \rangle$',
                                 clabel=r'$\theta^A_R$',
                                 vmin=0.,vmax=2.*nu.pi,
                                 crange=[0.,2.*nu.pi],
                                 colorbar=True,
                                 **kwargs)
         elif type == 'lz':
             if downsample:
                 plotx= ts[::int(round(self._ntintJ//400))]
                 ploty= lz[0,::int(round(self._ntintJ//400))]/lz[0,-1]
                 plotz= anglephiI[0,:-1:int(round(self._ntintJ//400))]
             else:
                 plotx= ts
                 ploty= lz[0,:]/lz[0,-1]
                 plotz= anglephiI[0,:-1]
             bovy_plot.bovy_plot(plotx,ploty,c=plotz,s=20.,
                                 scatter=True,
                                 edgecolor='none',
                                 xlabel=r'$t$',
                                 ylabel=r'$L^A_Z / \langle L^A_Z \rangle$',
                                 clabel=r'$\theta^A_\phi$',
                                 vmin=0.,vmax=2.*nu.pi,
                                 crange=[0.,2.*nu.pi],
                                 colorbar=True,
                                 **kwargs)
         elif type == 'jz':
             if downsample:
                 plotx= ts[::int(round(self._ntintJ//400))]
                 ploty= jz[0,::int(round(self._ntintJ//400))]/jz[0,-1]
                 plotz= anglezI[0,:-1:int(round(self._ntintJ//400))]
             else:
                 plotx= ts
                 ploty= jz[0,:]/jz[0,-1]
                 plotz= anglezI[0,:-1]
             bovy_plot.bovy_plot(plotx,ploty,c=plotz,s=20.,
                                 scatter=True,
                                 edgecolor='none',
                                 xlabel=r'$t$',
                                 ylabel=r'$J^A_Z / \langle J^A_Z \rangle$',
                                 clabel=r'$\theta^A_Z$',
                                 vmin=0.,vmax=2.*nu.pi,
                                 crange=[0.,2.*nu.pi],
                                 colorbar=True,
                                 **kwargs)
     else:
         if kwargs.get('nonaxi',False):
             raise NotImplementedError('angles for non-axisymmetric potentials not implemented yet')
         if deperiod:
             if 'ar' in type:
                 angleRT= dePeriod(nu.reshape(acfs[6],R.shape))
             else:
                 angleRT= nu.reshape(acfs[6],R.shape)
             if 'aphi' in type:
                 acfs7= nu.reshape(acfs[7],R.shape)
                 negFreqIndx= nu.median(acfs7-nu.roll(acfs7,1,axis=1),axis=1) < 0. #anglephi is decreasing
                 anglephiT= nu.empty(acfs7.shape)
                 anglephiT[negFreqIndx,:]= dePeriod(_TWOPI-acfs7[negFreqIndx,:])
                 negFreqPhi= nu.zeros(R.shape[0],dtype='bool')
                 negFreqPhi[negFreqIndx]= True
                 anglephiT[True-negFreqIndx,:]= dePeriod(acfs7[True-negFreqIndx,:])
             else:
                 anglephiT= nu.reshape(acfs[7],R.shape)
             if 'az' in type:
                 angleZT= dePeriod(nu.reshape(acfs[8],R.shape))
             else:
                 angleZT= nu.reshape(acfs[8],R.shape)
             xrange= None
             yrange= None
         else:
             angleRT= nu.reshape(acfs[6],R.shape)
             anglephiT= nu.reshape(acfs[7],R.shape)
             angleZT= nu.reshape(acfs[8],R.shape)
             xrange= [-0.5,2.*nu.pi+0.5]
             yrange= [-0.5,2.*nu.pi+0.5]
         vmin, vmax= 0.,2.*nu.pi
         crange= [vmin,vmax]
         if type == 'araz':
             if downsample:
                 plotx= angleRT[0,::int(round(self._ntintJ//400))]
                 ploty= angleZT[0,::int(round(self._ntintJ//400))]
                 plotz= anglephiT[0,::int(round(self._ntintJ//400))]
             else:
                 plotx= angleRT[0,:]
                 ploty= angleZT[0,:]
                 plotz= anglephiT[0,:]
             bovy_plot.bovy_plot(plotx,ploty,c=plotz,s=20.,
                                 scatter=True,
                                 edgecolor='none',
                                 xlabel=r'$\theta^A_R$',
                                 ylabel=r'$\theta^A_Z$',
                                 clabel=r'$\theta^A_\phi$',
                                 xrange=xrange,yrange=yrange,
                                 vmin=vmin,vmax=vmax,
                                 crange=crange,
                                 colorbar=True,
                                 **kwargs)           
         elif type == 'araphi':
             if downsample:
                 plotx= angleRT[0,::int(round(self._ntintJ//400))]
                 ploty= anglephiT[0,::int(round(self._ntintJ//400))]
                 plotz= angleZT[0,::int(round(self._ntintJ//400))]
             else:
                 plotx= angleRT[0,:]
                 ploty= anglephiT[0,:]
                 plotz= angleZT[0,:]
             bovy_plot.bovy_plot(plotx,ploty,c=plotz,s=20.,
                                 scatter=True,
                                 edgecolor='none',
                                 xlabel=r'$\theta^A_R$',
                                 clabel=r'$\theta^A_Z$',
                                 ylabel=r'$\theta^A_\phi$',
                                 xrange=xrange,yrange=yrange,
                                 vmin=vmin,vmax=vmax,
                                 crange=crange,
                                 colorbar=True,
                                 **kwargs)           
         elif type == 'azaphi':
             if downsample:
                 plotx= angleZT[0,::int(round(self._ntintJ//400))]
                 ploty= anglephiT[0,::int(round(self._ntintJ//400))]
                 plotz= angleRT[0,::int(round(self._ntintJ//400))]
             else:
                 plotx= angleZT[0,:]
                 ploty= anglephiT[0,:]
                 plotz= angleRT[0,:]
             bovy_plot.bovy_plot(plotx,ploty,c=plotz,s=20.,
                                 scatter=True,
                                 edgecolor='none',
                                 clabel=r'$\theta^A_R$',
                                 xlabel=r'$\theta^A_Z$',
                                 ylabel=r'$\theta^A_\phi$',
                                 xrange=xrange,yrange=yrange,
                                 vmin=vmin,vmax=vmax,
                                 crange=crange,
                                 colorbar=True,
                                 **kwargs)           
     return None
Example #60
0
def plotEscapecurve(Pot,*args,**kwargs):
    """
    NAME:

       plotEscapecurve

    PURPOSE:

       plot the escape velocity curve for this potential (in the z=0 plane for
       non-spherical potentials)

    INPUT:

       Pot - Potential or list of Potential instances

       Rrange= Range in R to consider (can be Quantity)

       grid= grid in R

       savefilename= save to or restore from this savefile (pickle)

       +bovy_plot.bovy_plot args and kwargs

    OUTPUT:

       plot to output device

    HISTORY:

       2010-08-08 - Written - Bovy (NYU)

    """
    # Using physical units or not?
    if isinstance(Pot,list):
        potro= Pot[0]._ro
        roSet= Pot[0]._roSet
        potvo= Pot[0]._vo
        voSet= Pot[0]._voSet
    else:
        potro= Pot._ro
        roSet= Pot._roSet
        potvo= Pot._vo
        voSet= Pot._voSet
    if (kwargs.get('use_physical',False) \
            and kwargs.get('ro',roSet) and kwargs.get('vo',voSet)) or \
            (not 'use_physical' in kwargs \
                 and kwargs.get('ro',roSet) and kwargs.get('vo',voSet)):
        use_physical= True
        potro= kwargs.get('ro',potro)
        potvo= kwargs.get('vo',potvo)
        xlabel= r'$R\,(\mathrm{kpc})$'
        ylabel= r"$v_e(R)\,(\mathrm{km\,s}^{-1})$"
        Rrange= kwargs.pop('Rrange',[0.01*potro,5.*potro])
    else:
        use_physical= False
        xlabel= r"$R/R_0$"
        ylabel= r"$v_e(R)/v_c(R_0)$"
        Rrange= kwargs.pop('Rrange',[0.01,5.])
    # Parse ro
    if _APY_LOADED:
        if isinstance(potro,units.Quantity):
            potro= potro.to(units.kpc).value
        if isinstance(potvo,units.Quantity):
            potvo= potvo.to(units.km/units.s).value
        if isinstance(Rrange[0],units.Quantity):
            Rrange[0]= Rrange[0].to(units.kpc).value
        if isinstance(Rrange[1],units.Quantity):
            Rrange[1]= Rrange[1].to(units.kpc).value
    if use_physical:
        Rrange[0]/= potro
        Rrange[1]/= potro
    grid= kwargs.pop('grid',1001)
    savefilename= kwargs.pop('savefilename',None)
    if not savefilename == None and os.path.exists(savefilename):
        print("Restoring savefile "+savefilename+" ...")
        savefile= open(savefilename,'rb')
        esccurve= pickle.load(savefile)
        Rs= pickle.load(savefile)
        savefile.close()
    else:
        Rs= nu.linspace(Rrange[0],Rrange[1],grid)
        esccurve= calcEscapecurve(Pot,Rs)
        if not savefilename == None:
            print("Writing savefile "+savefilename+" ...")
            savefile= open(savefilename,'wb')
            pickle.dump(esccurve,savefile)
            pickle.dump(Rs,savefile)
            savefile.close()
    if use_physical:
        Rs*= potro
        esccurve*= potvo
        Rrange[0]*= potro
        Rrange[1]*= potro
    if not 'xlabel' in kwargs:
        kwargs['xlabel']= xlabel
    if not 'ylabel' in kwargs:
        kwargs['ylabel']= ylabel
    if not 'xrange' in kwargs:
        kwargs['xrange']= Rrange
    if not 'yrange' in kwargs:
        kwargs['yrange']=\
            [0.,1.2*nu.amax(esccurve[True^nu.isnan(esccurve)])]
    kwargs.pop('ro',None)
    kwargs.pop('vo',None)
    kwargs.pop('use_physical',None)
    return plot.bovy_plot(Rs,esccurve,*args,
                          **kwargs)