Ejemplo n.º 1
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
Ejemplo n.º 2
0
def plot_forces():
    potparams= numpy.array([numpy.log(2.15/_REFR0),
                            1.,
                            numpy.log(0.3/_REFR0),
                            0.307169914244,
                            -1.79107550983])
    options= setup_options(None)
    options.potential= 'dpdiskplhalofixcutbulgeflatwgasalt'
    pot= setup_potential(potparams,options,0,returnrawpot=True)
    bovy_plot.bovy_print(fig_width=8.,fig_height=5.)
    potential.plotDensities(pot,rmin=-15./8.,rmax=15./8.,nrs=100,
                            zmin=-10./8,zmax=10./8.,nzs=101,ncontours=10,
                            aspect=5./5.,log=True)
    
    bovy_plot.bovy_end_print('/home/bovy/Desktop/test.png')
    pass
Ejemplo n.º 3
0
def plotDistanceSystematics(plotfilename):
    #hard-code these paths 
    savefilename= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc230_an_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    savefilename_iv= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc230_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    #Read surface densities
    if os.path.exists(savefilename):
        surffile= open(savefilename,'rb')
        surfrs= pickle.load(surffile)
        surfs= pickle.load(surffile)
        surferrs= pickle.load(surffile)
        kzs= pickle.load(surffile)
        kzerrs= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    #Read surface densities
    if os.path.exists(savefilename_iv):
        surffile= open(savefilename_iv,'rb')
        surfrs_iv= pickle.load(surffile)
        surfs_iv= pickle.load(surffile)
        surferrs_iv= pickle.load(surffile)
        kzs_iv= pickle.load(surffile)
        kzerrs_iv= pickle.load(surffile)
        altsurfrs_iv= pickle.load(surffile)
        altsurfs_iv= pickle.load(surffile)
        altsurferrs_iv= pickle.load(surffile)
        altkzs_iv= pickle.load(surffile)
        altkzerrs_iv= 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)
    indx= numpy.isnan(surfrs)
    indx[50]= True
    indx[57]= True
    indx= True - indx
    surfrs= surfrs[indx]
    surfs= surfs[indx]
    surferrs= surferrs[indx]
    kzs= kzs[indx]
    kzerrs= kzerrs[indx]
    #vo250
    surfrs_iv= surfrs_iv[indx]
    surfs_iv= surfs_iv[indx]
    surferrs_iv= surferrs_iv[indx]
    kzs_iv= kzs_iv[indx]
    kzerrs_iv= kzerrs_iv[indx]
    altsurfrs_iv= altsurfrs_iv[indx]
    altsurfs_iv= altsurfs_iv[indx]
    altsurferrs_iv= altsurferrs_iv[indx]
    altkzs_iv= altkzs_iv[indx]
    altkzerrs_iv= altkzerrs_iv[indx]
    fehs= fehs[indx]
    afes= afes[indx]
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(surfrs,numpy.log(altsurfs_iv/surfs),'ko',
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$\ln \Sigma_{1.1}^{\mathrm{Ivezic}} / \Sigma_{1.1}^{\mathrm{An}}$',
                        xrange=[4.,10.],
                        yrange=[-0.29,0.29],zorder=10)
    pyplot.errorbar(surfrs,numpy.log(altsurfs_iv/surfs),
                    yerr=surferrs/surfs,
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=5,
                    color='k')
    #Get distance factors
    options= setup_options(None)
    raw= read_rawdata(options)
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Get fehs from monoAb
    tfehs= monoAbundanceMW.fehs(k=(options.sample.lower() == 'k'))
    tafes= monoAbundanceMW.afes(k=(options.sample.lower() == 'k'))
    plotthis= numpy.zeros_like(tfehs)
    for ii in range(len(tfehs)):
        #Get the relevant data
        data= binned(tfehs[ii],tafes[ii])
        plotthis[ii]= AnDistance.AnDistance(data.dered_g-data.dered_r,
                                            data.feh)
    plotthis= plotthis[indx]
    #Spline interpolate
    distfunc= interpolate.UnivariateSpline(surfrs,numpy.log(plotthis))
    plotrs= numpy.linspace(4.5,9.,1001)
    pyplot.plot(plotrs,distfunc(plotrs),'--',color='0.5',lw=2.)
    pyplot.plot(plotrs,-distfunc(plotrs),'--',color='0.5',lw=2.)
    bovy_plot.bovy_end_print(plotfilename)
Ejemplo n.º 4
0
def plot_hrhrvshr(options,args):
    """Plot hr^out/hr^in as a function of hr for various sr"""
    if len(args) == 0.:
        print "Must provide a savefilename ..."
        print "Returning ..."
        return None
    if os.path.exists(args[0]):
        #Load
        savefile= open(args[0],'rb')
        plotthis= pickle.load(savefile)
        hrs= pickle.load(savefile)
        srs= pickle.load(savefile)
        savefile.close()
    else:
        #Grid of models to test
        hrs= numpy.linspace(options.hrmin,options.hrmax,options.nhr)
        srs= numpy.linspace(options.srmin,options.srmax,options.nsr)
        #Tile
        hrs= numpy.tile(hrs,(options.nsr,1)).T
        srs= numpy.tile(srs,(options.nhr,1))
        plotthis= numpy.zeros((options.nhr,options.nsr))
        #Setup potential and aA
        poptions= setup_options(None)
        #poptions.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        #params= [0.,0.,0.,0.,0.,0.,-1.16315,1.,-3.,0.4,0.]
        poptions.potential= 'btii'
        params= None
        #pot= MWPotential
        pot= setup_potential(params,poptions,1)
        if options.aAmethod.lower() == 'staeckel':
            aA= actionAngleStaeckel(pot=pot,delta=0.45,c=True)
        else:
            aA=actionAngleAdiabaticGrid(pot=pot,nR=16,nEz=16,nEr=31,nLz=31,
                                        zmax=1.,Rmax=5.)
        for ii in range(options.nhr):
            for jj in range(options.nsr):
                qdf= quasiisothermaldf(hrs[ii,jj]/8.,srs[ii,jj]/220.,
                                       srs[ii,jj]/numpy.sqrt(3.)/220.,
                                       7./8.,1.,
                                       pot=pot,aA=aA)
                plotthis[ii,jj]= qdf.estimate_hr(1.,z=0.8/8.,
                                                 dR=0.33,
                                                 gl=True)/hrs[ii,jj]*8.
                print ii*options.nsr+jj+1, options.nsr*options.nhr, \
                    hrs[ii,jj], srs[ii,jj], plotthis[ii,jj]
        #Save
        save_pickles(args[0],plotthis,hrs,srs)
    #Now plot
    bovy_plot.bovy_print(fig_width=6.,
                         text_fontsize=20.,
                         legend_fontsize=24.,
                         xtick_labelsize=18.,
                         ytick_labelsize=18.,
                         axes_labelsize=24.)
    indx= 0
    lines= []
    colors= [cm.jet(ii/float(options.nsr-1.)*1.+0.) for ii in range(options.nsr)]
    lss= ['-' for ii in range(options.nsr)]#,'--','-.','..']
    labels= []
    lines.append(bovy_plot.bovy_plot(hrs[:,indx],plotthis[:,indx],
                                     color=colors[indx],ls=lss[indx],
                                     xrange=[0.5,5.5],
                                     yrange=[0.,2.],
                                     xlabel=r'$h^{\mathrm{in}}_R\ \mathrm{at}\ 8\,\mathrm{kpc}$',
                                     ylabel=r'$h^{\mathrm{out}}_R / h^{\mathrm{in}}_R$'))
    labels.append(r'$\sigma_R = %.0f \,\mathrm{km\,s}^{-1}$' % srs[0,indx])
    for indx in range(1,options.nsr):
        lines.append(bovy_plot.bovy_plot(hrs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         overplot=True))
        labels.append(r'$\sigma_R = %.0f \,\mathrm{km\,s}^{-1}$' % srs[0,indx])
    """
    #Legend
    pyplot.legend(lines,#(line1[0],line2[0],line3[0],line4[0]),
                  labels,#(r'$v_{bc} = 0$',
#                   r'$v_{bc} = 1\,\sigma_{bc}$',
#                   r'$v_{bc} = 2\,\sigma_{bc}$',
#                   r'$v_{bc} = 3\,\sigma_{bc}$'),
                  loc='lower right',#bbox_to_anchor=(.91,.375),
                  numpoints=2,
                  prop={'size':14},
                  frameon=False)
    """
     #Add colorbar
    map = cm.ScalarMappable(cmap=cm.jet)
    map.set_array(srs[0,:])
    map.set_clim(vmin=numpy.amin(srs[0,:]),vmax=numpy.amax(srs[0,:]))
    cbar= pyplot.colorbar(map,fraction=0.15)
    cbar.set_clim(numpy.amin(srs[0,:]),numpy.amax(srs[0,:]))
    cbar.set_label(r'$\sigma_R \,(\mathrm{km\,s}^{-1})$')
    bovy_plot.bovy_end_print(options.plotfilename)
Ejemplo n.º 5
0
def plot_szszvssz(options,args):
    """Plot sz^out/sz^in as a function of sz for various hr"""
    if len(args) == 0.:
        print "Must provide a savefilename ..."
        print "Returning ..."
        return None
    if os.path.exists(args[0]):
        #Load
        savefile= open(args[0],'rb')
        plotthis= pickle.load(savefile)
        szs= pickle.load(savefile)
        hrs= pickle.load(savefile)
        savefile.close()
    else:
        #Grid of models to test
        if options.subtype.lower() == 'sr':
            szs= numpy.linspace(options.srmin,options.srmax,options.nsz)
        else:
            szs= numpy.linspace(options.szmin,options.szmax,options.nsz)
        hrs= numpy.linspace(options.hrmin,options.hrmax,options.nhr)
        #Tile
        szs= numpy.tile(szs,(options.nhr,1)).T
        hrs= numpy.tile(hrs,(options.nsz,1))
        plotthis= numpy.zeros((options.nsz,options.nhr))
        #Setup potential and aA
        poptions= setup_options(None)
        #poptions.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        #params= [0.,0.,0.,0.,0.,0.,-1.16315,1.,-3.,0.4,0.]
        poptions.potential= 'btii'
        params= None
        #pot= MWPotential
        pot= setup_potential(params,poptions,1)
        if options.aAmethod.lower() == 'staeckel':
            aA= actionAngleStaeckel(pot=pot,delta=0.45,c=True)
        else:
            aA=actionAngleAdiabaticGrid(pot=pot,nR=16,nEz=16,nEr=31,nLz=31,
                                        zmax=1.,Rmax=5.)
        for ii in range(options.nsz):
            for jj in range(options.nhr):
                if options.subtype.lower() == 'sr':
                    qdf= quasiisothermaldf(hrs[ii,jj]/8.,
                                           szs[ii,jj]/220.,
                                           szs[ii,jj]/220./numpy.sqrt(3.),
                                           7./8.,1.,
                                           pot=pot,aA=aA)
                else:
                    qdf= quasiisothermaldf(hrs[ii,jj]/8.,
                                           szs[ii,jj]/220.*numpy.sqrt(3.),
                                           szs[ii,jj]/220.,
                                           7./8.,1.,
                                           pot=pot,aA=aA)
                if options.subtype.lower() == 'sr':
                    plotthis[ii,jj]= numpy.sqrt(qdf.sigmaR2(1.,0.8/8.,
                                                            gl=True))/szs[ii,jj]*220.
                else:
                    plotthis[ii,jj]= numpy.sqrt(qdf.sigmaz2(1.,0.8/8.,
                                                        gl=True))/szs[ii,jj]*220.
                print ii*options.nhr+jj+1, options.nhr*options.nsz, \
                    szs[ii,jj], hrs[ii,jj], plotthis[ii,jj]
        #Save
        save_pickles(args[0],plotthis,szs,hrs)
    #Now plot
    bovy_plot.bovy_print(fig_width=6.,
                         text_fontsize=20.,
                         legend_fontsize=24.,
                         xtick_labelsize=18.,
                         ytick_labelsize=18.,
                         axes_labelsize=24.)
    indx= 0
    lines= []
    colors= [cm.jet(ii/float(options.nhr-1.)*1.+0.) for ii in range(options.nhr)]
    lss= ['-' for ii in range(options.nhr)]#,'--','-.','..']
    labels= []
    if options.subtype.lower() == 'sr':
        lines.append(bovy_plot.bovy_plot(szs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         xrange=[10.,85.],
                                         yrange=[0.8,1.5],
                                         xlabel=r'$\sigma^{\mathrm{in}}_R\ \mathrm{at}\ R = 8\,\mathrm{kpc}$',
                                         ylabel=r'$\sigma^{\mathrm{out}}_R / \sigma^{\mathrm{in}}_R$'))
    else:
        lines.append(bovy_plot.bovy_plot(szs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         xrange=[10.,115.],
                                         yrange=[0.5,1.2],
                                         xlabel=r'$\sigma^{\mathrm{in}}_Z\ \mathrm{at}\ R = 8\,\mathrm{kpc}$',
                                         ylabel=r'$\sigma^{\mathrm{out}}_Z / \sigma^{\mathrm{in}}_Z$'))
    for indx in range(1,options.nhr):
        lines.append(bovy_plot.bovy_plot(szs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         overplot=True))
     #Add colorbar
    map = cm.ScalarMappable(cmap=cm.jet)
    map.set_array(hrs[0,:])
    map.set_clim(vmin=numpy.amin(hrs[0,:]),vmax=numpy.amax(hrs[0,:]))
    cbar= pyplot.colorbar(map,fraction=0.15)
    cbar.set_clim(numpy.amin(hrs[0,:]),numpy.amax(hrs[0,:]))
    cbar.set_label(r'$h_R\, (\mathrm{kpc})$')
    bovy_plot.bovy_end_print(options.plotfilename)
Ejemplo n.º 6
0
def plotSurfRdfh(plotfilename):
    #Calculate the surface density profile for each trial potential, then plot in 2D
    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.array([5.,8.,11.])
        rds= numpy.linspace(2.,3.4,_NRDS)
        fhs= numpy.linspace(0.,1.,_NFHS)
        surfz= numpy.zeros((len(rs),len(rds),len(fhs)))+numpy.nan
        ro= 1.
        vo= _VC/ _REFV0
        dlnvcdlnr= _DLNVCDLNR
        zh= _ZH
        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)):
                    if False:
                        surfz[ii,jj,kk]= -potential.evaluatezforces(rs[ii]/_REFR0,options.height/_REFR0/ro,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro/2./numpy.pi
                    else:
                        surfz[ii,jj,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
        #Save
        save_pickles(savefilename,rs,rds,fhs,surfz)
    else:
        savefile= open(savefilename,'rb')
        rs= pickle.load(savefile)
        rds= pickle.load(savefile)
        fhs= pickle.load(savefile)
        surfz= pickle.load(savefile)
        savefile.close()
    #Now plot
    bovy_plot.bovy_print()
    data = numpy.ma.masked_invalid(surfz[1,:,:])
    bovy_plot.bovy_dens2d(data.filled(data.mean()).T,
                          origin='lower',
                          cmap='jet',
                          colorbar=True,
                          shrink=0.775,
                          xlabel=r'$\mathrm{disk\ scale\ length}\,(\mathrm{kpc})$',
                          ylabel=r'$\mathrm{relative\ halo\ contribution\ to}\ V^2_c(R_0)$',
                          zlabel=r'$\Sigma(R_0,|Z| \leq 1.1\,\mathrm{kpc})\, (M_\odot\,\mathrm{pc}^{-2})$',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.])
    #Fix bad data
    bad_data = numpy.ma.masked_where(~data.mask, data.mask)
    bovy_plot.bovy_dens2d(bad_data.T,
                          origin='lower',
                          interpolation='nearest',
                          cmap=cm.gray_r,
                          overplot=True,
                          
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.])
    #Overlay contours of sigma at other R
    bovy_plot.bovy_dens2d(surfz[0,:,:].T,origin='lower',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.],
                          overplot=True,
                          justcontours=True,
                          contours=True,
                          cntrcolors='k',
                          cntrls='-')
    bovy_plot.bovy_dens2d(surfz[2,:,:].T,origin='lower',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.],
                          overplot=True,
                          justcontours=True,
                          contours=True,
                          cntrcolors='w',
#                          cntrlabel=True,
                          cntrls='--')
    #Add labels
    bovy_plot.bovy_text(r'$\Sigma(R=5\,\mathrm{kpc})$'
                        +'\n'
                        +r'$\Sigma(R=11\,\mathrm{kpc})$',
                        bottom_left=True,size=14.)
    bovy_plot.bovy_plot([2.575,2.8],[0.15,0.31],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot([2.625,2.95],[0.06,0.1525],'-',color='0.5',overplot=True)
    #overplot actual gridpoints
    gridrds= numpy.linspace(2.,3.4,8)
    gridfhs= numpy.linspace(0.,1.,16)
    for ii in range(len(gridrds)):
        bovy_plot.bovy_plot(gridrds[ii]+numpy.zeros(len(gridfhs)),
                            gridfhs,
                            's',
                            color='w',ms=3.,overplot=True,
                            markeredgecolor='none')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Ejemplo n.º 7
0
def plotMAPMassScaleLength(plotfilename):
    #First calculate the mass-weighted scale length
    fehs= monoAbundanceMW.fehs()
    afes= monoAbundanceMW.afes()
    #Load the samples of masses and scale lengths
    #Savefile
    denssamplesfile= '../fits/pixelFitG_DblExp_BigPix0.1_1000samples.sav'
    masssamplesfile= '../fits/pixelFitG_Mass_DblExp_BigPix0.1_simpleage_1000samples.sav'
    if os.path.exists(denssamplesfile):
        savefile= open(denssamplesfile,'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
        denserrors= True
    else:
        raise IOError("%s file with density samples does not exist" % denssamplesfile)
    if os.path.exists(masssamplesfile):
        savefile= open(masssamplesfile,'rb')
        masssamples= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("%s file with mass samples does not exist" % masssamplesfile)
    #Load the relative distance factors
    options= setup_options(None)
    raw= read_rawdata(options)
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Get fehs from monoAb
    distfac= numpy.zeros_like(fehs)
    for ii in range(len(fehs)):
        #Get the relevant data
        data= binned(fehs[ii],afes[ii])
        distfac[ii]= AnDistance.AnDistance(data.dered_g-data.dered_r,
                                           data.feh)
    nsamples= 100
    rs= numpy.linspace(2.,11.5,101)
    rds= numpy.zeros((101,nsamples))
    rndindx= numpy.random.permutation(len(masssamples[108]))[0:nsamples]
    for jj in range(nsamples):
        hrs= numpy.zeros_like(fehs)
        mass= numpy.zeros_like(fehs)
        kk, ii= 0, 0
        while kk < len(denssamples):
            if denssamples[kk] is None: 
                kk+= 1
                continue
            hrs[ii]= numpy.exp(denssamples[kk][rndindx[jj]][0])*distfac[ii]*8.
            mass[ii]= masssamples[kk][rndindx[jj]] 
            ii+= 1
            kk+= 1
        #hrs[hrs > 3.5]= 3.5
        #Effective density profile
        tdens= numpy.zeros_like(rs)
        mass/= numpy.sum(mass)
        for ii in range(len(rs)):
            tdens[ii]= numpy.sum(mass*numpy.exp(-(rs[ii]-8.)/hrs))
        tdens= numpy.log(tdens)
        rds[:,jj]= -(rs[1]-rs[0])/(numpy.roll(tdens,-1)-tdens)
        #for ii in range(len(rs)):
        #    rds[ii,jj]= numpy.exp(numpy.sum(numpy.log(hrs)*mass*numpy.exp(-(rs[ii]-8.)/hrs))/numpy.sum(mass*numpy.exp(-(rs[ii]-8.)/hrs)))
    rds= rds[:-1,:]
    rs= rs[:-1]
    #Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(rs,numpy.median(rds,axis=1),'k-',
                        xrange=[0.,12.],
                        yrange=[0.,4.],
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$\mathrm{effective\ disk\ scale\ length\,(kpc)}$',
                        zorder=10)
    #Find 68 range at each r
    nsigs= 1
    rcsigs= numpy.zeros((len(rs),2*nsigs))
    fs= rds
    for ii in range(nsigs):
        for jj in range(len(rs)):
            thisf= sorted(fs[jj,:])
            thiscut= 0.5*special.erfc((ii+1.)/math.sqrt(2.))
            rcsigs[jj,2*ii]= thisf[int(math.floor(thiscut*nsamples))]
            thiscut= 1.-thiscut
            rcsigs[jj,2*ii+1]= thisf[int(math.floor(thiscut*nsamples))]
    colord, cc= (1.-0.75)/(nsigs+1.), 1
    nsigma= nsigs
    pyplot.fill_between(rs,rcsigs[:,0],rcsigs[:,1],color='0.75')
    while nsigma > 1:
        pyplot.fill_between(rs,rcsigs[:,cc+1],rcsigs[:,cc-1],
                            color='%f' % (.75+colord*cc))
        pyplot.fill_between(rs,rcsigs[:,cc],rcsigs[:,cc+2],
                            color='%f' % (.75+colord*cc))
        cc+= 2
        nsigma-= 1
    #pyplot.fill_between(rs,numpy.amin(rds,axis=1),numpy.amax(rds,axis=1),
    #                    color='0.50')
    pyplot.errorbar([7.],[2.15],
                    xerr=[2.],
                    yerr=[0.14],
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=15,
                    marker='o',color='k')
    bovy_plot.bovy_text(4.5,0.25,r'$\mathrm{Prediction\ from\ star\ counts}$'
                        +'\n'
                        +r'$\mathrm{Dynamical\ measurement}$',
                        size=14.,
                        ha='left')
    bovy_plot.bovy_plot([2.82,4.0],[0.53,0.53],'k-',overplot=True)
    pyplot.fill_between(numpy.array([2.8,4.0]),
                        numpy.array([0.45,0.45]),
                        numpy.array([0.61,0.61]),
                        color='0.75')
    pyplot.errorbar([3.5],[0.3],yerr=[0.1],xerr=[0.4],
                     color='k',marker='o',ls='none')
    bovy_plot.bovy_end_print(plotfilename)
Ejemplo n.º 8
0
def dfResultsTable(args):
    cmdline = "%python dfResultsTable.py " + args
    # Load g, k, and combined fits
    options = setup_options(None)
    options.sample = "g"
    options.select = "all"
    gfits = calcDFResults(options, [_GFIT])
    options.sample = "k"
    options.select = "program"
    kfits = calcDFResults(options, [_KFIT])
    options.sample = "gk"
    gkfits = calcDFResults(options, [_GFIT, _KFIT])
    # Set up sections
    names = [
        "$R_d\ (\mathrm{kpc})$",
        "$z_h\ (\mathrm{pc})$",
        "$V_{c,\mathrm{disk}}/V_c\,(R_0)$",
        "$V_{c,\mathrm{disk}}/V_c\,(2.2\,R_d)$",
        "$\\Sigma_{\mathrm{disk}}(R_0)\ (M_{\odot}\,\mathrm{pc}^{-2})$",
        "$M_{\mathrm{disk}}\ (10^{10}\,M_{\odot})$",
        "$\\alpha_{h}$",
        "$\\rho_{\mathrm{DM}}\,(R_0,0)\ (M_{\odot}\,\mathrm{pc}^{-3})$",
        "$V_c(R_0)\ (\mathrm{km\ s}^{-1})$",
        "$\\frac{\mathrm{d}\ln V_c}{\mathrm{d}\ln R}\,(R_0)$",
        "$\\rho_{\mathrm{total}}\,(R_0,0)\ (M_{\odot}\,\mathrm{pc}^{-3})$",
        "$\\Sigma(R_0,|Z|\leq 0.8\,\mathrm{kpc})\ (M_{\odot}\,\mathrm{pc}^{-2})$",
        "$\\Sigma(R_0,|Z|\leq 1.1\,\mathrm{kpc})\ (M_{\odot}\,\mathrm{pc}^{-2})$",
    ]
    skip = [0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0]  # 1 if line skip after this parameter
    scale = [_REFR0, _REFR0 * 1000.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
    key = [
        "rdexp",
        "zhexp",
        "vcdvcro",
        "vcdvc",
        "surfzdisk",
        "massdisk",
        "plhalo",
        "rhodm",
        "vc",
        "dlnvcdlnr",
        "rhooalt",
        "surfz800",
        "surfz",
    ]
    # Make table
    outfile = open(args, "w")
    for ii in range(len(names)):
        # Set up line
        printline = names[ii]
        # G
        printline += " & "
        bestfit = gfits[key[ii] + "_m"] * scale[ii]
        err = gfits[key[ii] + "_merr"] * scale[ii]
        # Prepare
        if math.log10(err) >= 0.0:
            value = "$%.0f$" % bestfit
            err = "$\pm$%.0f" % err
        elif math.log10(err) >= -1.0:
            value = "$%.1f$" % bestfit
            err = "$\pm$%.1f" % err
        elif math.log10(err) >= -2.0:
            value = "$%.2f$" % bestfit
            err = "$\pm$%.2f" % err
        elif math.log10(err) >= -3.0:
            value = "$%.3f$" % bestfit
            err = "$\pm$%.3f" % err
        else:
            value = "$%.4f$" % bestfit
            err = "$\pm$%.4f" % err
        printline += value + "&" + err
        # K
        printline += " & "
        bestfit = kfits[key[ii] + "_m"] * scale[ii]
        err = kfits[key[ii] + "_merr"] * scale[ii]
        # Prepare
        if math.log10(err) >= 0.0:
            value = "$%.0f$" % bestfit
            err = "$\pm$%.0f" % err
        elif math.log10(err) >= -1.0:
            value = "$%.1f$" % bestfit
            err = "$\pm$%.1f" % err
        elif math.log10(err) >= -2.0:
            value = "$%.2f$" % bestfit
            err = "$\pm$%.2f" % err
        elif math.log10(err) >= -3.0:
            value = "$%.3f$" % bestfit
            err = "$\pm$%.3f" % err
        else:
            value = "$%.4f$" % bestfit
            err = "$\pm$%.4f" % err
        printline += value + "&" + err
        # combined
        printline += " & "
        bestfit = gkfits[key[ii] + "_m"] * scale[ii]
        err = gkfits[key[ii] + "_merr"] * scale[ii]
        # Prepare
        if math.log10(err) >= 0.0:
            value = "$%.0f$" % bestfit
            err = "$\pm$%.0f" % err
        elif math.log10(err) >= -1.0:
            value = "$%.1f$" % bestfit
            err = "$\pm$%.1f" % err
        elif math.log10(err) >= -2.0:
            value = "$%.2f$" % bestfit
            err = "$\pm$%.2f" % err
        elif math.log10(err) >= -3.0:
            value = "$%.3f$" % bestfit
            err = "$\pm$%.3f" % err
        else:
            value = "$%.4f$" % bestfit
            err = "$\pm$%.4f" % err
        printline += value + "&" + err
        if not ii == (len(names) - 1):
            printline += "\\\\"
        if skip[ii]:
            printline += "\\\\"
            # Write the line
        outfile.write(printline + "\n")
    outfile.write("\\enddata\n")
    outfile.write(cmdline + "\n")
    outfile.close()