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)
Exemple #2
0
def fakeSlopesFig1(options,args):
    #Read data for bins
    raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    binned= pixelAfeFeh(raw,dfeh=_DFEH,dafe=_DAFE)#these dfehs are binsizes
    tightbinned= pixelAfeFeh(raw,dfeh=_DFEH,dafe=_DAFE,
                             fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                             afemax=0.55)
    plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if len(data) < _MINNDATA:
                plotthis[ii,jj]= numpy.nan
                continue
            plotthis[ii,jj]= calcSlope(tightbinned.feh(ii),tightbinned.afe(jj),
                                       options.dfeh,options.dafe,options)
    vmin, vmax= -5.,5.
    zlabel= r'$\frac{\mathrm{d} \sigma_z(z_{1/2})}{\mathrm{d} z}\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    xrange=[-1.6,0.5]
    yrange=[-0.05,0.55]
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          zlabel=zlabel,
                          xrange=xrange,yrange=yrange,
                          vmin=vmin,vmax=vmax,
                          contours=False,
                          colorbar=True,shrink=0.78)
    bovy_plot.bovy_text(r'$\delta_{[\mathrm{Fe/H}]} = %.2f$' % options.dfeh
                        +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]} = %.2f$' % options.dafe,
                        top_right=True,size=18.)
    bovy_plot.bovy_end_print(options.plotfile)
Exemple #3
0
def plotMass(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        mass= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        mass= []
        ii, jj= 0, 0
    #parameters
    if os.path.exists(args[1]):#Load initial
        savefile= open(args[1],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    else:
        print "Error: must provide parameters of best fits"
        print "Returning ..."
        return None
    #Mass uncertainties are in savefile3
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        masssamples= pickle.load(savefile)
        savefile.close()
        masserrors= True
    else:
        masssamples= None
        masserrors= False
    if len(args) > 3 and os.path.exists(args[3]): #Load savefile
        savefile= open(args[3],'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
        denserrors= True
    else:
        denssamples= None
        denserrors= False
    if len(args) > 4 and os.path.exists(args[4]):#Load savefile
        savefile= open(args[4],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
        velfitsLoaded= True
    else:
        velfitsLoaded= False
    if len(args) > 5 and os.path.exists(args[5]):
        savefile= open(args[5],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
        velerrors= True
    else:
        velsamples= None            
        velerrors= False
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    if denserrors: errors= []
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(fits):
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            thismass= mass[afeindx+fehindx*binned.npixafe()]
            if masserrors:
                thismasssamples= masssamples[afeindx+fehindx*binned.npixafe()]
            else:
                thismasssamples= None
            thisfit= fits[afeindx+fehindx*binned.npixafe()]
            if denserrors:
                thisdenssamples= denssamples[afeindx+fehindx*binned.npixafe()]
            else:
                thisdenssamples= None
            if velfitsLoaded:
                thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            if velerrors:
                thisvelsamples= velsamples[afeindx+fehindx*binned.npixafe()]
            if thisfit is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if options.type == 'mass':
                if not options.distzmin is None or not options.distzmax is None:
                    if options.distzmin is None and not options.distzmax is None:
                        thismass*= (1.-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.))
                    elif not options.distzmin is None and options.distzmax is None:
                        thismass*= numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)
                    else:
                        thismass*= (numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.))
                if options.logmass:
                    plotthis[ii,jj]= numpy.log10(thismass/10**6.)
                else:
                    plotthis[ii,jj]= thismass/10**6.
            elif options.type == 'nstars':
                if options.logmass:
                    plotthis[ii,jj]= numpy.log10(len(data))
                else:
                    plotthis[ii,jj]= len(data)
            elif options.model.lower() == 'hwr':
                if options.type == 'hz':
                    plotthis[ii,jj]= numpy.exp(thisfit[0])*1000.
                elif options.type == 'hr':
                    plotthis[ii,jj]= numpy.exp(thisfit[1])
                elif options.type.lower() == 'afe' \
                        or options.type.lower() == 'feh' \
                        or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    plotthis.append([tightbinned.feh(ii),
                                         tightbinned.afe(jj),
                                     numpy.exp(thisfit[0])*1000.,
                                     numpy.exp(thisfit[1]),
                                     len(data),
                                     thismass/10.**6.,
                                     thismasssamples])
                    if denserrors:
                        theseerrors= []
                        thesesamples= denssamples[afeindx+fehindx*binned.npixafe()]
                        if options.model.lower() == 'hwr':
                            for kk in [0,1]:
                                xs= numpy.array([s[kk] for s in thesesamples])
                                theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                        errors.append(theseerrors)
                    if velfitsLoaded:
                        if options.velmodel.lower() == 'hwr':
                            plotthis[-1].extend([numpy.exp(thisvelfit[1]),
                                                 numpy.exp(thisvelfit[4]),
                                                 thisvelfit[2],
                                                 thisvelfit[3]])
                            if velerrors:
                                theseerrors= []
                                thesesamples= velsamples[afeindx+fehindx*binned.npixafe()]
                                for kk in [1,4]:
                                    xs= numpy.array([s[kk] for s in thesesamples])
                                    theseerrors.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                                xs= numpy.array([s[4] for s in thesesamples])
                                theseerrors.append(0.5*(numpy.exp(-numpy.mean(xs))-numpy.exp(numpy.mean(-xs)-numpy.std(-xs))-numpy.exp(numpy.mean(-xs))+numpy.exp(numpy.mean(-xs)+numpy.std(-xs))))
                                errors[-1].extend(theseerrors)
    #Set up plot
    #print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    if options.type == 'mass':
        if options.logmass:
            vmin, vmax= numpy.log10(0.01), numpy.log10(2.)
            zlabel=r'$\log_{10} \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
        else:
            vmin, vmax= 0.,1.
            zlabel=r'$\Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
            if not options.distzmin is None or not options.distzmax is None:
                vmin, vmax= None, None
        title=r'$\mathrm{mass\ weighted}$'
    elif options.type == 'nstars':
        if options.logmass:
            vmin, vmax= 2., 3.
            zlabel=r'$\log_{10} \mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$'
        else:
            vmin, vmax= 100.,1000.
            zlabel=r'$\mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$'
        title= r'$\mathrm{raw\ sample\ counts}$'
    elif options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.5,0.
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.6]
        yrange=[-0.1,0.6]
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        #Gather hR and hz
        sz_err, sz, hz_err, hr_err, mass_err, mass, hz, hr,afe, feh, ndata= [], [], [], [], [], [], [], [], [], [], []
        for ii in range(len(plotthis)):
            if denserrors:
                hz_err.append(errors[ii][0]*1000.)
                hr_err.append(errors[ii][1])
            mass.append(plotthis[ii][5])
            hz.append(plotthis[ii][2])
            hr.append(plotthis[ii][3])
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][4])
            if velfitsLoaded:
                sz.append(plotthis[ii][7])
            if velerrors:
                sz_err.append(errors[ii][2])
            if masserrors:
                mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.))
                
                """
                if options.logmass:
                    mass_err.append(numpy.std(numpy.log10(numpy.array(plotthis[ii][6])/10.**6.)))
                else:
                    mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.))
                """
        if denserrors:
            hz_err= numpy.array(hz_err)
            hr_err= numpy.array(hr_err)
        if velfitsLoaded:
            sz= numpy.array(sz)
        if velerrors:
            sz_err= numpy.array(sz_err)
        mass= numpy.array(mass)
        if masserrors:
            mass_err= numpy.array(mass_err)
        hz= numpy.array(hz)
        hr= numpy.array(hr)
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata))
        #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        xrange= [150,1200]
        if options.cumul:
            #Print total surface mass and uncertainty
            totmass= numpy.sum(mass)
            if options.ploterrors:
                toterr= numpy.sqrt(numpy.sum(mass_err**2.))
            else:
                toterr= 0.
            print "Total surface-mass density: %4.1f +/- %4.2f" %(totmass,toterr)
            ids= numpy.argsort(hz)
            plotc= plotc[ids]
            ndata= ndata[ids]
            mass= mass[ids]
            mass= numpy.cumsum(mass)
            hz.sort()
            ylabel=r'$\mathrm{cumulative}\ \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
            if options.logmass:
                yrange= [0.01,30.]
            else:
                yrange= [-0.1,30.]
        else:
            if options.logmass:
                yrange= [0.005*0.13/.07,10.*.13/.07]
            else:
                yrange= [-0.1,10.*.13/.07]
            ylabel=r'$\Sigma_{R_0}(h_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
        if not options.vstructure and not options.hzhr:
            if options.hr:
                ploth= hr
                plotherr= hr_err
                xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$'
                xrange= [1.2,4.]
                bins= 11
            elif options.sz:
                ploth= sz**2.
                plotherr= 2.*sz_err*sz
                xlabel=r'$\sigma_z^2\ \mathrm{[km}^2\ \mathrm{s}^{-2}]$'
                xrange= [12.**2.,50.**2.]
                ylabel=r'$\Sigma_{R_0}(\sigma^2_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
                bins= 9
            else:
                ploth= hz
                plotherr= hz_err
                xlabel=r'$\mathrm{vertical\ scale\ height}\ h_z\ \mathrm{[pc]}$'
                xrange= [165,1200]
                bins= 12
            bovy_plot.bovy_plot(ploth,mass*.13/0.07,
                                s=ndata,c=plotc,
                                cmap='jet',
                                xlabel=xlabel,
                                ylabel=ylabel,
                                clabel=zlabel,
                                xrange=xrange,yrange=yrange,
                                vmin=vmin,vmax=vmax,
                                scatter=True,edgecolors='none',
                                colorbar=True,zorder=2,
                                semilogy=options.logmass)
            if not options.cumul and masserrors and options.ploterrors:
                colormap = cm.jet
                for ii in range(len(hz)):
                    pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,
                                    yerr=mass_err[ii]*.13/0.07,
                                    color=colormap(_squeeze(plotc[ii],
                                                            numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                            numpy.amin([vmax,
                                                                        numpy.amax(plotc)]))),
                                    elinewidth=1.,capsize=3,zorder=0)
            if not options.cumul and denserrors and options.ploterrors:
                colormap = cm.jet
                for ii in range(len(hz)):
                    pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,xerr=plotherr[ii],
                                    color=colormap(_squeeze(plotc[ii],
                                                            numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                            numpy.amin([vmax,
                                                                        numpy.amax(plotc)]))),
                                    elinewidth=1.,capsize=3,zorder=0)
            #Add binsize label
            bovy_plot.bovy_text(r'$\mathrm{points\ use}\ \Delta [\mathrm{Fe/H}] = 0.1,$'+'\n'+r'$\Delta [\alpha/\mathrm{Fe}] = 0.05\ \mathrm{bins}$',
                                bottom_left=True)
            #Overplot histogram
            #ax2 = pyplot.twinx()
            pyplot.hist(ploth,range=xrange,weights=mass*0.13/0.07,color='k',histtype='step',
                        bins=bins,lw=3.,zorder=10)
            #Also XD?
            if options.xd:
                #Set up data
                ydata= numpy.zeros((len(hz),1))
                if options.sz:
                    ydata[:,0]= numpy.log(sz)
                else:
                    ydata[:,0]= numpy.log(hz)
                ycovar= numpy.zeros((len(hz),1))
                if options.sz:
                    ycovar[:,0]= sz_err**2./sz**2.
                else:
                    ycovar[:,0]= hz_err**2./hz**2.
                #Set up initial conditions
                xamp= numpy.ones(options.k)/float(options.k)
                xmean= numpy.zeros((options.k,1))
                for kk in range(options.k):
                    xmean[kk,:]= numpy.mean(ydata,axis=0)\
                        +numpy.random.normal()*numpy.std(ydata,axis=0)
                xcovar= numpy.zeros((options.k,1,1))
                for kk in range(options.k):
                    xcovar[kk,:,:]= numpy.cov(ydata.T)
                #Run XD
                print extreme_deconvolution(ydata,ycovar,xamp,xmean,xcovar,
                                      weight=mass)*len(hz)
                print xamp, xmean, xcovar
                #Plot
                xs= numpy.linspace(xrange[0],xrange[1],1001)
                xdys= numpy.zeros(len(xs))
                for kk in range(options.k):
                    xdys+= xamp[kk]/numpy.sqrt(2.*numpy.pi*xcovar[kk,0,0])\
                        *numpy.exp(-0.5*(numpy.log(xs)-xmean[kk,0])**2./xcovar[kk,0,0])
                xdys/= xs
                bovy_plot.bovy_plot(xs,xdys,'-',color='0.5',overplot=True)
#            ax2.set_yscale('log')
#            ax2.set_yticklabels('')        
#            if options.hr:
#                pyplot.ylim(10**-2.,10.**0.)
#            if options.sz:
#                pyplot.ylim(10**-5.,10.**-2.5)
#            else:
#                pyplot.ylim(10**-5.5,10.**-1.5)
#            pyplot.xlim(xrange[0],xrange[1])
            ax= pyplot.gca()
            if options.sz:
                def my_formatter(x, pos):
                    """s^2"""
                    xs= int(round(math.sqrt(x)))
                    return r'$%i^2$' % xs
                major_formatter = FuncFormatter(my_formatter)
                ax.xaxis.set_major_formatter(major_formatter)
            xstep= ax.xaxis.get_majorticklocs()
            xstep= xstep[1]-xstep[0]
            ax.xaxis.set_minor_locator(MultipleLocator(xstep/5.))
        elif options.hzhr:
            #Make density plot in hR and hz
            bovy_plot.scatterplot(hr,hz,'k,',
                                  levels=[1.01],#HACK such that outliers aren't plotted
                                  cmap='gist_yarg',
                                  bins=11,
                                  xrange=[1.,7.],
                                  yrange=[150.,1200.],
                                  ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$',
                                  xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$',
                                  onedhists=False,
                                  weights=mass)
        else:
            #Make an illustrative plot of the vertical structure
            nzs= 1001
            zs= numpy.linspace(200.,3000.,nzs)
            total= numpy.zeros(nzs)
            for ii in range(len(hz)):
                total+= mass[ii]/2./hz[ii]*numpy.exp(-zs/hz[ii])
            bovy_plot.bovy_plot(zs,total,color='k',ls='-',lw=3.,
                                semilogy=True,
                                xrange=[0.,3200.],
                                yrange=[0.000001,0.02],
                                xlabel=r'$\mathrm{vertical\ height}\ Z$',
                                ylabel=r'$\rho_*(R=R_0,Z)\ [\mathrm{M}_\odot\ \mathrm{pc}^{-3}]$',
                                zorder=10)
            if options.vbinned:
                #Bin
                mhist, edges= numpy.histogram(hz,range=xrange,
                                              weights=mass,bins=10)
                stotal= numpy.zeros(nzs)
                for ii in range(len(mhist)):
                    hz= (edges[ii+1]+edges[ii])/2.
                    if options.vcumul:
                        if ii == 0.:
                            pstotal= numpy.zeros(nzs)+0.0000001
                        else:
                            pstotal= copy.copy(stotal)
                        stotal+= mhist[ii]/2./hz*numpy.exp(-zs/hz)
                        pyplot.fill_between(zs,stotal,pstotal,
                                            color='%.6f' % (0.25+0.5/(len(mhist)-1)*ii))
                    else:
                        bovy_plot.bovy_plot([zs[0],zs[-1]],
                                            1.*numpy.array([mhist[ii]/2./hz*numpy.exp(-zs[0]/hz),
                                                            mhist[ii]/2./hz*numpy.exp(-zs[-1]/hz)]),
                                            color='0.5',ls='-',overplot=True,
                                            zorder=0)
            else:
                colormap = cm.jet
                for ii in range(len(hz)):
                    bovy_plot.bovy_plot([zs[0],zs[-1]],
                                        100.*numpy.array([mass[ii]/2./hz[ii]*numpy.exp(-zs[0]/hz[ii]),
                                                          mass[ii]/2./hz[ii]*numpy.exp(-zs[-1]/hz[ii])]),
                                        ls='-',overplot=True,alpha=0.5,
                                        zorder=0,
                                        color=colormap(_squeeze(plotc[ii],
                                                                numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                                numpy.amin([vmax,
                                                                            numpy.amax(plotc)]))))
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              onedhists=True,
                              contours=False)
        bovy_plot.bovy_text(title,top_right=True,fontsize=16)
        if not options.distzmin is None or not options.distzmax is None:
            if options.distzmin is None:
                distlabel= r'$|Z| < %i\ \mathrm{pc}$' % int(options.distzmax)
            elif options.distzmax is None:
                distlabel= r'$|Z| > %i\ \mathrm{pc}$' % int(options.distzmin)
            else:
                distlabel= r'$%i < |Z| < %i\ \mathrm{pc}$' % (int(options.distzmin),int(options.distzmax))
            bovy_plot.bovy_text(distlabel,bottom_left=True,fontsize=16)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
Exemple #4
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)
Exemple #5
0
def pixelFitVel(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
    if not options.bmin is None:
        #Cut on |b|
        raw= raw[(numpy.fabs(raw.b) > options.bmin)]
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        fits= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        fits= []
        ii, jj= 0, 0
    #Sample?
    if options.mcsample:
        if ii < len(binned.fehedges)-1 and jj < len(binned.afeedges)-1:
            print "First do all of the fits ..."
            print "Returning ..."
            return None
        if os.path.exists(args[1]): #Load savefile
            savefile= open(args[1],'rb')
            samples= pickle.load(savefile)
            ii= pickle.load(savefile)
            jj= pickle.load(savefile)
            savefile.close()
        else:
            samples= []
            ii, jj= 0, 0
    #Model
    if options.model.lower() == 'hwr':
        like_func= _HWRLikeMinus
        pdf_func= _HWRLike
        step= [0.01,0.3,0.3,0.3,0.3]
        create_method=['full','step_out','step_out',
                       'step_out','step_out']
        isDomainFinite=[[True,True],[True,True],
                        [True,True],[True,True],
                        [False,True]]
        domain=[[0.,1.],[-10.,10.],[-100.,100.],[-100.,100.],
                [0.,4.6051701859880918]]
    elif options.model.lower() == 'hwrrz':
        like_func= _HWRRZLikeMinus
        pdf_func= _HWRRZLike
        step= [0.01,0.3,0.3,0.3,0.3,
               0.3,0.3,0.3,0.3,
               0.3,0.3,0.3]
        create_method=['full',
                       'step_out','step_out',
                       'step_out','step_out',
                       'step_out','step_out',
                       'step_out','step_out',
                       'step_out','step_out']
#                       'step_out']
        isDomainFinite=[[True,True],
                        [True,True],[True,True],[True,True],[False,True],
                        [True,True],[True,True],[True,True],[False,True],
                        [True,True],[True,True]]#,[True,True]]
        domain=[[0.,1.],
                [-10.,10.],[-100.,100.],[-100.,100.],[0.,4.6051701859880918],
                [-10.,10.],[-100.,100.],[-100.,100.],[0.,4.6051701859880918],
                [-2.,2.],[-10.,10.]]#,[-100.,100.]]
    elif options.model.lower() == 'isotherm':
        like_func= _IsothermLikeMinus
        pdf_func= _IsothermLike
        step= [0.01,0.05,0.3]
        create_method=['full','step_out','step_out']
        isDomainFinite=[[True,True],[False,False],
                        [False,True]]
        domain=[[0.,1.],[0.,0.],[0.,4.6051701859880918]]
    #Run through the bins
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                if options.mcsample: samples.append(None)
                else: fits.append(None)
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            print binned.feh(ii), binned.afe(jj), len(data)
            #Create XYZ and R, vxvyvz, cov_vxvyvz
            R= ((8.-data.xc)**2.+data.yc**2.)**0.5
            #Confine to R-range?
            if not options.rmin is None and not options.rmax is None:
                dataindx= (R >= options.rmin)*\
                    (R < options.rmax)
                data= data[dataindx]
                R= R[dataindx]
            XYZ= numpy.zeros((len(data),3))
            XYZ[:,0]= data.xc
            XYZ[:,1]= data.yc
            XYZ[:,2]= data.zc+_ZSUN
            if options.pivotmean:
                d= numpy.fabs((XYZ[:,2]-numpy.mean(numpy.fabs(XYZ[:,2]))))
            else:
                d= numpy.fabs((XYZ[:,2]-numpy.median(numpy.fabs(XYZ[:,2]))))
            vxvyvz= numpy.zeros((len(data),3))
            vxvyvz[:,0]= data.vxc
            vxvyvz[:,1]= data.vyc
            vxvyvz[:,2]= data.vzc
            cov_vxvyvz= numpy.zeros((len(data),3,3))
            cov_vxvyvz[:,0,0]= data.vxc_err**2.
            cov_vxvyvz[:,1,1]= data.vyc_err**2.
            cov_vxvyvz[:,2,2]= data.vzc_err**2.
            cov_vxvyvz[:,0,1]= data.vxvyc_rho*data.vxc_err*data.vyc_err
            cov_vxvyvz[:,0,2]= data.vxvzc_rho*data.vxc_err*data.vzc_err
            cov_vxvyvz[:,1,2]= data.vyvzc_rho*data.vyc_err*data.vzc_err
            if options.vr or options.vrz:
                #Rotate vxvyvz to vRvTvz
                cosphi= (8.-XYZ[:,0])/R
                sinphi= XYZ[:,1]/R
                vR= -vxvyvz[:,0]*cosphi+vxvyvz[:,1]*sinphi
                vT= vxvyvz[:,0]*sinphi+vxvyvz[:,1]*cosphi
                #Subtract mean vR
                vR-= numpy.mean(vR)
                vxvyvz[:,0]= vR               
                vxvyvz[:,1]= vT
                for rr in range(len(XYZ[:,0])):
                    rot= numpy.array([[cosphi[rr],sinphi[rr]],
                                      [-sinphi[rr],cosphi[rr]]])
                    sxy= cov_vxvyvz[rr,0:2,0:2]
                    sRT= numpy.dot(rot,numpy.dot(sxy,rot.T))
                    cov_vxvyvz[rr,0:2,0:2]= sRT
            #Fit this data
            #Initial condition
            if options.model.lower() == 'hwr':
                params= numpy.array([0.02,numpy.log(30.),0.,0.,numpy.log(6.)])
            elif options.model.lower() == 'hwrrz':
                params= numpy.array([0.02,numpy.log(30.),0.,0.,numpy.log(6.),
                                     numpy.log(30.),0.,0.,numpy.log(6.),
                                     0.2,0.])#,0.])
            elif options.model.lower() == 'isotherm':
                params= numpy.array([0.02,numpy.log(30.),numpy.log(6.)])
            if not options.mcsample:
                #Optimize likelihood
                params= optimize.fmin_powell(like_func,params,
                                             args=(XYZ,vxvyvz,cov_vxvyvz,R,d,
                                                   options.vr,options.vrz))
                if options.chi2:
                    #Calculate chi2 and chi2/dof
                    chi2, dof= like_func(params,XYZ,vxvyvz,cov_vxvyvz,R,d,options.vr,options.vrz,
                                    chi2=True)
                    dof-= len(params)
                    params.resize(len(params)+2)
                    params[-2]= chi2
                    params[-1]= chi2/dof
                print numpy.exp(params)
                fits.append(params)
            else:
                #Load best-fit params
                params= fits[jj+ii*binned.npixafe()]
                print numpy.exp(params)
                thesesamples= bovy_mcmc.markovpy(params,
                #thesesamples= bovy_mcmc.slice(params,
                                                 #step,
                                                 0.01,
                                                 pdf_func,
                                                 (XYZ,vxvyvz,cov_vxvyvz,R,d,
                                                  options.vr),#options.vrz),
                                                 #create_method=create_method,
                                                 isDomainFinite=isDomainFinite,
                                                 domain=domain,
                                                 nsamples=options.nsamples)
                #Print some helpful stuff
                printthis= []
                for kk in range(len(params)):
                    xs= numpy.array([s[kk] for s in thesesamples])
                    printthis.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                print printthis
                samples.append(thesesamples)               
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
            if options.mcsample: save_pickles(args[1],samples,ii,jj)
            else: save_pickles(args[0],fits,ii,jj)
            if jj == 0: #this means we've reset the counter 
                break
    if options.mcsample: save_pickles(args[1],samples,ii,jj)
    else: save_pickles(args[0],fits,ii,jj)
    return None
def plotDensComparisonDFMulti(options, args):
    # Read data etc.
    print "Reading the data ..."
    raw = read_rawdata(options)
    # Bin the data
    binned = pixelAfeFeh(raw, dfeh=options.dfeh, dafe=options.dafe)
    # Map the bins with ndata > minndata in 1D
    fehs, afes = [], []
    for ii in range(len(binned.fehedges) - 1):
        for jj in range(len(binned.afeedges) - 1):
            data = binned(binned.feh(ii), binned.afe(jj))
            if len(data) < options.minndata:
                continue
            # print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins = len(fehs)
    fehs = numpy.array(fehs)
    afes = numpy.array(afes)
    gafes, gfehs, left_legend = getMultiComparisonBins(options)
    if options.usemedianpotential:
        potparams = get_median_potential(options, nabundancebins)
        print "Median potential parameters: ", potparams
    # Setup everything for the selection function
    print "Setting up stuff for the normalization integral ..."
    normintstuff = setup_normintstuff(options, raw, binned, fehs, afes)
    M = len(gfehs)
    # Check whether fits exist, if not, pop
    removeBins = numpy.ones(M, dtype="bool")
    for jj in range(M):
        # Find pop corresponding to this bin
        pop = numpy.argmin((gfehs[jj] - fehs) ** 2.0 / 0.1 + (gafes[jj] - afes) ** 2.0 / 0.0025)
        # Load savefile
        if not options.init is None:
            # Load initial parameters from file
            savename = options.init
            spl = savename.split(".")
            newname = ""
            for ll in range(len(spl) - 1):
                newname += spl[ll]
                if not ll == len(spl) - 2:
                    newname += "."
            newname += "_%i." % pop
            newname += spl[-1]
            if not os.path.exists(newname):
                removeBins[jj] = False
        else:
            raise IOError("base filename not specified ...")
    if numpy.sum(removeBins) == 0:
        raise IOError("None of the group bins have been fit ...")
    elif numpy.sum(removeBins) < M:
        # Some bins have not been fit yet, and have to be removed
        gfehs = list((numpy.array(gfehs))[removeBins])
        gafes = list((numpy.array(gafes))[removeBins])
        print "Only using %i bins out of %i ..." % (numpy.sum(removeBins), M)
        M = len(gfehs)
    model1s = []
    model2s = []
    model3s = []
    params1 = []
    params2 = []
    params3 = []
    data = []
    colordists = []
    fehdists = []
    fehmins = []
    fehmaxs = []
    cfehs = []
    for jj in range(M):
        print "Working on group %i / %i ..." % (jj + 1, M)
        # Find pop corresponding to this bin
        pop = numpy.argmin((gfehs[jj] - fehs) ** 2.0 / 0.1 + (gafes[jj] - afes) ** 2.0 / 0.0025)
        # Load savefile
        if not options.init is None:
            # Load initial parameters from file
            savename = options.init
            spl = savename.split(".")
            newname = ""
            for ll in range(len(spl) - 1):
                newname += spl[ll]
                if not ll == len(spl) - 2:
                    newname += "."
            newname += "_%i." % pop
            newname += spl[-1]
            savefile = open(newname, "rb")
            tparams = pickle.load(savefile)
            savefile.close()
        else:
            raise IOError("base filename not specified ...")
        if options.usemedianpotential:
            tparams = set_potparams(potparams, tparams, options, 1)
        print tparams
        # Set up density models and their parameters
        model1s.append(interpDens)
        paramsInterp, surfz = calc_model(tparams, options, 0, _retsurfz=True)
        params1.append(paramsInterp)
        if True:
            # Add outlier and plot sum
            if not options.usemedianpotential:
                potparams = get_potparams(tparams, options, 1)
            logoutfrac = numpy.log(get_outfrac(tparams, 0, options))
            logoutfrac += numpy.log(surfz)
            outfrac = numpy.exp(logoutfrac)
            ro = get_ro(tparams, options)
            halodens = ro * outDens(1.0, 0.0, None)
            model2s.append(interpDenswoutlier)
            params2.append([paramsInterp, outfrac * halodens])
            model3s.append(None)
            params3.append(None)
        elif False:
            if not options.usemedianpotential:
                potparams = get_potparams(tparams, options, 1)
            if options.potential.lower() == "flatlog":
                tparams = set_potparams([potparams[0] * 1.05, potparams[1]], tparams, options, 1)
                model2s.append(interpDens)
                params2.append(calc_model(tparams, options, 0))
                tparams = set_potparams([potparams[0] * 0.95, potparams[1]], tparams, options, 1)
                model3s.append(interpDens)
                params3.append(calc_model(tparams, options, 0))
            elif options.potential.lower() == "mwpotentialfixhalo":
                tparams = set_potparams(
                    [numpy.log(2.0 / _REFR0), potparams[1], potparams[2], potparams[3], potparams[4]],
                    tparams,
                    options,
                    1,
                )
                model2s.append(interpDens)
                params2.append(calc_model(tparams, options, 0))
                tparams = set_potparams(
                    [numpy.log(3.0 / 8.0), potparams[1], potparams[2], potparams[3], potparams[4]], tparams, options, 1
                )
                model3s.append(interpDens)
                params3.append(calc_model(tparams, options, 0))
        else:
            model2s.append(None)
            params2.append(None)
            model3s.append(None)
            params3.append(None)
        data.append(binned(fehs[pop], afes[pop]))
        # Setup everything for selection function
        thisnormintstuff = normintstuff[pop]
        if _PRECALCVSAMPLES:
            sf, plates, platel, plateb, platebright, platefaint, grmin, grmax, rmin, rmax, fehmin, fehmax, feh, colordist, fehdist, gr, rhogr, rhofeh, mr, dmin, dmax, ds, surfscale, hr, hz, surfnrs, surfnzs, surfRgrid, surfzgrid, surfvrs, surfvts, surfvzs = unpack_normintstuff(
                thisnormintstuff, options
            )
        else:
            sf, plates, platel, plateb, platebright, platefaint, grmin, grmax, rmin, rmax, fehmin, fehmax, feh, colordist, fehdist, gr, rhogr, rhofeh, mr, dmin, dmax, ds, surfscale, hr, hz = unpack_normintstuff(
                thisnormintstuff, options
            )
        colordists.append(colordist)
        fehdists.append(fehdist)
        fehmins.append(fehmin)
        fehmaxs.append(fehmax)
        cfehs.append(feh)
        if True:
            # Cut out bright stars on faint plates and vice versa
            indx = []
            nfaintbright, nbrightfaint = 0, 0
            for ii in range(len(data[jj].feh)):
                if sf.platebright[str(data[jj][ii].plate)] and data[jj][ii].dered_r >= 17.8:
                    indx.append(False)
                    nbrightfaint += 1
                elif not sf.platebright[str(data[jj][ii].plate)] and data[jj][ii].dered_r < 17.8:
                    indx.append(False)
                    nfaintbright += 1
                else:
                    indx.append(True)
            print "nbrightfaint, nfaintbright", nbrightfaint, nfaintbright
            indx = numpy.array(indx, dtype="bool")
            if numpy.sum(indx) > 0:
                data[jj] = data[jj][indx]
    # Ranges
    if options.type == "z":
        xrange = [-0.1, 5.0]
    elif options.type == "R":
        xrange = [4.8, 14.2]
    elif options.type == "r":
        xrange = [14.2, 20.1]
    # We do bright/faint for 4 directions and all, all bright, all faint
    ls = [180, 180, 45, 45]
    bs = [0, 90, -23, 23]
    bins = 21
    # Set up comparison
    if options.type == "r":
        compare_func = compareDataModel.comparerdistPlateMulti
    elif options.type == "z":
        compare_func = compareDataModel.comparezdistPlateMulti
    elif options.type == "R":
        compare_func = compareDataModel.compareRdistPlateMulti
    # all, faint, bright
    bins = [31, 31, 31]
    plates = ["all", "bright", "faint"]
    for ii in range(len(plates)):
        plate = plates[ii]
        if plate == "all":
            thisleft_legend = left_legend
            #            thisright_legend= right_legend
            #            thisleft_legend= None
            thisright_legend = None
        else:
            thisleft_legend = None
            thisright_legend = None
        bovy_plot.bovy_print()
        compare_func(
            model1s,
            params1,
            sf,
            colordists,
            fehdists,
            data,
            plate,
            color="k",
            rmin=14.5,
            rmax=rmax,
            grmin=grmin,
            grmax=grmax,
            fehmin=fehmins,
            fehmax=fehmaxs,
            feh=cfehs,
            xrange=xrange,
            bins=bins[ii],
            ls="-",
            left_legend=thisleft_legend,
            right_legend=thisright_legend,
        )
        if not params2[0] is None:
            compare_func(
                model2s,
                params2,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins[ii],
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls="--",
            )
        if not params3[0] is None:
            compare_func(
                model3s,
                params3,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins[ii],
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls=":",
            )
        if options.type == "r":
            bovy_plot.bovy_end_print(args[0] + "model_data_g_" + options.group + "_" + plate + "." + options.ext)
        else:
            bovy_plot.bovy_end_print(
                args[0] + "model_data_g_" + options.group + "_" + options.type + "dist_" + plate + "." + options.ext
            )
        if options.all:
            return None
    bins = 16
    for ii in range(len(ls)):
        # Bright
        plate = compareDataModel.similarPlatesDirection(ls[ii], bs[ii], 20.0, sf, data, faint=False)
        bovy_plot.bovy_print()
        compare_func(
            model1s,
            params1,
            sf,
            colordists,
            fehdists,
            data,
            plate,
            color="k",
            rmin=14.5,
            rmax=rmax,
            grmin=grmin,
            grmax=grmax,
            fehmin=fehmins,
            fehmax=fehmaxs,
            feh=cfehs,
            xrange=xrange,
            bins=bins,
            ls="-",
        )
        if not params2[0] is None:
            compare_func(
                model2s,
                params2,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls="--",
            )
        if not params3[0] is None:
            compare_func(
                model3s,
                params3,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls=":",
            )
        if options.type == "r":
            bovy_plot.bovy_end_print(
                args[0] + "model_data_g_" + options.group + "_" + "l%i_b%i_bright." % (ls[ii], bs[ii]) + options.ext
            )
        else:
            bovy_plot.bovy_end_print(
                args[0]
                + "model_data_g_"
                + options.group
                + "_"
                + options.type
                + "dist_l%i_b%i_bright." % (ls[ii], bs[ii])
                + options.ext
            )
        # Faint
        plate = compareDataModel.similarPlatesDirection(ls[ii], bs[ii], 20.0, sf, data, bright=False)
        bovy_plot.bovy_print()
        compare_func(
            model1s,
            params1,
            sf,
            colordists,
            fehdists,
            data,
            plate,
            color="k",
            rmin=14.5,
            rmax=rmax,
            grmin=grmin,
            grmax=grmax,
            fehmin=fehmins,
            fehmax=fehmaxs,
            feh=cfehs,
            xrange=xrange,
            bins=bins,
            ls="-",
        )
        if not params2[0] is None:
            compare_func(
                model2s,
                params2,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls="--",
            )
        if not params3[0] is None:
            compare_func(
                model3s,
                params3,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls=":",
            )
        if options.type == "r":
            bovy_plot.bovy_end_print(
                args[0] + "model_data_g_" + options.group + "_" + "l%i_b%i_faint." % (ls[ii], bs[ii]) + options.ext
            )
        else:
            bovy_plot.bovy_end_print(
                args[0]
                + "model_data_g_"
                + options.group
                + "_"
                + options.type
                + "dist_l%i_b%i_faint." % (ls[ii], bs[ii])
                + options.ext
            )
    return None
Exemple #7
0
def resampleMags(raw,comps,options,args):
    #For each data point's line-of-sight and color and feh 
    #calculate the "thin" and "thick" distributions
    model_thick= _DblExpDensity
    model_thin= _DblExpDensity
    params_thick= numpy.array([numpy.log(options.hz_thick/1000.),
                               -numpy.log(options.hr_thick)])
    params_thin= numpy.array([numpy.log(options.hz_thin/1000.),
                              -numpy.log(options.hr_thin)])
    if options.allthin:
        params_thick= params_thin
    elif options.allthick:
        params_thin= params_thick 
   #Load sf
    sf= segueSelect(sample=options.sample,sn=True,
                    type_bright='tanhrcut',
                    type_faint='tanhrcut')
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    #Cut out bright stars on faint plates and vice versa
    cutbright= False
    if cutbright:
        indx= []
        for ii in range(len(raw.feh)):
            if sf.platebright[str(raw[ii].plate)] and raw[ii].dered_r >= 17.8:
                indx.append(False)
            elif not sf.platebright[str(raw[ii].plate)] and raw[ii].dered_r < 17.8:
                indx.append(False)
            else:
                indx.append(True)
        indx= numpy.array(indx,dtype='bool')
        raw= raw[indx]
        comps= comps[indx]
    #Loadthe data into the pixelAfeFeh structure
    raw= _append_field_recarray(raw,'comps',comps)
    binned= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05,fehmin=-1.6,
                        fehmax=0.5,afemin=-0.05,afemax=0.55)
    #Color
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
        rmax= 20.2
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
        rmax= 19.
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.5, 20.2
    ngr, nfeh, nrs= 2, 2, 201
    grs= numpy.linspace(grmin,grmax,ngr)
    rs= numpy.linspace(rmin,rmax,nrs)
    #Run through the bins
    ii, jj= 0, 0
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            rawIndx= binned.callIndx(binned.feh(ii),binned.afe(jj))
            if len(data) < 1:
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            #Set up feh and color
            feh= binned.feh(ii)
            fehrange= [binned.fehedges[ii],binned.fehedges[ii+1]]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            #Predict the r-distribution for all plates
            #Thick or thin?
            thick_amp= numpy.mean(data.comps)
            rdists_thin= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
            rdists_thick= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
            for pp in range(len(sf.plates)):
                sys.stdout.write('\r'+"Working on bin %i / %i: plate %i / %i" \
                                     % (ii*(len(binned.afeedges)-1)+jj+1,
                                        (len(binned.afeedges)-1)*(len(binned.fehedges)-1),pp+1,len(sf.plates))+'\r')
                sys.stdout.flush()
                rdists_thin[pp,:,:,:]= _predict_rdist_plate(rs,model_thin,
                                                            params_thin,
                                                            rmin,rmax,
                                                            platelb[pp,0],platelb[pp,1],
                                                            grmin,grmax,
                                                            fehrange[0],fehrange[1],feh,
                                                            colordist,
                                                            fehdist,sf,sf.plates[pp],
                                                            dontmarginalizecolorfeh=True,
                                                            ngr=ngr,nfeh=nfeh)
            
                rdists_thick[pp,:,:,:]= _predict_rdist_plate(rs,model_thick,
                                                             params_thick,
                                                             rmin,rmax,
                                                             platelb[pp,0],platelb[pp,1],
                                                             grmin,grmax,
                                                             fehrange[0],fehrange[1],feh,
                                                             colordist,
                                                             fehdist,sf,sf.plates[pp],
                                                             dontmarginalizecolorfeh=True,
                                                             ngr=ngr,nfeh=nfeh)
            rdists= thick_amp*rdists_thick+(1.-thick_amp)*rdists_thin
            rdists[numpy.isnan(rdists)]= 0.
            numbers= numpy.sum(rdists,axis=3)
            numbers= numpy.sum(numbers,axis=2)
            numbers= numpy.sum(numbers,axis=1)
            numbers= numpy.cumsum(numbers)
            numbers/= numbers[-1]
            rdists= numpy.cumsum(rdists,axis=1)
            for ww in range(len(sf.plates)):
                for ll in range(ngr):
                    for kk in range(nfeh):
                        if rdists[ww,-1,ll,kk] != 0.:
                            rdists[ww,:,ll,kk]/= rdists[ww,-1,ll,kk]
            #Now sample
            nout= 0
            while nout < len(data):
                #First sample a plate
                ran= numpy.random.uniform()
                kk= 0
                while numbers[kk] < ran: kk+= 1
                #plate==kk; now sample from the rdist of this plate
                ran= numpy.random.uniform()
                ll= 0
                #Find cc and ff for this data point
                cc= int(numpy.floor((data[nout].dered_g-data[nout].dered_r-colorrange[0])/(colorrange[1]-colorrange[0])*ngr))
                ff= int(numpy.floor((data[nout].feh-fehrange[0])/(fehrange[1]-fehrange[0])*nfeh))
                while rdists[kk,ll,cc,ff] < ran and ll < nrs-1: ll+= 1
                #r=ll
                oldgr= data.dered_g[nout]-data.dered_r[nout]
                oldr= data.dered_r[nout]
                data.dered_r[nout]= rs[ll]
                data.dered_g[nout]= oldgr+data.dered_r[nout]
                #Also change plate and l and b
                data.plate[nout]= sf.plates[kk]
                data.ra[nout]= sf.platestr.ra[kk]
                data.dec[nout]= sf.platestr.dec[kk]
                data.l[nout]= platelb[kk,0]
                data.b[nout]= platelb[kk,1]
                nout+= 1
            raw.dered_r[rawIndx]= data.dered_r
            raw.dered_g[rawIndx]= data.dered_g
            raw.plate[rawIndx]= data.plate
            raw.ra[rawIndx]= data.ra
            raw.dec[rawIndx]= data.dec
            raw.l[rawIndx]= data.l
            raw.b[rawIndx]= data.b
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    #Dump raw
    fitsio.write(args[0],raw,clobber=True)
Exemple #8
0
def plot2d(options,args):
    """Make a plot of a quantity's best-fit vs. FeH and aFe"""
    if options.sample.lower() == 'g':
        npops= 62
    elif options.sample.lower() == 'k':
        npops= 54
    if options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    savefile.close()
    #First calculate the derivative properties
    if not options.multi is None:
        derivProps= multi.parallel_map((lambda x: calcAllDerivProps(x,options,args)),
                                  range(npops),
                                  numcores=numpy.amin([options.multi,
                                                       npops,
                                                       multiprocessing.cpu_count()]))
    else:
        derivProps= []
        for ii in range(npops):
            derivProps.append(calcAllDerivProps(ii,options,args))
    xprop= options.subtype.split(',')[0]
    yprop= options.subtype.split(',')[1]
    if xprop == 'fracfaint' or yprop == 'fracfaint':
        #Read the data
        print "Reading the data ..."
        raw= read_rawdata(options)
        #Bin the data
        binned= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05)
        for ii in range(npops):
            if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                            k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                                            or (options.sample.lower() == 'g' and (ii == 50 or ii == 57)) \
                                            or (options.sample.lower() == 'k' and ii < 7):
                                            continue
            data= binned(fehs[ii],afes[ii])
            indx= (data.dered_r > 17.8)
            derivProps[ii]['fracfaint']= numpy.sum(indx)/float(len(indx))
            derivProps[ii]['fracfaint_err']= 0.
    if xprop == 'nfaint' or yprop == 'nfaint':
        #Read the data
        print "Reading the data ..."
        raw= read_rawdata(options)
        #Bin the data
        binned= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05)
        for ii in range(npops):
            if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                            k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                                            or (options.sample.lower() == 'g' and ii < 6) \
                                            or (options.sample.lower() == 'k' and ii < 7):
                                            continue
            data= binned(fehs[ii],afes[ii])
            indx= (data.dered_r > 17.8)
            derivProps[ii]['nfaint']= numpy.sum(indx)
            derivProps[ii]['nfaint_err']= 0.
    if xprop == 'hz' or yprop == 'hz':
        for ii in range(npops):
            if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                            k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                                            or (options.sample.lower() == 'g' and ii < 6) \
                                            or (options.sample.lower() == 'k' and ii < 7):
                                            continue
            hz, hzerr= monoAbundanceMW.hz(fehs[ii],afes[ii],
                                          k=(options.sample.lower() == 'k'),
                                          err=True)
            derivProps[ii]['hz']= hz
            derivProps[ii]['hz_err']= hzerr    
    if xprop == 'hr' or yprop == 'hr':
        for ii in range(npops):
            if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                            k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                                            or (options.sample.lower() == 'g' and ii < 6) \
                                            or (options.sample.lower() == 'k' and ii < 7):
                                            continue
            hr, hrerr= monoAbundanceMW.hr(fehs[ii],afes[ii],
                                          k=(options.sample.lower() == 'k'),
                                          err=True)
            derivProps[ii]['hr']= hr
            derivProps[ii]['hr_err']= hrerr    
    #Load into plotthis
    plotthis_x= numpy.zeros(npops)+numpy.nan
    plotthis_y= numpy.zeros(npops)+numpy.nan
    plotthis_x_err= numpy.zeros(npops)+numpy.nan
    plotthis_y_err= numpy.zeros(npops)+numpy.nan
    for ii in range(npops):
        if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                         k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                or (options.sample.lower() == 'g' and ii < 6) \
                or (options.sample.lower() == 'k' and ii < 7):
            continue
        plotthis_x[ii]= derivProps[ii][xprop]
        plotthis_y[ii]= derivProps[ii][yprop]
        plotthis_x_err[ii]= derivProps[ii][xprop+'_err']
        plotthis_y_err[ii]= derivProps[ii][yprop+'_err']
    #Now plot
    bovy_plot.bovy_print(fig_width=6.)
    bovy_plot.bovy_plot(plotthis_x,plotthis_y,
                        s=25.,c=afes,
                        cmap='jet',
                        xlabel=labels[xprop],ylabel=labels[yprop],
                        clabel=r'$[\alpha/\mathrm{Fe}]$',
                        xrange=ranges[xprop],yrange=ranges[yprop],
                        vmin=0.,vmax=0.5,
                        scatter=True,edgecolors='none',
                        colorbar=True)
    colormap = cm.jet
    for ii in range(npops):
        if numpy.isnan(plotthis_x[ii]): continue
        pyplot.errorbar(plotthis_x[ii],
                        plotthis_y[ii],
                        xerr=plotthis_x_err[ii],
                        yerr=plotthis_y_err[ii],
                        color=colormap(_squeeze(afes[ii],
                                                numpy.amax([numpy.amin(afes)]),
                                                            numpy.amin([numpy.amax(afes)]))),
                        elinewidth=1.,capsize=3,zorder=0)  
    bovy_plot.bovy_end_print(options.outfilename)
    return None        
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)
def plot_distsystematic(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin)
    if not options.bmin is None:
        #Cut on |b|
        raw= raw[(numpy.fabs(raw.b) > options.bmin)]
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))+numpy.nan
    #Run through the bins
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            if len(data) < options.minndata:
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            #Create XYZ and R, vxvyvz, cov_vxvyvz
            R= ((8.-data.xc)**2.+data.yc**2.)**0.5
            #Confine to R-range?
            if not options.rmin is None and not options.rmax is None:
                dataindx= (R >= options.rmin)*\
                    (R < options.rmax)
                data= data[dataindx]
                R= R[dataindx]
            XYZ= numpy.zeros((len(data),3))
            XYZ[:,0]= data.xc
            XYZ[:,1]= data.yc
            XYZ[:,2]= data.zc+_ZSUN
            vxvyvz= numpy.zeros((len(data),3))
            vxvyvz[:,0]= data.vxc
            vxvyvz[:,1]= data.vyc
            vxvyvz[:,2]= data.vzc
            """
            cov_vxvyvz= numpy.zeros((len(data),3,3))
            cov_vxvyvz[:,0,0]= data.vxc_err**2.
            cov_vxvyvz[:,1,1]= data.vyc_err**2.
            cov_vxvyvz[:,2,2]= data.vzc_err**2.
            cov_vxvyvz[:,0,1]= data.vxvyc_rho*data.vxc_err*data.vyc_err
            cov_vxvyvz[:,0,2]= data.vxvzc_rho*data.vxc_err*data.vzc_err
            cov_vxvyvz[:,1,2]= data.vyvzc_rho*data.vyc_err*data.vzc_err
            """
            cosphi= (8.-XYZ[:,0])/R
            sinphi= XYZ[:,1]/R
            sinbeta= XYZ[:,2]/numpy.sqrt(R*R+XYZ[:,2]*XYZ[:,2])
            cosbeta= R/numpy.sqrt(R*R+XYZ[:,2]*XYZ[:,2])
            ndata= len(data.ra)
            cov_pmradec= numpy.zeros((ndata,2,2))
            cov_pmradec[:,0,0]= data.pmra_err**2.
            cov_pmradec[:,1,1]= data.pmdec_err**2.
            cov_pmllbb= bovy_coords.cov_pmrapmdec_to_pmllpmbb(cov_pmradec,data.ra,
                                                              data.dec,degree=True)
            """
            vR= -vxvyvz[:,0]*cosphi+vxvyvz[:,1]*sinphi
            vT= vxvyvz[:,0]*sinphi+vxvyvz[:,1]*cosphi
            vz= vxvyvz[:,2]
            vxvyvz[:,0]= vR               
            vxvyvz[:,1]= vT
            for rr in range(len(XYZ[:,0])):
                rot= numpy.array([[cosphi[rr],sinphi[rr]],
                                  [-sinphi[rr],cosphi[rr]]])
                sxy= cov_vxvyvz[rr,0:2,0:2]
                sRT= numpy.dot(rot,numpy.dot(sxy,rot.T))
                cov_vxvyvz[rr,0:2,0:2]= sRT
            """
            #calculate x and y
            lb= bovy_coords.radec_to_lb(data.ra,data.dec,degree=True)
            lb*= _DEGTORAD
            tuu= 1.-numpy.cos(lb[:,1])**2.*numpy.cos(lb[:,0])**2.
            tuv= -0.5*numpy.cos(lb[:,1])**2.*numpy.sin(2.*lb[:,0])
            tuw= -0.5*numpy.cos(lb[:,0])*numpy.sin(2.*lb[:,1])
            tvv= 1.-numpy.cos(lb[:,1])**2.*numpy.sin(lb[:,0])**2.
            tvw= -0.5*numpy.sin(2.*lb[:,1])*numpy.sin(lb[:,0])
            tww= numpy.cos(lb[:,1])**2.
            #x= tuu*_VRSUN+tuv*vxvyvz[:,1]+tuw*vxvyvz[:,2]
            #y= -tww*_VZSUN+tuw*vxvyvz[:,0]+tvw*vxvyvz[:,1]
            x= -tuu*numpy.mean(vxvyvz[:,0])+tuv*vxvyvz[:,1]+tuw*vxvyvz[:,2]
            y= -tww*numpy.mean(vxvyvz[:,2])+tuw*vxvyvz[:,0]+tvw*vxvyvz[:,1]
            if options.type.lower() == 'u':
                corcorr=0.
                plotthis[ii,jj]= (numpy.mean(vxvyvz[:,0]*x)-numpy.mean(vxvyvz[:,0])*numpy.mean(x))/(numpy.var(x)+numpy.mean(tuv**2.+tuw**2.)*numpy.var(vxvyvz[:,0]))
            elif options.type.lower() == 'meanu':
                plotthis[ii,jj]= numpy.mean(vxvyvz[:,0])
            elif options.type.lower() == 'meanw':
                plotthis[ii,jj]= numpy.mean(vxvyvz[:,2])
            else:
                corcorr= 0.25*numpy.mean(2.*sinbeta*cosbeta*numpy.sin(2.*lb[:,1])*numpy.cos(lb[:,0])*cosphi)*(numpy.var(vxvyvz[:,0])-numpy.var(vxvyvz[:,2]))\
                    -0.25*numpy.mean(2.*sinbeta*cosbeta*numpy.sin(2.*lb[:,1])*numpy.sin(lb[:,0])*sinphi)*(numpy.var(vxvyvz[:,0])-numpy.var(vxvyvz[:,2]))\
                    +0.25*numpy.mean(numpy.sin(lb[:,1])**2.*(cov_pmllbb[:,1,1]*data.dist**2.*4.74**2.-data.vr_err**2.))
                plotthis[ii,jj]= (numpy.mean(vxvyvz[:,2]*y)-numpy.mean(vxvyvz[:,2])*numpy.mean(y)-corcorr)/(numpy.var(y)+numpy.mean(tvw**2.+tuw**2.)*numpy.var(vxvyvz[:,2]))
            #print ii, jj, plotthis[ii,jj], corcorr, numpy.mean(vxvyvz[:,2]*y)-numpy.mean(vxvyvz[:,2])*numpy.mean(y)-corcorr
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
            if jj == 0: #this means we've reset the counter 
                break
    #print plotthis
    #Set up plot
    if options.type.lower() == 'meanu':
        vmin, vmax= -20.,20.
        zlabel=r'$\mathrm{mean}\ U$'
    elif options.type.lower() == 'meanw':
        vmin, vmax= -20.,20.
        zlabel=r'$\mathrm{mean}\ W$'
    else:
        vmin, vmax= -0.2,0.2
        zlabel=r'$\mathrm{fractional\ distance\ overestimate}$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.5]
        yrange=[-0.2,0.6]
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          zlabel=zlabel,
                          xrange=xrange,yrange=yrange,
                          vmin=vmin,vmax=vmax,
                          contours=False,
                          colorbar=True,shrink=0.78)
    bovy_plot.bovy_text(r'$\mathrm{median} = %.2f$' % (numpy.median(plotthis[numpy.isfinite(plotthis)])),
                        bottom_left=True,size=14.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
def plotVelComparisonDFMulti(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    gafes, gfehs, left_legend= getMultiComparisonBins(options)
    M= len(gfehs)
    if options.andistances:
        distancefacs= numpy.zeros_like(fehs)
        gdistancefacs= numpy.zeros_like(gfehs)
        for jj in range(M):
            #Find pop corresponding to this bin
            ii= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
            print ii
            #Get the relevant data
            data= binned(fehs[ii],afes[ii])
            distancefacs[ii]= AnDistance.AnDistance(data.dered_g-data.dered_r,
                                                    data.feh)
            gdistancefacs[jj]= distancefacs[ii]
            options.fixdm= numpy.log10(distancefacs[ii])*5.
            #Apply distance factor to the data
            newraw= read_rawdata(options)
            newbinned= pixelAfeFeh(newraw,dfeh=options.dfeh,dafe=options.dafe)
            thisdataIndx= binned.callIndx(fehs[ii],afes[ii])
            binned.data.xc[thisdataIndx]= newbinned.data.xc[thisdataIndx]
            binned.data.yc[thisdataIndx]= newbinned.data.yc[thisdataIndx]
            binned.data.zc[thisdataIndx]= newbinned.data.zc[thisdataIndx]
            binned.data.plate[thisdataIndx]= newbinned.data.plate[thisdataIndx]
            binned.data.dered_r[thisdataIndx]= newbinned.data.dered_r[thisdataIndx]
    else:
        distancefacs=numpy.ones_like(fehs)
        gdistancefacs=numpy.ones_like(gfehs)
    ##########POTENTIAL PARAMETERS####################
    potparams1= numpy.array([numpy.log(2.5/8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.2,0.])
    if options.group.lower() == 'aenhanced':
        potparams2= numpy.array([numpy.log(2.8/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.266666666,0.])
        potparams3= numpy.array([numpy.log(2.8/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.8,0.])
    elif options.group.lower() == 'aintermediate':
        potparams2= numpy.array([numpy.log(3.0/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.3333333333333,0.])
        potparams3= numpy.array([numpy.log(3.0/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.933333333333,0.])
    elif options.group.lower() == 'apoor':
        potparams2= numpy.array([numpy.log(2.6/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.4,0.])
        potparams3= numpy.array([numpy.log(2.6/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),1.0,0.])
    options.potential=  'dpdiskplhalofixbulgeflatwgasalt'
    #Check whether fits exist, if not, pop
    removeBins= numpy.ones(M,dtype='bool')
    for jj in range(M):
        #Find pop corresponding to this bin
        pop= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
        #Load savefile
        if not options.init is None:
            #Load initial parameters from file
            savename= options.init
            spl= savename.split('.')
            newname= ''
            for ll in range(len(spl)-1):
                newname+= spl[ll]
                if not ll == len(spl)-2: newname+= '.'
            newname+= '_%i.' % pop
            newname+= spl[-1]
            if not os.path.exists(newname):
                removeBins[jj]= False
        else:
            raise IOError("base filename not specified ...")
    if numpy.sum(removeBins) == 0:
        raise IOError("None of the group bins have been fit ...")
    elif numpy.sum(removeBins) < M:
        #Some bins have not been fit yet, and have to be remove
        gfehs= list((numpy.array(gfehs))[removeBins])
        gafes= list((numpy.array(gafes))[removeBins])
        print "Only using %i bins out of %i ..." % (numpy.sum(removeBins),M)
        M= len(gfehs)
    data= []
    zs= []
    velps= numpy.zeros((len(binned.data),options.nv))
    velps[:,:]= numpy.nan
    velps2= numpy.zeros((len(binned.data),options.nv))
    velps2[:,:]= numpy.nan
    velps3= numpy.zeros((len(binned.data),options.nv))
    velps3[:,:]= numpy.nan
    cumulndata= 0
    if options.type.lower() == 'vz':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-180.,180.,options.nv)
            xrange=[-180.,180.]
            bins= 39
        elif options.group == 'aintermediate':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 33
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-120.,120.,options.nv)
            xrange=[-140.,140.]
            bins= 26
        xlabel=r'$V_Z\ (\mathrm{km\,s}^{-1})$'
    elif options.type.lower() == 'vr':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-220.,220.,options.nv)
            xrange=[-220.,220.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 26
        xlabel=r'$V_R\ (\mathrm{km\,s}^{-1})$'
    elif options.type.lower() == 'vt':
        if options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        xlabel=r'$V_T\ (\mathrm{km\,s}^{-1})$'
    alts= True
    if not options.multi is None:
        #Generate list of temporary files
        tmpfiles= []
        for jj in range(M): 
            tfile, tmpfile= tempfile.mkstemp()
            os.close(tfile) #Close because it's open
            tmpfiles.append(tmpfile)
        try:
            dummy= multi.parallel_map((lambda x: run_calc_model_multi(x,M,gfehs,gafes,fehs,afes,options,
                                                                      vs,
                                                                      potparams1,potparams2,potparams3,
                                                                      distancefacs,
                                                                      binned,alts,True,tmpfiles)),
                                      range(M),
                                      numcores=numpy.amin([M,
                                                           multiprocessing.cpu_count(),
                                                           options.multi]))
            #Now read all of the temporary files
            for jj in range(M):
                tmpfile= open(tmpfiles[jj],'rb')
                tvelps= pickle.load(tmpfile)
                if tvelps is None:
                    continue
                tvelps2= pickle.load(tmpfile)
                tvelps3= pickle.load(tmpfile)
                data.extend(pickle.load(tmpfile))
                zs.extend(pickle.load(tmpfile))
                tndata= pickle.load(tmpfile)
                velps[cumulndata:cumulndata+tndata,:]= tvelps
                velps2[cumulndata:cumulndata+tndata,:]= tvelps2
                velps3[cumulndata:cumulndata+tndata,:]= tvelps3
                cumulndata+= tndata
                tmpfile.close()
        finally:
            for jj in range(M):
                os.remove(tmpfiles[jj])
    else:
        for jj in range(M):
            try:
                tvelps, tvelps2, tvelps3, tdata, tzs, tndata= run_calc_model_multi(jj,M,gfehs,gafes,fehs,afes,options,
                                                                                   vs,
                                                                                                                                potparams1,potparams2,potparams3,
                                                                      distancefacs,
                                                                                                                                binned,alts,
                                                                                                                                False,None)
            except TypeError:
                continue
            velps[cumulndata:cumulndata+tndata,:]= tvelps
            velps2[cumulndata:cumulndata+tndata,:]= tvelps2
            velps3[cumulndata:cumulndata+tndata,:]= tvelps3
            data.extend(tdata)
            zs.extend(tzs)
            cumulndata+= tndata
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data,bins=26,normed=True,color='k',
                        histtype='step',
                        xrange=xrange,xlabel=xlabel)
    plotp= numpy.nansum(velps[:cumulndata,:],axis=0)/cumulndata
    print numpy.sum(plotp)*(vs[1]-vs[0])
    bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
    if alts:
        plotp= numpy.nansum(velps2,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
        plotp= numpy.nansum(velps3,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
    if not left_legend is None:
        bovy_plot.bovy_text(left_legend,top_left=True,size=_legendsize)
    bovy_plot.bovy_text(r'$\mathrm{full\ subsample}$'
                        +'\n'+
                        '$%i \ \ \mathrm{stars}$' % 
                        len(data),top_right=True,
                        size=_legendsize)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_all.'+options.ext)
    if options.all: return None
    #Plot zranges
    #First determine the ranges that have nstars in them
    rranges_nstars= 1000
    zs= numpy.array(zs)
    data= numpy.array(data)
    tdata_z= sorted(numpy.fabs(zs))
    nbins= numpy.ceil(len(tdata_z)/float(rranges_nstars))
    rranges_nstars= int(numpy.floor(float(len(tdata_z))/nbins))
    accum= rranges_nstars
    zranges= [0.0]
    while accum < len(tdata_z):
        zranges.append(tdata_z[accum])
        accum+= rranges_nstars
    zranges.append(5.0)
    print zranges
    #zranges= [0.5,1.,1.5,2.,3.,4.]
    nzranges= len(zranges)-1
    sigzsd= numpy.empty(nzranges)
    esigzsd= numpy.empty(nzranges)
    sigzs1= numpy.empty(nzranges)
    sigzs2= numpy.empty(nzranges)
    sigzs3= numpy.empty(nzranges)
    for ii in range(nzranges):
        indx= (numpy.fabs(zs) >= zranges[ii])*(numpy.fabs(zs) < zranges[ii+1])
        plotp= numpy.nansum(velps[indx,:],axis=0)/numpy.sum(indx)
        yrange= [0.,1.35*numpy.nanmax(plotp)]
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(data[indx],bins=26,normed=True,color='k',
                            histtype='step',
                            yrange=yrange,
                            xrange=xrange,xlabel=xlabel)
        sigzsd[ii]= numpy.std(data[indx][(numpy.fabs(data[indx]) < 100.)])
        esigzsd[ii]= sigzsd[ii]/numpy.sqrt(float(len(data[indx][(numpy.fabs(data[indx]) < 100.)])))
        sigzs1[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
        bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
        if alts:
            plotp= numpy.nansum(velps2[indx,:],axis=0)/numpy.sum(indx)
            sigzs2[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
            plotp= numpy.nansum(velps3[indx,:],axis=0)/numpy.sum(indx)
            sigzs3[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
        bovy_plot.bovy_text(r'$ %i\ \mathrm{pc} \leq |Z| < %i\ \mathrm{pc}$' % (int(1000*zranges[ii]),int(1000*zranges[ii+1])),
#                            +'\n'+
#                            '$%i \ \ \mathrm{stars}$' % (numpy.sum(indx)),
                            top_right=True,
                            size=_legendsize)
        bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_z%.1f_z%.1f.' % (zranges[ii],zranges[ii+1])+options.ext)
    #Plot velocity dispersion as a function of |Z|
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzsd,
                        'ko',
                        xlabel=r'$|Z|\ (\mathrm{kpc})$',
                        ylabel=r'$\sigma_z\ (\mathrm{km\,s}^{-1})$',
                        xrange=[0.,4.],
                        yrange=[0.,60.])
    pyplot.errorbar(((numpy.roll(zranges,-1)+zranges)/2.)[:-1],sigzsd,
                    yerr=esigzsd,
                    marker='o',color='k',linestyle='none')
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzs1,
                        'r+',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzs2,
                        'cx',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzs3,
                        'gd',overplot=True,ms=10.)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_szvsz.' +options.ext)
    return None
Exemple #12
0
def collateFits(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Savefiles
    if os.path.exists(args[0]):#Load density fits
        savefile= open(args[0],'rb')
        densfits= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("density fits file not included")
    if os.path.exists(args[1]):#Load density fits
        savefile= open(args[1],'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("density samples file not included")
    if os.path.exists(args[2]):#Load density fits
        savefile= open(args[2],'rb')
        mass= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("masses file not included")
    #if os.path.exists(args[3]):#Load density fits
    #    savefile= open(args[3],'rb')
    #    masssamples= pickle.load(savefile)
    #    savefile.close()
    #else:
    #    raise IOError("mass samples file not included")
    if os.path.exists(args[4]):#Load density fits
        savefile= open(args[4],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("vertical velocity file not included")
    if os.path.exists(args[5]):#Load density fits
        savefile= open(args[5],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("vertical velocity samples  file not included")
    if os.path.exists(args[6]):#Load density fits
        savefile= open(args[6],'rb')
        velrfits= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("radial velocity file not included")
    if os.path.exists(args[7]):#Load density fits
        savefile= open(args[7],'rb')
        velrsamples= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("radial velocity samples  file not included")
    nrecs= len([r for r in densfits if not r is None])
    out= numpy.recarray(nrecs,dtype=[('feh',float),
                                     ('afe',float),
                                     ('hz',float),
                                     ('hr',float),
                                     ('bc',float),
                                     ('mass',float),
                                     ('sz',float),
                                     ('hsz',float),
                                     ('p1',float),
                                     ('p2',float),
                                     ('sr',float),
                                     ('hsr',float),
                                     ('zmin',float),
                                     ('zmax',float),
                                     ('zmedian',float),
                                     ('hz_err',float),
                                     ('hr_err',float),
                                     ('mass_err',float),
                                     ('sz_err',float),
                                     ('hsz_err',float),
                                     ('p1_err',float),
                                     ('p2_err',float),
                                     ('szp1_corr',float),
                                     ('szp2_corr',float),
                                     ('szhsz_corr',float),
                                     ('p1hsz_corr',float),
                                     ('p2hsz_corr',float),
                                     ('p1p2_corr',float),
                                     ('sr_err',float)])
                                     
    nout= 0
    #Start filling it up
    for ii in range(binned.npixfeh()):
        for jj in range(binned.npixafe()):
            data= binned(binned.feh(ii),binned.afe(jj))
            fehindx= binned.fehindx(binned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(binned.afe(jj))#Unnecessary here
            if afeindx+fehindx*binned.npixafe() >= len(densfits):
                continue
            thisdensfit= densfits[afeindx+fehindx*binned.npixafe()]
            thisdenssamples= denssamples[afeindx+fehindx*binned.npixafe()]
            thismass= mass[afeindx+fehindx*binned.npixafe()]
            #thismasssamples= masssamples[afeindx+fehindx*binned.npixafe()]
            thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            thesevelsamples= velsamples[afeindx+fehindx*binned.npixafe()]
            thisvelrfit= velrfits[afeindx+fehindx*binned.npixafe()]
            thesevelrsamples= velrsamples[afeindx+fehindx*binned.npixafe()]
            if thisdensfit is None:
                continue
            if len(data) < options.minndata:
                continue
            out['feh'][nout]= binned.feh(ii)
            out[nout]['afe']= binned.afe(jj)
            if options.densmodel.lower() == 'hwr' \
                    or options.densmodel.lower() == 'dblexp':
                out[nout]['hz']= numpy.exp(thisdensfit[0])*1000.
                if options.densmodel.lower() == 'dblexp':
                    out[nout]['hr']= numpy.exp(-thisdensfit[1])
                else:
                    out[nout]['hr']= numpy.exp(thisdensfit[1])
                out[nout]['bc']= thisdensfit[2]
                theseerrors= []
                xs= numpy.array([s[0] for s in thisdenssamples])
                theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                out[nout]['hz_err']= theseerrors[0]*1000.
                if options.densmodel.lower() == 'dblexp':
                    xs= numpy.array([-s[1] for s in thisdenssamples])
                else:
                    xs= numpy.array([s[1] for s in thisdenssamples])
                theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                out[nout]['hr_err']= theseerrors[1]
            #mass
            if options.sample.lower() == 'k':
                out[nout]['mass']= numpy.nan
            else:
                out[nout]['mass']= thismass/10.**6.
            #out[nout]['mass_err']= numpy.std(numpy.array(thismasssamples)/10.**6.)
            #Velocities
            if options.velmodel.lower() == 'hwr':
                out[nout]['sz']= numpy.exp(thisvelfit[1])
                out[nout]['hsz']= numpy.exp(thisvelfit[4])
                out[nout]['sr']= numpy.exp(thisvelrfit[1])
                out[nout]['hsr']= numpy.exp(thisvelrfit[4])
                out[nout]['p1']= thisvelfit[2]
                out[nout]['p2']= thisvelfit[3]
                zsorted= sorted(numpy.fabs(data.zc+_ZSUN))
                out[nout]['zmin']= zsorted[int(numpy.ceil(0.16*len(zsorted)))]*1000.
                out[nout]['zmax']= zsorted[int(numpy.floor(0.84*len(zsorted)))]*1000.
                out[nout]['zmedian']= numpy.median(numpy.fabs(data.zc)-_ZSUN)*1000.
                #Errors
                xs= numpy.array([s[1] for s in thesevelsamples])
                out[nout]['sz_err']= 0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs)))
                xs= numpy.array([s[4] for s in thesevelsamples])
                out[nout]['hsz_err']= 0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs)))
                xs= numpy.array([s[2] for s in thesevelsamples])
                out[nout]['p1_err']= numpy.std(xs)
                xs= numpy.array([s[3] for s in thesevelsamples])
                out[nout]['p2_err']= numpy.std(xs)
                xs= numpy.exp(numpy.array([s[1] for s in thesevelsamples]))
                ys= numpy.array([s[2] for s in thesevelsamples])
                out[nout]['szp1_corr']= numpy.corrcoef(xs,ys)[0,1]
                ys= numpy.array([s[3] for s in thesevelsamples])
                out[nout]['szp2_corr']= numpy.corrcoef(xs,ys)[0,1]
                xs= numpy.array([s[2] for s in thesevelsamples])
                out[nout]['p1p2_corr']= numpy.corrcoef(xs,ys)[0,1]
                xs= numpy.exp(numpy.array([s[4] for s in thesevelsamples]))
                ys= numpy.exp(numpy.array([s[1] for s in thesevelsamples]))
                out[nout]['szhsz_corr']= numpy.corrcoef(xs,ys)[0,1]
                ys= numpy.array([s[2] for s in thesevelsamples])
                out[nout]['p1hsz_corr']= numpy.corrcoef(xs,ys)[0,1]
                ys= numpy.array([s[3] for s in thesevelsamples])
                out[nout]['p2hsz_corr']= numpy.corrcoef(xs,ys)[0,1]
                xs= numpy.array([s[1] for s in thesevelrsamples])
                out[nout]['sr_err']= 0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs)))
            nout+= 1
    #Write output
    fitsio.write(options.outfile,out,clobber=True)
Exemple #13
0
def plot_DFsingles(options,args):
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    counter= 0
    abindx= numpy.zeros((len(binned.fehedges)-1,len(binned.afeedges)-1),
                        dtype='int')
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
            abindx[ii,jj]= counter
            counter+= 1
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    #Load each solutions
    sols= []
    savename= args[0]
    initname= options.init
    for ii in range(nabundancebins):
        spl= savename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        savefilename= newname
        #Read savefile
        try:
            savefile= open(savefilename,'rb')
        except IOError:
            print "WARNING: MISSING ABUNDANCE BIN"
            sols.append(None)
        else:
            sols.append(pickle.load(savefile))
            savefile.close()
        #Load samples as well
        if options.mcsample:
            #Do the same for init
            spl= initname.split('.')
            newname= ''
            for jj in range(len(spl)-1):
                newname+= spl[jj]
                if not jj == len(spl)-2: newname+= '.'
            newname+= '_%i.' % ii
            newname+= spl[-1]
            options.init= newname
    mapfehs= monoAbundanceMW.fehs()
    mapafes= monoAbundanceMW.afes()
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
        errors= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            #Find abundance indx
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            solindx= abindx[fehindx,afeindx]
            monoabindx= numpy.argmin((tightbinned.feh(ii)-mapfehs)**2./0.01 \
                                         +(tightbinned.afe(jj)-mapafes)**2./0.0025)
            if sols[solindx] is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if options.type.lower() == 'q':
                s= get_potparams(sols[solindx],options,1)
                plotthis[ii,jj]= s[0]
                if not options.flatten is None:
                    plotthis[ii,jj]/= options.flatten
            elif options.type.lower() == 'vc':
                if options.fixvo:
                    plotthis[ii,jj]= 1.
                else:
                    s= get_potparams(sols[solindx],options,1)
                    plotthis[ii,jj]= s[1]
            elif options.type.lower() == 'rd':
                s= get_potparams(sols[solindx],options,1)
                plotthis[ii,jj]= numpy.exp(s[0])
            elif options.type.lower() == 'zh':
                s= get_potparams(sols[solindx],options,1)
                plotthis[ii,jj]= numpy.exp(s[2-(1-(options.fixvo is None))])
            elif options.type.lower() == 'ndata':
                plotthis[ii,jj]= len(data)
            elif options.type.lower() == 'hr':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[0]*_REFR0
                if options.relative:
                    thishr= monoAbundanceMW.hr(mapfehs[monoabindx],mapafes[monoabindx])
                    plotthis[ii,jj]/= thishr
            elif options.type.lower() == 'sz':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[2]*_REFV0
                if options.relative:
                    thissz= monoAbundanceMW.sigmaz(mapfehs[monoabindx],mapafes[monoabindx])
                    plotthis[ii,jj]/= thissz
            elif options.type.lower() == 'sr':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[1]*_REFV0
                if options.relative:
                    thissr= monoAbundanceMW.sigmaz(mapfehs[monoabindx],mapafes[monoabindx])*2.
                    plotthis[ii,jj]/= thissr
            elif options.type.lower() == 'srsz':
                #Setup everything
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                aA= setup_aA(pot,options)               
                dfparams= get_dfparams(sols[solindx],0,options,log=False)
                if options.dfmodel.lower() == 'qdf':
                    #Normalize
                    hr= dfparams[0]/ro
                    sr= dfparams[1]/vo
                    sz= dfparams[2]/vo
                    hsr= dfparams[3]/ro
                    hsz= dfparams[4]/ro
                    #Setup
                    qdf= quasiisothermaldf(hr,sr,sz,hsr,hsz,pot=pot,
                                           aA=aA,cutcounter=True)              
                plotthis[ii,jj]= numpy.sqrt(qdf.sigmaR2(1.,1./_REFR0/ro,
                                                        ngl=options.ngl,gl=True)\
                                                /qdf.sigmaz2(1.,1./_REFR0/ro,
                                                            ngl=options.ngl,gl=True))
            elif options.type.lower() == 'outfrac':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[5]
            elif options.type.lower() == 'rhodm':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                    plotthis[ii,jj]= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                elif options.potential.lower() == 'mpdiskflplhalofixplfixbulgeflat':
                    plotthis[ii,jj]= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
            elif options.type.lower() == 'rhoo':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= potential.evaluateDensities(1.,0.,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
            elif options.type.lower() == 'surfz':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
            elif options.type.lower() == 'surfzdisk':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mpdisk' in options.potential.lower() or 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot[0])),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
            elif options.type.lower() == 'kz':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= numpy.fabs(potential.evaluatezforces(1.,options.height/ro/_REFR0,pot)/2./numpy.pi/4.302*_REFV0**2.*vo**2./_REFR0/ro)
            elif options.type.lower() == 'plhalo':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                    plotthis[ii,jj]= pot[1].alpha
            elif options.type.lower() == 'qhalo':
                #Setup potential
                s= get_potparams(sols[solindx],options,1)
                if options.potential.lower() == 'mpdiskflplhalofixplfixbulgeflat':
                    plotthis[ii,jj]= s[4]
            elif options.type.lower() == 'dlnvcdlnr':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= potential.dvcircdR(pot,1.)
            elif options.type.lower() == 'fd':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= (pot[0].vcirc(1.))**2.
            elif options.type.lower() == 'fh':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= (pot[1].vcirc(1.))**2.
            elif options.type.lower() == 'fb':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= (pot[2].vcirc(1.))**2.
            elif options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                    or options.type.lower() == 'afefeh':
                thisplot=[tightbinned.feh(ii),
                          tightbinned.afe(jj),
                          len(data)]
                if options.subtype.lower() == 'qvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisq= s[0]
                    if not options.flatten is None:
                        thisq/= options.flatten
                    thisvc= s[1]
                    thisplot.extend([thisq,thisvc])
                elif options.subtype.lower() == 'rdzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisplot.extend([thisrd,thiszh])
                elif options.subtype.lower() == 'zhvc':
                    s= get_potparams(sols[solindx],options,1)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisvc= s[1]*_REFV0
                    thisplot.extend([thiszh,thisvc])
                elif options.subtype.lower() == 'dlnvcdlnrvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisslope= s[3-(1-(options.fixvo is None))]/30.
                    thisvc= s[1]*_REFV0
                    thisplot.extend([thisslope,thisvc])
                elif options.subtype.lower() == 'rdvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    thisvc= s[1]*_REFV0
                    thisplot.extend([thisrd,thisvc])
                elif options.subtype.lower() == 'rdplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thisrd,thisplhalo])
                elif options.subtype.lower() == 'dlnvcdlnrplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thisslope= s[3-(1-(options.fixvo is None))]/30.
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thisslope,thisplhalo])
                elif options.subtype.lower() == 'dlnvcdlnrzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisslope= s[3-(1-(options.fixvo is None))]/30.
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisplot.extend([thisslope,thiszh])
                elif options.subtype.lower() == 'vc14plhalo':
                    s= get_potparams(sols[solindx],options,1)
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisvc14= potential.vcirc(pot,14./_REFR0/ro)*_REFV0*vo
                    thisplot.extend([thisplhalo,thisvc14])
                elif options.subtype.lower() == 'plhalovc':
                    s= get_potparams(sols[solindx],options,1)
                    thisvc= s[1]*_REFV0
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thisplhalo,thisvc])
                elif options.subtype.lower() == 'zhplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thiszh,thisplhalo])
                elif options.subtype.lower() == 'rhodmzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thiszh])
                elif options.subtype.lower() == 'rhodmsurfz':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thissurfz= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thissurfz])
                elif options.subtype.lower() == 'surfzzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thissurfz= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
                    thisplot.extend([thissurfz,thiszh])
                elif options.subtype.lower() == 'rhoozh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisrhoo= potential.evaluateDensities(1.,0.,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhoo,thiszh])
                elif options.subtype.lower() == 'rhodmvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisvc= s[1]*_REFV0
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thisvc])
                elif options.subtype.lower() == 'rhodmrd':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thisrdh= numpy.exp(s[0])
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thisrd])
                elif options.subtype.lower() == 'rhodmplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thisplhalo])
                plotthis.append(thisplot)
    #Set up plot
    if options.type.lower() == 'q':
        if not options.flatten is None:
            vmin, vmax= 0.9, 1.1
            zlabel=r'$\mathrm{flattening}\ q / %.1f$' % options.flatten
        elif 'real' in options.outfilename.lower():
            vmin, vmax= 0.9, 1.1
            medianq= numpy.median(plotthis[numpy.isfinite(plotthis)])
            plotthis/= medianq
            zlabel=r'$\mathrm{flattening}\ q / %.2f$' % medianq
        else:
            vmin, vmax= 0.5, 1.2
            zlabel=r'$\mathrm{flattening}\ q$'
    elif options.type.lower() == 'vc':
        vmin, vmax= 0.95, 1.05
        zlabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0)
        if 'real' in options.outfilename.lower():
           medianvc= numpy.median(plotthis[numpy.isfinite(plotthis)])
           plotthis/= medianvc
           zlabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0*medianvc)
    elif options.type.lower() == 'rhodm':
        vmin, vmax= 0.00, 0.02
        zlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
    elif options.type.lower() == 'rhoo':
        vmin, vmax= 0.00, 0.2
        zlabel=r'$\rho(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
    elif options.type.lower() == 'surfz':
        vmin, vmax= 50.,120.
        zlabel=r'$\Sigma(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
    elif options.type.lower() == 'surfzdisk':
        vmin, vmax= 20.,90.
        zlabel=r'$\Sigma_{\mathrm{disk}}(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
    elif options.type.lower() == 'kz':
        vmin, vmax= 50.,120.
        zlabel=r'$K_Z(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
    elif options.type.lower() == 'dlnvcdlnr':
        vmin, vmax= -0.3,0.2
        zlabel=r'$\frac{\mathrm{d} \ln V_c}{\mathrm{d} \ln R}$'
    elif options.type.lower() == 'fd':
        vmin, vmax= 0.00, 1.
        zlabel=r'$V_{c,\mathrm{disk}} / V_c\,(R_0)$'
    elif options.type.lower() == 'fh':
        vmin, vmax= 0.00, 1.
        zlabel=r'$V_{c,\mathrm{halo}} / V_c\,(R_0)$'
    elif options.type.lower() == 'fb':
        vmin, vmax= 0.00, .1
        zlabel=r'$V_{c,\mathrm{halo}} / V_c\,(R_0)$'
    elif options.type.lower() == 'rd':
        vmin, vmax= 0.2, 0.6
        zlabel=r'$R_d / R_0$'
    elif options.type.lower() == 'zh':
        vmin, vmax= 0.0125, 0.075
        zlabel=r'$z_h / R_0$'
    elif options.type.lower() == 'plhalo':
        vmin, vmax= 0.0, 2.
        zlabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
    elif options.type.lower() == 'qhalo':
        vmin, vmax= 0.4, 1.15
        zlabel=r'$q_\Phi^{\mathrm{halo}}$'
    elif options.type.lower() == 'ndata':
        vmin, vmax= numpy.nanmin(plotthis), numpy.nanmax(plotthis)
        zlabel=r'$N_\mathrm{data}$'
    elif options.type == 'hr':
        if options.relative:
            vmin, vmax= 0.8, 1.2
            zlabel=r'$\mathrm{input / output\ radial\ scale\ length}$'
        else:
            vmin, vmax= 1.35,4.5
            zlabel=r'$\mathrm{model\ radial\ scale\ length\ [kpc]}$'
    elif options.type == 'sz':
        if options.relative:
            vmin, vmax= 0.8, 1.2
            zlabel= r'$\mathrm{input / output\ model}\ \sigma_z$'
        else:
            vmin, vmax= 10.,60.
            zlabel= r'$\mathrm{model}\ \sigma_z\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'sr':
        if options.relative:
            vmin, vmax= 0.8, 1.2
            zlabel= r'$\mathrm{input/output\ model}\ \sigma_R$'
        else:
            vmin, vmax= 10.,60.
            zlabel= r'$\mathrm{model}\ \sigma_R\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'srsz':
        vmin, vmax= 0.5,2.
        zlabel= r'$\sigma_R/\sigma_z\ (R_0,1\,\mathrm{kpc})$'
    elif options.type == 'outfrac':
        vmin, vmax= 0., 1.
        zlabel= r'$\mathrm{relative\ number\ of\ outliers}$'
    elif options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.6,0.4
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.5]
        yrange=[-0.2,0.6]
    #Now plot
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe':
        #Gather everything
        afe, feh, ndata, x, y= [], [], [], [], []
        for ii in range(len(plotthis)):
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][2])
            x.append(plotthis[ii][3])
            y.append(plotthis[ii][4])
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        x= numpy.array(x)
        y= numpy.array(y)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        onedhists=False
        if options.subtype.lower() == 'qvc':
            if not options.flatten is None:
                xrange= [0.9,1.1]
                xlabel=r'$\mathrm{flattening}\ q / %.1f$' % options.flatten
            elif 'real' in options.outfilename.lower():
                xrange= [0.9,1.1]
                medianq= numpy.median(x[numpy.isfinite(x)])
                x/= medianq
                xlabel=r'$\mathrm{flattening}\ q / %.2f$' % medianq
            else:
                xrange= [0.5, 1.2]
                xlabel=r'$\mathrm{flattening}\ q$'
            yrange= [0.95, 1.05]
            ylabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0)
            if 'real' in options.outfilename.lower():
                medianvc= numpy.median(y[numpy.isfinite(y)])
                y/= medianvc
                ylabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0*medianvc)
        elif options.subtype.lower() == 'rdzh':
            yrange= [0.0125,0.1]
            xrange= [0.2,0.8]
            xlabel=r'$R_d / R_0$'
            ylabel=r'$z_h / R_0$'
        elif options.subtype.lower() == 'rdplhalo':
            yrange= [0.,2.]
            xrange= [0.2,0.8]
            xlabel=r'$R_d / R_0$'
            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
        elif options.subtype.lower() == 'vc14plhalo':
            yrange= [210.,280.]
            xrange= [0.,2.]
            xlabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            ylabel=r'$V_c (R=14\,\mathrm{kpc})\ [\mathrm{km\,s}^{-1}$]'
        elif options.subtype.lower() == 'zhplhalo':
            yrange= [0.,2.]
            xrange= [0.0125,0.1]

            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            xlabel=r'$z_h / R_0$'
        elif options.subtype.lower() == 'rhodmplhalo':
            xrange= [0.,0.02]
            yrange= [0.,2.]
            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rhodmzh':
            yrange= [0.0125,0.1]
            xrange= [0.,0.02]
            ylabel=r'$z_h / R_0$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rhoozh':
            yrange= [0.0125,0.1]
            xrange= [0.,0.2]
            ylabel=r'$z_h / R_0$'
            xlabel=r'$\rho(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'surfzzh':
            yrange= [0.0125,0.1]
            xrange= [50.+20.*(options.height-1.1),120.+20.*(options.height-1.1)]
            ylabel=r'$z_h / R_0$'
            xlabel=r'$\Sigma(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
        elif options.subtype.lower() == 'rhodmsurfz':
            yrange= [50.+20.*(options.height-1.1),120.+20.*(options.height-1.1)]
            xrange= [0.,0.02]
            ylabel=r'$\Sigma(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rhodmrd':
            yrange= [0.2,0.8]
            xrange= [0.,0.02]
            ylabel=r'$R_d / R_0$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rdvc':
            yrange= [210.,250.]
            xrange= [0.2,0.8]
            xlabel=r'$R_d / R_0$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
        elif options.subtype.lower() == 'zhvc':
            yrange= [210.,250.]
            xrange= [0.0125,0.1]
            xlabel=r'$z_h / R_0$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
        elif options.subtype.lower() == 'dlnvcdlnrvc':
            yrange= [210.,250.]
            xrange= [-0.2,0.07]
            xlabel=r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
            onedhists=True
        elif options.subtype.lower() == 'dlnvcdlnrplhalo':
            yrange= [0.,2.]
            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            xrange= [-0.2,0.07]
            xlabel=r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$'
        elif options.subtype.lower() == 'dlnvcdlnrzh':
            yrange= [0.0125,0.1]
            ylabel=r'$z_h / R_0$'
            xrange= [-0.2,0.07]
            xlabel=r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$'
        elif options.subtype.lower() == 'rhodmvc':
            yrange= [210.,250.]
            xrange= [0.,0.02]
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'plhalovc':
            yrange= [210.,250.]
            xrange= [0.,2.]
            xlabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}$]'
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        ax= bovy_plot.bovy_plot(x,y,
                            s=ndata,c=plotc,
                            cmap='jet',
                            xlabel=xlabel,ylabel=ylabel,
                            clabel=zlabel,
                            xrange=xrange,yrange=yrange,
                            vmin=vmin,vmax=vmax,
                            scatter=True,edgecolors='none',
                            colorbar=True-onedhists,
                            onedhists=onedhists,
                            onedhistxnormed=onedhists,
                            onedhistynormed=onedhists,
                            bins=15)
        if onedhists:
            axS, axx, axy= ax
        if options.subtype.lower() == 'dlnvcdlnrvc':
            #Plot prior on one-d axes
            sb= numpy.linspace(-0.2,0.0399,1001)
            fsb= numpy.exp(numpy.log((0.04-sb)/0.04)-(0.04-sb)/0.04)
            fsb/= numpy.sum(fsb)*(sb[1]-sb[0])
            axx.plot(sb,fsb,'-',color='0.65')
            tvc= numpy.linspace(150.,350.,1001)
            fvc= numpy.exp(-(tvc-225.)**2./2./15.**2.)
            fvc/= numpy.sum(fvc)*(tvc[1]-tvc[0])
            axy.plot(fvc,tvc,'-',color='0.65')
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              contours=False,
                              colorbar=True,shrink=0.78)
        if options.type.lower() == 'q' or options.type.lower() == 'vc' \
                or options.relative or options.type.lower() == 'rd' \
                or options.type.lower() == 'fd' \
                or options.type.lower() == 'fh' \
                or options.type.lower() == 'fb' \
                or options.type.lower() == 'plhalo' \
                or options.type.lower() == 'surfz' \
                or options.type.lower() == 'surfzdisk' \
                or options.type.lower() == 'rhoo' \
                or options.type.lower() == 'qhalo' \
                or options.type.lower() == 'kz':
            bovy_plot.bovy_text(r'$\mathrm{median} = %.2f \pm %.2f$' % (numpy.median(plotthis[numpy.isfinite(plotthis)]),
                                                                        1.4826*numpy.median(numpy.fabs(plotthis[numpy.isfinite(plotthis)]-numpy.median(plotthis[numpy.isfinite(plotthis)])))),
                                bottom_left=True,size=14.)
        if options.type.lower() == 'zh' or options.type.lower() == 'rhodm':
            bovy_plot.bovy_text(r'$\mathrm{median} = %.4f \pm %.4f$' % (numpy.median(plotthis[numpy.isfinite(plotthis)]),
                                                                        1.4826*numpy.median(numpy.fabs(plotthis[numpy.isfinite(plotthis)]-numpy.median(plotthis[numpy.isfinite(plotthis)])))),
                                bottom_left=True,size=14.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Exemple #14
0
def plotDFResults1D(options,args):
    #First load the results
    #Load g and k fits
    options.sample= 'g'
    options.select= 'all'
    gfits= calcDFResults(options,[_GFIT])
    options.sample= 'k'
    options.select= 'program'   
    kfits= calcDFResults(options,[_KFIT])
    #Setup plane
    tightbinned= pixelAfeFeh(None,dfeh=options.dfeh,dafe=options.dafe,
                             fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                             afemax=0.55) 
    #Setup plotting
    bovy_plot.bovy_print(fig_height=8.,fig_width=8.,
                         axes_labelsize=11,xtick_labelsize=7,
                         ytick_labelsize=7,
                         xtick_major_size=2,
                         xtick_minor_size=1,
                         ytick_major_size=2,
                         ytick_minor_size=1)
    nullfmt   = NullFormatter()         # no labels
    if options.subtype.lower() == 'regular':
        npanels= 5
        keys= ['rd','zh','dlnvcdlnr','plhalo','vc']
        scale= [_REFR0,_REFR0*1000.,1.,1.,1.]
        ranges=[[1.5,4.5],
                [100.,800.],
                [-0.3,0.1],
                [0.,3.],
                [180.,260.]]
        labels=[r'$R_d^{\mathrm{MN}}\ [\mathrm{kpc}]$',
                r'$z_h^{\mathrm{MN}}\ [\mathrm{pc}]$',
                r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$',
                r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$',
                r'$V_c\ [\mathrm{km\,s}^{-1}]$']                
        ticks= [[2.,3.,4.],
                [100.,300.,500.,700.],
                [-0.3,-0.1,0.1],
                [0.,1.5,3.],
                [180.,220.,260.]]
    elif options.subtype.lower() == 'valueadded':
        npanels= 4
        keys= ['rdexp','zhexp','surfzdisk','rhodm']
        scale= [_REFR0,_REFR0*1000.,1.,1.]
        ranges=[[1.5,4.5],
                [100.,800.],
                [40.,80.],
                [0.,0.02]]
        ticks= [[2.,3.,4.],
                [100.,300.,500.,700.],
                [40.,60.,80.],
                [0.,0.01,0.02]]
        labels=[r'$R_d^{\mathrm{Exp}}\ [\mathrm{kpc}]$',
                r'$z_h^{\mathrm{Exp}}\ [\mathrm{pc}]$',
                r'$\Sigma_{\mathrm{disk}}(R_0)\ [M_{\odot}\,\mathrm{pc}^{-2}]$',
                r'$\rho_{\mathrm{DM}}\,(R_0,0)\ [M_{\odot}\,\mathrm{pc}^{-3}]$']
    nrows= 2
    xrange=[-1.6,0.5]
    yrange=[-0.05,0.55]
    dx= 0.8/npanels
    dy= dx#*(yrange[1]-yrange[0])/(xrange[1]-xrange[0])
    allaxes= []
    for jj in range(nrows):
        for ii in range(npanels):
            if jj == 0: thesefits= gfits
            else: thesefits= kfits
            #Gather results
            plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
            key= keys[ii]
            for tt in range(tightbinned.npixfeh()):
                for rr in range(tightbinned.npixafe()):
                    tfeh= tightbinned.feh(tt)
                    tafe= tightbinned.afe(rr)
                    if numpy.amin((thesefits['feh']-tfeh)**2./options.dfeh**2.+(thesefits['afe']-tafe)**2./options.dafe**2.) > 0.:
                        plotthis[tt,rr]= numpy.nan
                        continue
                    tindx= numpy.argmin((thesefits['feh']-tfeh)**2./options.dfeh**2.+(thesefits['afe']-tafe)**2./options.dafe**2.)
                    plotthis[tt,rr]= thesefits[key][tindx]
            left, bottom, width, height= 0.1+ii*dx, 0.1+dy*(1-jj), dx, dy
            ax= pyplot.axes([left,bottom,width,height])
            allaxes.append(ax)
            fig= pyplot.gcf()
            fig.sca(ax)
            out= bovy_plot.bovy_dens2d(plotthis.T*scale[ii],
                                       origin='lower',cmap='jet',
                                       interpolation='nearest',
                                       xrange=xrange,yrange=yrange,
                                       vmin=ranges[ii][0],vmax=ranges[ii][1],
                                       contours=False,overplot=True,
                                       colorbar=False,aspect='auto')
            if jj == 1:
                bovy_plot._add_axislabels(r'$[\mathrm{Fe/H}]$',None)
            if ii == 0:
                bovy_plot._add_axislabels(None,r'$[\alpha/\mathrm{Fe}]$')
            if jj == 0:
                ax.xaxis.set_major_formatter(nullfmt)
            if ii > 0:
                ax.yaxis.set_major_formatter(nullfmt)
            if jj == 0:
                #Add colorbar
                left, bottom, width, height= 0.1+ii*dx, 0.1+2.*dy*(1-jj), dx, dy
                ax= pyplot.axes([left,bottom,width,height],frameon=False)
                ax.xaxis.set_major_formatter(nullfmt)
                ax.yaxis.set_major_formatter(nullfmt)
                ax.yaxis.set_tick_params(size=0)
                ax.xaxis.set_tick_params(size=0)
                allaxes.append(ax)
                fig.sca(ax)
                CB1= pyplot.colorbar(out,shrink=0.85,orientation='horizontal',
                                     fraction=0.25,ticks=ticks[ii])
                CB1.set_label(labels[ii],labelpad=-30)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Exemple #15
0
def plotActionData(options,args):
    #Read the data
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Setup error mc integration
    options.nmcerr= 1#in case this isn't set correctly
    raw, errstuff= setup_err_mc(raw,options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    #print numpy.argmin((fehs+0.25)**2.+(afes-0.175)**2.)
    #Setup potential
    params= numpy.array([-1.33663190049,0.998420232634,-3.49031638164,0.31949840593,-1.63965169376])
    try:
        pot= setup_potential(params,options,0)#Assume that the potential parameters come from a file with a single set of df parameters first
    except RuntimeError: #if this set of parameters gives a nonsense potential
        raise
    ro= 1.
    vo= params[1]
    aA= setup_aA(pot,options)
    jr, lz, jz= [], [], []
    #Get data ready
    params= [None,None,None,None,None,None,params[0],params[1],params[2],params[3],params[4]]
    for indx in range(len(fehs)):
        if numpy.log(monoAbundanceMW.hr(fehs[indx],afes[indx],k=(options.sample.lower() == 'k'))/8.) > -0.5 :
            continue
        R,vR,vT,z,vz,e,ee,eee= prepare_coordinates(params,indx,fehs,afes,binned,
                                          errstuff,
                                          options,1)
        tjr, tlz, tjz= aA(R.flatten(),vR.flatten(),vT.flatten(),z.flatten(),vz.flatten())
        jr.extend(list(tjr))
        lz.extend(list(tlz))
        jz.extend(list(tjz))
    #Now plot
    jr= numpy.array(jr).flatten()*ro*vo*_REFR0*_REFV0
    lz= numpy.array(lz).flatten()*ro*vo*_REFR0*_REFV0
    jz= numpy.array(jz).flatten()*ro*vo*_REFR0*_REFV0
    bovy_plot.bovy_print()
    levels= special.erf(numpy.sqrt(0.5)*numpy.arange(1,3))
    levels= list(levels)
    levels.append(1.01)
    print len(jr)
    if options.type.lower() == 'lzjr':
        axScatter, axHistx,axHisty= bovy_plot.scatterplot(lz/220.,jr/220.,',',
                              xlabel=r'$L_z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              ylabel=r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              xrange=[0.,3600./220.],
                              yrange=[0.,500./220.],
                              onedhists=True,
                              bins=41,
                              levels=levels,retAxes=True)
        axScatter.set_xlim(0.,3600./220.)
        axScatter.set_ylim(0.,500./220.)
        axScatter.set_xlabel(r'$L_z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axScatter.set_ylabel(r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axHistx.set_xlim( axScatter.get_xlim() )
        axHisty.set_ylim( axScatter.get_ylim() )
        #Calculate locus of 6 kpc pericenter
        nlzs= 1001
        plzs= numpy.linspace(0.,6./8.,nlzs)
        pjrs= numpy.zeros(nlzs)
        for ii in range(nlzs):
            pjrs[ii]= aA(6./8.,0.,plzs[ii]/6.*8.,0.,0.)[0]*ro*vo*_REFR0*_REFV0
        bovy_plot.bovy_plot(plzs*ro*vo*_REFR0*_REFV0/220.,
                            pjrs/220.,'k--',overplot=True)
        plzs= numpy.linspace(11./8.,2.,nlzs)
        pjrs= numpy.zeros(nlzs)
        for ii in range(nlzs):
            pjrs[ii]= aA(11./8.,0.,plzs[ii]/11.*8.,0.,0.)[0]*ro*vo*_REFR0*_REFV0
        bovy_plot.bovy_plot(plzs*ro*vo*_REFR0*_REFV0/220.,
                            pjrs/220.,'k--',overplot=True)
    elif options.type.lower() == 'jrjz':
        axScatter, axHistx, axHisty= bovy_plot.scatterplot(jr/220.,jz/220.,color='k',marker=',',ls='none',
                              xlabel=r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              ylabel=r'$J_Z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              xrange=[0.,500./220.],
                              yrange=[0.,250./220.],
                              bins=41,
                              onedhists=True,
                              levels=levels,
                                                           retAxes=True)
        axScatter.set_xlim(0.,500./220.)
        axScatter.set_ylim(0.,250./220.)
        axScatter.set_ylabel(r'$J_Z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axScatter.set_xlabel(r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axHistx.set_xlim( axScatter.get_xlim() )
        axHisty.set_ylim( axScatter.get_ylim() )
    #if options.sample == 'g':
    #    bovy_plot.bovy_text(r'$\mathrm{G\!-\!type\ dwarfs}$',top_right=True,size=16.)
    #elif options.sample == 'k':
    #    bovy_plot.bovy_text(r'$\mathrm{K\!-\!type\ dwarfs}$',top_right=True,size=16.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Exemple #16
0
def testDFNorm(options,args):
    #Read the data
    print "Reading the data ..."
    if options.sample.lower() == 'g':
        if not options.fakedata is None:
            raw= read_gdwarfs(options.fakedata,logg=True,ebv=True,sn=options.snmin,nosolar=True)
        elif options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin,nosolar=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin,nosolar=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin,nosolar=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin,nosolar=True)
    if not options.bmin is None:
        #Cut on |b|
        raw= raw[(numpy.fabs(raw.b) > options.bmin)]
    if not options.fehmin is None:
        raw= raw[(raw.feh >= options.fehmin)]
    if not options.fehmax is None:
        raw= raw[(raw.feh < options.fehmax)]
    if not options.afemin is None:
        raw= raw[(raw.afe >= options.afemin)]
    if not options.afemax is None:
        raw= raw[(raw.afe < options.afemax)]
    if not options.plate is None and not options.loo:
        raw= raw[(raw.plate == options.plate)]
    elif not options.plate is None:
        raw= raw[(raw.plate != options.plate)]
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    if not options.singlefeh is None:
        if options.loo:
            pass
        else:
            #Set up single feh
            indx= binned.callIndx(options.singlefeh,options.singleafe)
            if numpy.sum(indx) == 0:
                raise IOError("Bin corresponding to singlefeh and singleafe is empty ...")
            data= copy.copy(binned.data[indx])
            print "Using %i data points ..." % (len(data))
            #Bin again
            binned= pixelAfeFeh(data,dfeh=options.dfeh,dafe=options.dafe)
            fehs, afes= [], []
            for ii in range(len(binned.fehedges)-1):
                for jj in range(len(binned.afeedges)-1):
                    data= binned(binned.feh(ii),binned.afe(jj))
                    if len(data) < options.minndata:
                        continue
                    fehs.append(binned.feh(ii))
                    afes.append(binned.afe(jj))
            nabundancebins= len(fehs)
            fehs= numpy.array(fehs)
            afes= numpy.array(afes)
    #Setup everything for the selection function
    print "Setting up stuff for the normalization integral ..."
    normintstuff= setup_normintstuff(options,raw,binned,fehs,afes)
    if not options.init is None:
        #Load initial parameters from file
        savefile= open(options.init,'rb')
        params= pickle.load(savefile)
        savefile.close()
    else:
        #First initialization
        params= initialize(options,fehs,afes)
    #Now perform tests
    if options.type.lower() == 'hr':
        testDFNormhr(params,fehs,afes,binned,options,normintstuff)
    elif options.type.lower() == 'sr':
        testDFNormsr(params,fehs,afes,binned,options,normintstuff)
    elif options.type.lower() == 'vo':
        testDFNormvo(params,fehs,afes,binned,options,normintstuff)
Exemple #17
0
def plotbestr(options,args):
    """Make a plot of a quantity's best-fit vs. FeH and aFe"""
    if options.sample.lower() == 'g':
        npops= 62
    elif options.sample.lower() == 'k':
        npops= 54
    if options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    savefile.close()
    #First calculate the derivative properties
    if not options.multi is None:
        derivProps= multi.parallel_map((lambda x: calcAllSurfErr(x,options,args)),
                                  range(npops),
                                  numcores=numpy.amin([options.multi,
                                                       npops,
                                                       multiprocessing.cpu_count()]))
    else:
        derivProps= []
        for ii in range(npops):
            derivProps.append(calcAllSurfErr(ii,options,args))
    #If a second argument is given, this gives a set of rs at which also to calculate the surface density
    if len(args) > 1:
        if os.path.exists(args[1]):
            surffile= open(args[1],'rb')
            altsurfrs= pickle.load(surffile)
            surffile.close()
            calcExtra= True
        else:
            raise IOError("extra savefilename with surface-densities has to exist when it is specified")
    else:
        calcExtra= False
    if not calcExtra: #Fiducial, for which we also calculate everything at the mean radius of each MAP
        #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(npops)
        for ii in range(npops):
            data= pix(fehs[ii],afes[ii])
            vals= data.densrmean*8.
            if False:#True:
                rmean[ii]= numpy.mean(vals)
            else:
                rmean[ii]= numpy.median(vals)
    #Load into plotthis
    plotthis= numpy.zeros(npops)+numpy.nan
    plotthis_y= numpy.zeros(npops)+numpy.nan
    plotthis_y_err= numpy.zeros(npops)+numpy.nan
    plotthiskz_y= numpy.zeros(npops)+numpy.nan
    plotthiskz_y_err= numpy.zeros(npops)+numpy.nan
    altplotthis= numpy.zeros(npops)+numpy.nan
    altplotthis_y= numpy.zeros(npops)+numpy.nan
    altplotthis_y_err= numpy.zeros(npops)+numpy.nan
    altplotthiskz_y= numpy.zeros(npops)+numpy.nan
    altplotthiskz_y_err= numpy.zeros(npops)+numpy.nan
    for ii in range(npops):
        if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                         k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                or (options.sample.lower() == 'g' and (ii < 0 or ii == 50)) \
                or (options.sample.lower() == 'k' and ii < 7):
            continue
        #Determine best-r
        #indx= numpy.argmin(derivProps[ii][:,2]/numpy.fabs(derivProps[ii][:,1]))
        indx= numpy.argmin(numpy.fabs(derivProps[ii][:,2]))
        if indx == 0: indx= int(numpy.floor(numpy.random.uniform()*10))
        plotthis[ii]= derivProps[ii][indx,0]
        plotthis_y[ii]= derivProps[ii][indx,1]
        plotthis_y_err[ii]= derivProps[ii][indx,3]
        plotthiskz_y[ii]= derivProps[ii][indx,4]
        plotthiskz_y_err[ii]= derivProps[ii][indx,5]
        if calcExtra:
            indx= numpy.argmin(numpy.fabs(derivProps[ii][:,0]-altsurfrs[ii]))
            altplotthis[ii]= derivProps[ii][indx,0]
            altplotthis_y[ii]= derivProps[ii][indx,1]
            altplotthis_y_err[ii]= derivProps[ii][indx,3]           
            altplotthiskz_y[ii]= derivProps[ii][indx,4]
            altplotthiskz_y_err[ii]= derivProps[ii][indx,5]           
        else:
            indx= numpy.argmin(numpy.fabs(derivProps[ii][:,0]-rmean[ii]))
            altplotthis[ii]= derivProps[ii][indx,0]
            altplotthis_y[ii]= derivProps[ii][indx,1]
            altplotthis_y_err[ii]= derivProps[ii][indx,3]           
            altplotthiskz_y[ii]= derivProps[ii][indx,4]
            altplotthiskz_y_err[ii]= derivProps[ii][indx,5]           
    #Now plot
    bovy_plot.bovy_print()
    monoAbundanceMW.plotPixelFunc(fehs,afes,plotthis,
                                  zlabel=r'$R_\Sigma\ (\mathrm{kpc})$')
    bovy_plot.bovy_end_print(options.outfilename)
    bovy_plot.bovy_print()
    print plotthis, plotthis_y
    bovy_plot.bovy_plot(plotthis,plotthis_y,'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.],#,numpy.nanmin(plotthis_y)-10.,
#                                numpy.nanmax(plotthis_y)+10.],
                        semilogy=True)
    pyplot.errorbar(plotthis,
                    plotthis_y,
                    yerr=plotthis_y_err,
                    elinewidth=1.,capsize=3,zorder=0,
                    color='k',linestyle='none')  
    trs= numpy.linspace(4.3,9.,1001)
    pyplot.plot(trs,72.*numpy.exp(-(trs-8.)/3.),'k--')
    pyplot.plot(trs,72.*numpy.exp(-(trs-8.)/2.),'k-.')
    pyplot.plot(trs,72.*numpy.exp(-(trs-8.)/4.),'k:')
    #Fit exponential
    #indx= (plotthis < 8.)
    #plotthis= plotthis[indx]
    #plotthis_y= plotthis_y[indx]
    #plotthis_y_err= plotthis_y_err[indx]
    exp_params= optimize.fmin_powell(expcurve,
                                     numpy.log(numpy.array([72.,2.5])),
                                     args=(plotthis,plotthis_y,plotthis_y_err))
    pyplot.plot(trs,numpy.exp(exp_params[0]-(trs-8.)/numpy.exp(exp_params[1])),
                'k-',lw=2.)
    print numpy.exp(exp_params) 
    bovy_plot.bovy_end_print(options.outfilename.replace('.png','_rvssurf.png'))
    #Save
    if calcExtra:
        save_pickles(options.outfilename.replace('.png','_rvssurf.sav'),
                     plotthis,plotthis_y,plotthis_y_err,
                     plotthiskz_y,plotthiskz_y_err,
                     altplotthis,altplotthis_y,altplotthis_y_err,
                     altplotthiskz_y,altplotthiskz_y_err)
    else:
        save_pickles(options.outfilename.replace('.png','_rvssurf.sav'),
                     plotthis,plotthis_y,plotthis_y_err,
                     plotthiskz_y,plotthiskz_y_err,
                     altplotthis,altplotthis_y,altplotthis_y_err,
                     altplotthiskz_y,altplotthiskz_y_err)
    return None        
Exemple #18
0
def plotOrbits(parser):
    options,args= parser.parse_args()
    if not os.path.exists(args[0]):
        print args[0]+" does not exist ..."
        print "Returning ..."
        return None
    if options.plotfile is None:
        print "-o or --plotfile needs to be set ..."
        print "Returning ..."
        return None
    #Load orbits
    savefile= open(args[0],'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=options.dfeh,dafe=options.dafe,fehmin=-1.6,
                     fehmax=0.5,afemin=-0.05,afemax=0.55)
    #Run through the pixels and gather
    plotthis= numpy.zeros((pix.npixfeh(),pix.npixafe()))
    for ii in range(pix.npixfeh()):
        for jj in range(pix.npixafe()):
            data= pix(pix.feh(ii),pix.afe(jj))
            if len(data) < options.minndata:
                plotthis[ii,jj]= numpy.nan
                continue
            if options.type == 'rmean':
                vals= data.rmean*8.
            elif options.type == 'densrmean':
                vals= data.densrmean*8.
            elif options.type == 'vzrmean':
                vals= data.vzrmean*8.
            elif options.type == 'e':
                vals= data.e
            elif options.type == 'rap':
                vals= data.rap*8.
            elif options.type == 'rperi':
                vals= data.rperi*8.
            elif options.type == 'zmax':
                vals= data.zmax*8.
            elif options.type == 'vphi':
                vals= data.vyc+220.
            if options.type == 'nstars':
                plotthis[ii,jj]= len(data)
            else:
                if options.mean:
                    plotthis[ii,jj]= numpy.mean(vals)
                else:
                    plotthis[ii,jj]= numpy.median(vals)
    #Set up plot
    if options.type == 'rmean':
        vmin, vmax= 6., 10.
        zlabel=r'$R_{\mathrm{mean}}\ [\mathrm{kpc}]$'
    elif  options.type == 'densrmean' \
            or options.type == 'vzrmean':
        vmin, vmax= 4.5, 10.
        zlabel=r'$R_{\mathrm{mean}}\ [\mathrm{kpc}]$'    
    elif options.type == 'rap':
        vmin, vmax= 6., 10.
        zlabel=r'$R_{\mathrm{apo}}\ [\mathrm{kpc}]$'
    elif options.type == 'rperi':
        vmin, vmax= 6., 10.
        zlabel=r'$R_{\mathrm{peri}}\ [\mathrm{kpc}]$'
    elif options.type == 'zmax':
        vmin, vmax= .7, 4.
        zlabel=r'$Z_{\mathrm{max}}\ [\mathrm{kpc}]$'
    elif options.type == 'vphi':
        vmin, vmax= 140.,250.
        zlabel=r'$v_{\phi}\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'e':
        vmin, vmax= 0.,1.
        zlabel=r'$\mathrm{eccentricity}$'
    elif options.type == 'nstars':
        vmin, vmax= 0.,550.
        zlabel=r'$\mathrm{number\ of\ stars}$'
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xrange=[-1.6,0.5],
                          yrange=[-0.05,0.55],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          zlabel=zlabel,
                          vmin=vmin,vmax=vmax,
                          contours=False,
                          colorbar=True,shrink=0.78)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
Exemple #19
0
def plotComps(options,args,comps):
    raw= readRealData(options,args)
    raw= _append_field_recarray(raw,'comps',comps)
    pix= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05,fehmin=-1.6,
                     fehmax=0.5,afemin=-0.05,afemax=0.55)
    plotthis= numpy.zeros((pix.npixfeh(),pix.npixafe()))
    for ii in range(pix.npixfeh()):
        for jj in range(pix.npixafe()):
            data= pix(pix.feh(ii),pix.afe(jj))
            if len(data) < 100:
                plotthis[ii,jj]= numpy.nan
                continue
            plotthis[ii,jj]= numpy.mean(data.comps)
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg',
                          interpolation='nearest',
                          xrange=[-1.6,0.5],
                          yrange=[-0.05,0.55],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          zlabel=r'$\mathrm{fraction\ of\ stars\ in\ thick\ component}$',
#                          vmin=vmin,vmax=vmax,
                          colorbar=True,shrink=0.78,
                          contours=False)
    #Overplot contours of the underlying components
    #Restore deconvolution
    outfile= open(options.xdfile,'rb')
    xamp= pickle.load(outfile)
    xmean= pickle.load(outfile)
    xcovar= pickle.load(outfile)
    outfile.close()
    from matplotlib import pyplot
    from matplotlib.patches import Ellipse
    eigs1= numpy.linalg.eig(xcovar[0,:,:])
    eigs2= numpy.linalg.eig(xcovar[1,:,:])
    angle1= math.atan(-eigs1[1][0,1]/eigs1[1][1,1])/numpy.pi*180.
    angle2= math.atan(-eigs2[1][0,1]/eigs2[1][1,1])/numpy.pi*180.
    thisellipse= Ellipse(xmean[0,:],2.*numpy.sqrt(eigs1[0][0]),
                         2*numpy.sqrt(eigs1[0][1]),angle1)
    ells= [thisellipse]
    ells.append(Ellipse(xmean[0,:],4.*numpy.sqrt(eigs1[0][0]),
                        4*numpy.sqrt(eigs1[0][1]),angle1))
    ells.append(Ellipse(xmean[0,:],6.*numpy.sqrt(eigs1[0][0]),
                        6*numpy.sqrt(eigs1[0][1]),angle1))
    ells.append(Ellipse(xmean[1,:],2.*numpy.sqrt(eigs2[0][0]),
                        2*numpy.sqrt(eigs2[0][1]),angle2))
    ells.append(Ellipse(xmean[1,:],4.*numpy.sqrt(eigs2[0][0]),
                        4*numpy.sqrt(eigs2[0][1]),angle2))
    ells.append(Ellipse(xmean[1,:],6.*numpy.sqrt(eigs2[0][0]),
                        6*numpy.sqrt(eigs2[0][1]),angle2))
    ax= pyplot.gca()
    xlims= ax.get_xlim()
    ylims= ax.get_ylim()
    for e in ells:
        ax.add_artist(e)
        e.set_facecolor('none')
        e.set_edgecolor('0.85')
        e.set_linestyle('dashed')
    ax.set_xlim(xlims)
    ax.set_ylim(ylims)
    bovy_plot.bovy_end_print(options.compsplotfile)
Exemple #20
0
def plotTilt(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile1
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
    #Uncertainties are in savefile2
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
        velerrors= True
    else:
        velsamples= None            
        velerrors= False
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'zfunc' \
            or options.type.lower() == 'afefeh':
        plotthis= []
        errors= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(velfits) \
                    or afeindx+fehindx*binned.npixafe() >= len(velfits):
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'zfunc' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            if thisvelfit is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'zfunc' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'zfunc' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if options.type == 'tilt':
                plotthis[ii,jj]= numpy.arctan(thisvelfit[9])/_DEGTORAD
            elif options.type == 'tiltslope':
                plotthis[ii,jj]= thisvelfit[10]
            elif options.type == 'srz':
                plotthis[ii,jj]= (numpy.exp(2.*thisvelfit[5])-numpy.exp(2.*thisvelfit[1]))*thisvelfit[9]/(1.-thisvelfit[9]**2.)
            elif options.type.lower() == 'afe' \
                    or options.type.lower() == 'feh' \
                    or options.type.lower() == 'fehafe' \
                    or options.type.lower() == 'zfunc' \
                    or options.type.lower() == 'afefeh':
                thisplot=[tightbinned.feh(ii),
                          tightbinned.afe(jj),
                          len(data)]
                thisplot.extend(thisvelfit)
                #Als find min and max z for this data bin, and median
                if options.subtype.lower() == 'rfunc':
                    zsorted= sorted(numpy.sqrt((8.-data.xc)**2.+data.yc**2.))
                else:
                    zsorted= sorted(numpy.fabs(data.zc+_ZSUN))
                zmin= zsorted[int(numpy.ceil(0.16*len(zsorted)))]
                zmax= zsorted[int(numpy.floor(0.84*len(zsorted)))]
                zmin= zsorted[int(numpy.ceil(0.025*len(zsorted)))]
                zmax= zsorted[int(numpy.floor(0.975*len(zsorted)))]
                if options.pivotmean:
                    thisplot.extend([zmin,zmax,numpy.mean(numpy.fabs(data.zc+_ZSUN))])
                else:
                    thisplot.extend([zmin,zmax,numpy.median(numpy.fabs(data.zc+_ZSUN))])
                plotthis.append(thisplot)
                #Errors
                if velerrors:
                    theseerrors= []
                    thesesamples= velsamples[afeindx+fehindx*binned.npixafe()]
                    for kk in [1,4,5,8]:
                        xs= numpy.array([s[kk] for s in thesesamples])
                        theseerrors.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                    for kk in [0,2,3,6,7,9,10]: #,11]:
                        xs= numpy.array([s[kk] for s in thesesamples])
                        theseerrors.append(numpy.std(xs))
                        errors.append(theseerrors)
    #Set up plot
    #print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    if options.type == 'tilt':
        print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
        vmin, vmax= -20.,20.
        zlabel= r'$\mathrm{tilt\ at}\ Z = 0\ [\mathrm{degree}]$'
    elif options.type == 'tiltslope':
        print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
        vmin, vmax= -2.,2.
        zlabel= r'$\frac{\mathrm{d}\tan \mathrm{tilt}}{\mathrm{d} (Z/R)}$'
    elif options.type == 'srz':
        vmin, vmax= -100.,100.
        zlabel= r'$\sigma^2_{RZ}\ [\mathrm{km}^2\, \mathrm{s}^{-2}]$'
    elif options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.6,0.4
        zlabel=r'$[\mathrm{Fe/H}]$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.6]
        yrange=[-0.1,0.6]
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        #Gather everything
        zmin, zmax, pivot, tilt, tiltp1, tiltp2, afe, feh, ndata= [], [], [], [], [], [], [], [], []
        tilt_err, tiltp1_err, tiltp2_err= [], [], []
        for ii in range(len(plotthis)):
            if velerrors:
                tilt_err.append(errors[ii][9])
                tiltp1_err.append(errors[ii][10])
#                tiltp2_err.append(errors[ii][11])
            tilt.append(plotthis[ii][11])
            tiltp1.append(plotthis[ii][12])
#            tiltp2.append(plotthis[ii][13])
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][4])
            zmin.append(plotthis[ii][13])
            zmax.append(plotthis[ii][14])
            pivot.append(plotthis[ii][15])
        indxarray= numpy.array([True for ii in range(len(plotthis))],dtype='bool')
        tilt= numpy.array(tilt)[indxarray]
        tiltp1= numpy.array(tiltp1)[indxarray]
#        tiltp2= numpy.array(tiltp2)[indxarray]
        pivot= numpy.array(pivot)[indxarray]
        zmin= numpy.array(zmin)[indxarray]
        zmax= numpy.array(zmax)[indxarray]
        if velerrors:
            tilt_err= numpy.array(tilt_err)[indxarray]
            tiltp1_err= numpy.array(tiltp1_err)[indxarray]
#            tiltp2_err= numpy.array(tiltp2_err)[indxarray]
        afe= numpy.array(afe)[indxarray]
        feh= numpy.array(feh)[indxarray]
        ndata= numpy.array(ndata)[indxarray]
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata))
        #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        if options.subtype.lower() == 'zfunc':
            from selectFigs import _squeeze
            colormap = cm.jet
            #Set up plot
            yrange= [-30.,30.]
            ylabel=r'$\mathrm{tilt}(Z|R=8\,\mathrm{kpc})\ [\mathrm{degree}]$'
            bovy_plot.bovy_plot([-100.,-100.],[100.,100.],'k,',
                                xrange=[0,2700],yrange=yrange,
                                xlabel=r'$|z|\ [\mathrm{pc}]$',
                                ylabel=ylabel)
            #Calculate and plot all zfuncs
            for ii in numpy.random.permutation(len(afe)):
                if velerrors: #Don't plot if errors > 30%
                    if tilt_err[ii]/tilt[ii] > .2: continue
                ds= numpy.linspace(zmin[ii]*1000.,zmax[ii]*1000.,1001)/8000.
                thiszfunc= numpy.arctan(tilt[ii]+tiltp1[ii]*ds)/_DEGTORAD #+tiltp2[ii]*ds**2.
                pyplot.plot(numpy.linspace(zmin[ii]*1000.,1000*zmax[ii],1001),
                            thiszfunc,'-',
                            color=colormap(_squeeze(plotc[ii],vmin,vmax)),
                            lw=ndata[ii]/15.)
                if not options.nofatdots:
                    #Also plot pivot
                    pyplot.plot(1000.*pivot[ii],
                                numpy.arctan(tilt[ii]+tiltp1[ii]*pivot[ii]/8.\
                                    +tiltp2[ii]*(pivot[ii]/8.)**2.)/_DEGTORAD,
                                'o',ms=8.,mec='none',
                                color=colormap(_squeeze(plotc[ii],vmin,vmax)))
            #Add colorbar
            m = cm.ScalarMappable(cmap=cm.jet)
            m.set_array(plotc)
            m.set_clim(vmin=vmin,vmax=vmax)
            cbar= pyplot.colorbar(m,fraction=0.15)
            cbar.set_clim((vmin,vmax))
            cbar.set_label(zlabel)
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              contours=False,
                              colorbar=True,shrink=0.78)
        bovy_plot.bovy_text(r'$\mathrm{median} = %.2f \pm %.2f$' % (numpy.median(plotthis[numpy.isfinite(plotthis)]),
                                                                    1.4826*numpy.median(numpy.fabs(plotthis[numpy.isfinite(plotthis)]-numpy.median(plotthis[numpy.isfinite(plotthis)])))),
                            bottom_left=True,size=14.)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
def plotVelComparisonDFMulti(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    gafes, gfehs, left_legend= getMultiComparisonBins(options)
    if options.usemedianpotential:
        potparams= get_median_potential(options,nabundancebins)
        print "Median potential parameters: ", potparams
    M= len(gfehs)
    #Check whether fits exist, if not, pop
    removeBins= numpy.ones(M,dtype='bool')
    for jj in range(M):
        #Find pop corresponding to this bin
        pop= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
        #Load savefile
        if not options.init is None:
            #Load initial parameters from file
            savename= options.init
            spl= savename.split('.')
            newname= ''
            for ll in range(len(spl)-1):
                newname+= spl[ll]
                if not ll == len(spl)-2: newname+= '.'
            newname+= '_%i.' % pop
            newname+= spl[-1]
            if not os.path.exists(newname):
                removeBins[jj]= False
        else:
            raise IOError("base filename not specified ...")
    if numpy.sum(removeBins) == 0:
        raise IOError("None of the group bins have been fit ...")
    elif numpy.sum(removeBins) < M:
        #Some bins have not been fit yet, and have to be remove
        gfehs= list((numpy.array(gfehs))[removeBins])
        gafes= list((numpy.array(gafes))[removeBins])
        print "Only using %i bins out of %i ..." % (numpy.sum(removeBins),M)
        M= len(gfehs)
    data= []
    zs= []
    velps= numpy.zeros((len(binned.data),options.nv))
    velps[:,:]= numpy.nan
    velps2= numpy.zeros((len(binned.data),options.nv))
    velps2[:,:]= numpy.nan
    velps3= numpy.zeros((len(binned.data),options.nv))
    velps3[:,:]= numpy.nan
    cumulndata= 0
    if options.type.lower() == 'vz':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-180.,180.,options.nv)
            xrange=[-180.,180.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-120.,120.,options.nv)
            xrange=[-120.,120.]
            bins= 26
        xlabel=r'$V_Z\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vr':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-220.,220.,options.nv)
            xrange=[-220.,220.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 26
        xlabel=r'$V_R\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vt':
        if options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        xlabel=r'$V_T\ [\mathrm{km\,s}^{-1}]$'
    for jj in range(M):
        print "Working on group %i / %i ..." % (jj+1,M)
        #Find pop corresponding to this bin
        pop= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
        #Load savefile
        if not options.init is None:
            #Load initial parameters from file
            savename= options.init
            spl= savename.split('.')
            newname= ''
            for ll in range(len(spl)-1):
                newname+= spl[ll]
                if not ll == len(spl)-2: newname+= '.'
            newname+= '_%i.' % pop
            newname+= spl[-1]
            savefile= open(newname,'rb')
            tparams= pickle.load(savefile)
            savefile.close()
        else:
            raise IOError("base filename not specified ...")
        if options.usemedianpotential:
            tparams= set_potparams(potparams,tparams,options,1)
        print tparams
        thisdata= binned(fehs[pop],afes[pop])
        velps[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
        alts= True
        if alts:
            if not options.usemedianpotential:
                potparams= get_potparams(tparams,options,1)
            if options.potential.lower() == 'flatlog':
                tparams= set_potparams([potparams[0]*1.05,potparams[1]],
                                       tparams,options,1)
                velps2[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
                tparams= set_potparams([potparams[0]*0.95,potparams[1]],
                                       tparams,options,1)
                velps3[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
        #Also add the correct data
        vo= get_vo(tparams,options,1)
        ro= get_ro(tparams,options)
        if 'vr' in options.type.lower() or 'vt' in options.type.lower():
            R= ((ro*_REFR0-thisdata.xc)**2.+thisdata.yc**2.)**(0.5)
            cosphi= (_REFR0*ro-thisdata.xc)/R
            sinphi= thisdata.yc/R
            vR= -(thisdata.vxc-_VRSUN)*cosphi+(thisdata.vyc+_VTSUN)*sinphi
            vT= (thisdata.vxc-_VRSUN)*sinphi+(thisdata.vyc+_VTSUN)*cosphi
        if options.type.lower() == 'vz':
            data.extend(thisdata.vzc+_VZSUN)
        elif options.type.lower() == 'vr':
            data.extend(vR)
        elif options.type.lower() == 'vt':
            data.extend(vT)
        zs.extend(thisdata.zc)
        cumulndata+= len(thisdata)
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data,bins=26,normed=True,color='k',
                        histtype='step',
                        xrange=xrange,xlabel=xlabel)
    plotp= numpy.nansum(velps,axis=0)/cumulndata
    print numpy.sum(plotp)*(vs[1]-vs[0])
    bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
    if alts:
        plotp= numpy.nansum(velps2,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
        plotp= numpy.nansum(velps3,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
    if not left_legend is None:
        bovy_plot.bovy_text(left_legend,top_left=True,size=_legendsize)
    bovy_plot.bovy_text(r'$\mathrm{full\ subsample}$'
                        +'\n'+
                        '$%i \ \ \mathrm{stars}$' % 
                        len(data),top_right=True,
                        size=_legendsize)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_all.'+options.ext)
    if options.all: return None
    #Plot zranges
    zranges= [0.5,1.,1.5,2.,3.,4.]
    nzranges= len(zranges)-1
    zs= numpy.array(zs)
    data= numpy.array(data)
    for ii in range(nzranges):
        indx= (numpy.fabs(zs) >= zranges[ii])*(numpy.fabs(zs) < zranges[ii+1])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(data[indx],bins=26,normed=True,color='k',
                            histtype='step',
                            xrange=xrange,xlabel=xlabel)
        plotp= numpy.nansum(velps[indx,:],axis=0)/numpy.sum(indx)
        bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
        if alts:
            plotp= numpy.nansum(velps2[indx,:],axis=0)/numpy.sum(indx)
            bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
            plotp= numpy.nansum(velps3[indx,:],axis=0)/numpy.sum(indx)
            bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
        bovy_plot.bovy_text(r'$ %i\ \mathrm{pc} \leq |Z| < %i\ \mathrm{pc}$' % (int(1000*zranges[ii]),int(1000*zranges[ii+1]))
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            (numpy.sum(indx)),top_right=True,
                            size=_legendsize)
        bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_z%.1f_z%.1f.' % (zranges[ii],zranges[ii+1])+options.ext)
    return None
def plotVelComparisonDF(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    if not options.singlefeh is None:
        if True: #Just to keep indentation the same
            #Set up single feh
            indx= binned.callIndx(options.singlefeh,options.singleafe)
            if numpy.sum(indx) == 0:
                raise IOError("Bin corresponding to singlefeh and singleafe is empty ...")
            allraw= copy.copy(raw)
            raw= copy.copy(binned.data[indx])
            #newerrstuff= []
            #for ii in range(len(binned.data)):
            #    if indx[ii]: newerrstuff.append(errstuff[ii])
            #errstuff= newerrstuff
            print "Using %i data points ..." % (numpy.sum(indx))
            #Bin again
            binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
            fehs, afes= [], []
            for ii in range(len(binned.fehedges)-1):
                for jj in range(len(binned.afeedges)-1):
                    data= binned(binned.feh(ii),binned.afe(jj))
                    if len(data) < options.minndata:
                        continue
                    fehs.append(binned.feh(ii))
                    afes.append(binned.afe(jj))
            nabundancebins= len(fehs)
            fehs= numpy.array(fehs)
            afes= numpy.array(afes)
    if options.singles:
        run_abundance_singles_plotdens(options,args,fehs,afes)
        return None
    normintstuff= setup_normintstuff(options,raw,binned,fehs,afes,allraw)
    ##########POTENTIAL PARAMETERS####################
    potparams1= numpy.array([numpy.log(2.6/8.),230./220.,numpy.log(400./8000.),0.266666666,0.])
    potparams2= numpy.array([numpy.log(2.8/8.),230./220,numpy.log(400./8000.),0.266666666666,0.])
    #potparams2= numpy.array([numpy.log(2.5/8.),1.,numpy.log(400./8000.),0.466666,0.,2.])
    potparams3= numpy.array([numpy.log(2.6/8.),230./220.,
                             numpy.log(400./8000.),0.5333333,0.])
    pop= 0 #assume first population
    #Load savefile
    if not options.init is None:
        #Load initial parameters from file
        savename= options.init
#        spl= savename.split('.')
#        newname= ''
#        for ll in range(len(spl)-1):
#            newname+= spl[ll]
#            if not ll == len(spl)-2: newname+= '.'
#        newname+= '_%i.' % pop
#        newname+= spl[-1]
        savefile= open(savename,'rb')
        try:
            if not _NOTDONEYET:
                params= pickle.load(savefile)
                mlogl= pickle.load(savefile)
            logl= pickle.load(savefile)
        except:
            if savetopickle:
                save_pickles(tmpfiles[jj],None)
                return None
            else:
                return None
        finally:
            savefile.close()
    else:
        raise IOError("base filename not specified ...")
    logl[numpy.isnan(logl)]= -numpy.finfo(numpy.dtype(numpy.float64)).max   
    #Set DF parameters as the maximum at R_d=2.4, f_h=0.4
    #######DF PARAMETER RANGES###########
    lnhr, lnsr, lnsz, rehr, resr, resz= approxFitResult(fehs[0],afes[0],
                                                        relerr=True)
    #if rehr > 0.3: rehr= 0.3 #regularize
    if True: rehr= 0.3 #regularize
    #if resr > 0.3: resr= 0.3
    #if resz > 0.3: resz= 0.3
    if True: resr= 0.3
    if True: resz= 0.3
    hrs= numpy.linspace(-1.85714286,0.9,options.nhrs)
    #hrs= numpy.linspace(lnhr-1.5*rehr,lnhr+1.5*rehr,options.nhrs)
    if _VARYHSZ:
        srs= numpy.linspace(numpy.log(0.5),numpy.log(2.),options.nsrs)#hsz now
    else:
        srs= numpy.linspace(lnsr-0.6*resz,lnsr+0.6*resz,options.nsrs)#USE ESZ
    szs= numpy.linspace(lnsz-0.6*resz,lnsz+0.6*resz,options.nszs)
    #hrs= numpy.linspace(lnhr-0.3,lnhr+0.3,options.nhrs)
    #srs= numpy.linspace(lnsr-0.1,lnsr+0.1,options.nsrs)
    #szs= numpy.linspace(lnsz-0.1,lnsz+0.1,options.nszs)
    dvts= numpy.linspace(-0.35,0.05,options.ndvts)
    #dvts= numpy.linspace(-0.05,0.05,options.ndvts)
    pouts= numpy.linspace(10.**-5.,.5,options.npouts)
    #indx= numpy.unravel_index(numpy.argmax(logl[3,0,0,3,:,:,:,:,:,0,0]),
    indx= numpy.unravel_index(numpy.argmax(logl[3,0,0,4,:,:,:,0]),
                              logl[3,0,0,4,:,:,:,0].shape)
    #tparams= numpy.array([dvts[indx[3]],hrs[indx[0]],
    if _VARYHSZ:
        tparams= numpy.array([0.,hrs[indx[0]],
                              #srs[indx[1]-2.*(indx[1] != 0)],
                              #szs[indx[2]-2.*(indx[2] != 0)],
                              lnsr,
                              szs[indx[2]],
                              numpy.log(8./_REFR0),
                              srs[indx[1]],
                              0.0,#logl[3,0,0,10,indx[0],indx[1],indx[2],2],#pouts[indx[4]],
                              0.,0.,0.,0.,0.])
    else:
        tparams= numpy.array([0.,hrs[indx[0]],
                              #srs[indx[1]-2.*(indx[1] != 0)],
                              #szs[indx[2]-2.*(indx[2] != 0)],
                              srs[indx[1]],
                              szs[indx[2]],
                              numpy.log(8./_REFR0),
                              numpy.log(7./_REFR0),0.,#pouts[indx[4]],
                              0.,0.,0.,0.,0.])
    options.potential=  'dpdiskplhalofixbulgeflatwgasalt'
    tparams= set_potparams(potparams1,tparams,options,1)
    data= []
    zs= []
    velps= numpy.zeros((len(binned.data),options.nv))
    velps[:,:]= numpy.nan
    velps2= numpy.zeros((len(binned.data),options.nv))
    velps2[:,:]= numpy.nan
    velps3= numpy.zeros((len(binned.data),options.nv))
    velps3[:,:]= numpy.nan
    cumulndata= 0
    if options.type.lower() == 'vz':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-180.,180.,options.nv)
            xrange=[-180.,180.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-120.,120.,options.nv)
            xrange=[-120.,120.]
            bins= 26
        xlabel=r'$V_Z\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vr':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-220.,220.,options.nv)
            xrange=[-220.,220.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 26
        xlabel=r'$V_R\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vt':
        if options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        xlabel=r'$V_T\ [\mathrm{km\,s}^{-1}]$'
    thisdata= binned(fehs[pop],afes[pop])
    velps[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs,normintstuff=normintstuff)
    alts= True
    if alts:
        indx= numpy.unravel_index(numpy.argmax(logl[4,0,0,4,:,:,:,0]),
                                  logl[4,0,0,4,:,:,:,0].shape)
        #tparams= numpy.array([dvts[indx[3]],hrs[indx[0]],
        if not _VARYHSZ:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-1.*(indx[1] != 0)],
                                  #szs[indx[2]-1.*(indx[2] != 0)],
                                  srs[indx[1]],
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  numpy.log(7./_REFR0),0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.,0.])
        else:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-1.*(indx[1] != 0)],
                                  #szs[indx[2]-1.*(indx[2] != 0)],
                                  lnsr,
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  srs[indx[1]],0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.,0.])
        #options.potential= 'dpdiskplhalodarkdiskfixbulgeflatwgasalt'
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        tparams= set_potparams(potparams2,tparams,options,1)
        print "Working on model 2 ..."
        velps2[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
        indx= numpy.unravel_index(numpy.argmax(logl[3,0,0,8,:,:,:,0]),
                                  logl[3,0,0,8,:,:,:,0].shape)
        #tparams= numpy.array([dvts[indx[3]],hrs[indx[0]],
        if _VARYHSZ:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-2.*(indx[1] != 0)],
                                  #szs[indx[2]-2.*(indx[2] != 0)],
                                  lnsr,
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  srs[indx[1]],0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.])
        else:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-2.*(indx[1] != 0)],
                                  #szs[indx[2]-2.*(indx[2] != 0)],
                                  srs[indx[1]],
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  numpy.log(7./_REFR0),0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.])
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        tparams= set_potparams(potparams3,tparams,options,1)
        print "Working on model 3 ..."
        velps3[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
    #Also add the correct data
    vo= get_vo(tparams,options,1)
    ro= get_ro(tparams,options)
    if 'vr' in options.type.lower() or 'vt' in options.type.lower():
        R= ((ro*_REFR0-thisdata.xc)**2.+thisdata.yc**2.)**(0.5)
        cosphi= (_REFR0*ro-thisdata.xc)/R
        sinphi= thisdata.yc/R
        vR= -(thisdata.vxc-_VRSUN)*cosphi+(thisdata.vyc+_VTSUN)*sinphi
        vT= (thisdata.vxc-_VRSUN)*sinphi+(thisdata.vyc+_VTSUN)*cosphi
    if options.type.lower() == 'vz':
        data.extend(thisdata.vzc+_VZSUN)
    elif options.type.lower() == 'vr':
        data.extend(vR)
    elif options.type.lower() == 'vt':
        data.extend(vT)
    zs.extend(thisdata.zc)
    cumulndata+= len(thisdata)
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data,bins=26,normed=True,color='k',
                        histtype='step',
                        xrange=xrange,xlabel=xlabel)
    plotp= numpy.nansum(velps,axis=0)/cumulndata
    print numpy.sum(plotp)*(vs[1]-vs[0])
    bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
    if alts:
        plotp= numpy.nansum(velps2,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
        plotp= numpy.nansum(velps3,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
    bovy_plot.bovy_text(r'$\mathrm{full\ subsample}$'
                        +'\n'+
                        '$%i \ \ \mathrm{stars}$' % 
                        len(data),top_right=True,
                        size=_legendsize)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_all.'+options.ext)
    if options.all: return None
    #Plot zranges
    zranges= numpy.array([0.5,1.,1.5,2.,3.,4.])
    nzranges= len(zranges)-1
    zs= numpy.array(zs)
    data= numpy.array(data)
    sigzsd= numpy.empty(nzranges)
    esigzsd= numpy.empty(nzranges)
    sigzs1= numpy.empty(nzranges)
    sigzs2= numpy.empty(nzranges)
    sigzs3= numpy.empty(nzranges)
    for ii in range(nzranges):
        indx= (numpy.fabs(zs) >= zranges[ii])*(numpy.fabs(zs) < zranges[ii+1])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(data[indx],bins=26,normed=True,color='k',
                            histtype='step',
                            xrange=xrange,xlabel=xlabel)
        sigzsd[ii]= numpy.std(data[indx][(numpy.fabs(data[indx]) < 100.)])
        esigzsd[ii]= sigzsd[ii]/numpy.sqrt(float(len(data[indx][(numpy.fabs(data[indx]) < 100.)])))
        plotp= numpy.nansum(velps[indx,:],axis=0)/numpy.sum(indx)
        sigzs1[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
        bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
        if alts:
            plotp= numpy.nansum(velps2[indx,:],axis=0)/numpy.sum(indx)
            sigzs2[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
            plotp= numpy.nansum(velps3[indx,:],axis=0)/numpy.sum(indx)
            sigzs3[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
        bovy_plot.bovy_text(r'$ %i\ \mathrm{pc} \leq |Z| < %i\ \mathrm{pc}$' % (int(1000*zranges[ii]),int(1000*zranges[ii+1]))
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            (numpy.sum(indx)),top_right=True,
                            size=_legendsize)
        bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_z%.1f_z%.1f.' % (zranges[ii],zranges[ii+1])+options.ext)
    #Plot velocity dispersion as a function of |Z|
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzsd,
                        'ko',
                        xlabel=r'$|Z|\ (\mathrm{kpc})$',
                        ylabel=r'$\sigma_z\ (\mathrm{km\,s}^{-1})$',
                        xrange=[0.,4.],
                        yrange=[0.,60.])
    pyplot.errorbar(((numpy.roll(zranges,-1)+zranges)/2.)[:5],sigzsd,
                    yerr=esigzsd,
                    marker='o',color='k',linestyle='none')
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzs1,
                        'r+',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzs2,
                        'cx',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzs3,
                        'gd',overplot=True,ms=10.)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_szvsz.'+options.ext)
    return None
def plotMultiBins(options, args):
    raw = read_rawdata(options)
    # Bin the data
    binned = pixelAfeFeh(raw, dfeh=options.dfeh, dafe=options.dafe)
    if options.tighten:
        tightbinned = pixelAfeFeh(
            raw, dfeh=options.dfeh, dafe=options.dafe, fehmin=-1.6, fehmax=0.5, afemin=-0.05, afemax=0.55
        )
    else:
        tightbinned = binned
    # Load the different categories
    # aenhanced
    options.group = "aenhanced"
    gafes_aenhanced, gfehs_aenhanced, dummy = getMultiComparisonBins(options)
    options.group = "apoor"
    gafes_apoor, gfehs_apoor, dummy = getMultiComparisonBins(options)
    options.group = "apoorfpoor"
    gafes_apoorfpoor, gfehs_apoorfpoor, dummy = getMultiComparisonBins(options)
    options.group = "aintermediate"
    gafes_aintermediate, gfehs_aintermediate, dummy = getMultiComparisonBins(options)
    # Run through the pixels and gather
    plotthis = numpy.zeros((tightbinned.npixfeh(), tightbinned.npixafe()))
    plotthis[:, :] = numpy.nan
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data = binned(tightbinned.feh(ii), tightbinned.afe(jj))
            fehindx = binned.fehindx(tightbinned.feh(ii))  # Map onto regular binning
            afeindx = binned.afeindx(tightbinned.afe(jj))
            thisfeh = tightbinned.feh(ii)
            thisafe = tightbinned.afe(jj)
            if inMultiBin(thisfeh, thisafe, gfehs_aenhanced, gafes_aenhanced):
                plotthis[ii, jj] = 3
            elif inMultiBin(thisfeh, thisafe, gfehs_apoor, gafes_apoor):
                plotthis[ii, jj] = 2
            elif inMultiBin(thisfeh, thisafe, gfehs_apoorfpoor, gafes_apoorfpoor):
                plotthis[ii, jj] = 1
            elif inMultiBin(thisfeh, thisafe, gfehs_aintermediate, gafes_aintermediate):
                plotthis[ii, jj] = 0
    print "Bins accounted for: %i / 62 ..." % (numpy.sum(True - numpy.isnan(plotthis)))
    vmin, vmax = -1, 3.5
    if options.tighten:
        xrange = [-1.6, 0.5]
        yrange = [-0.05, 0.55]
    else:
        xrange = [-2.0, 0.6]
        yrange = [-0.1, 0.6]
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(
        plotthis.T,
        origin="lower",
        cmap="jet",
        interpolation="nearest",
        xlabel=r"$[\mathrm{Fe/H}]$",
        ylabel=r"$[\alpha/\mathrm{Fe}]$",
        xrange=xrange,
        yrange=yrange,
        vmin=vmin,
        vmax=vmax,
        contours=False,
        colorbar=False,
    )
    bovy_plot.bovy_end_print(args[0])
def plotOneDiskVsTwoDisks(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.sn)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.sn)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.sn)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.sn)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-2.,fehmax=0.3,afemin=0.,afemax=0.45)
    else:
        tightbinned= binned
    #Savefile1
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        onefits= pickle.load(savefile)
        savefile.close()
    if os.path.exists(args[1]):#Load savefile
        savefile= open(args[1],'rb')
        twofits= pickle.load(savefile)
        savefile.close()
    #Uncertainties are in savefile3 and 4
    if len(args) > 3 and os.path.exists(args[3]):
        savefile= open(args[3],'rb')
        twosamples= pickle.load(savefile)
        savefile.close()
        twoerrors= True
    else:
        twosamples= None
        twoerrors= False
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        onesamples= pickle.load(savefile)
        savefile.close()
        oneerrors= True
    else:
        onesamples= None            
        oneerrors= False
    #If --mass is set to a filename, load the masses from that file
    #and use those for the symbol size
    if not options.mass is None and os.path.exists(options.mass):
        savefile= open(options.mass,'rb')
        mass= pickle.load(savefile)
        savefile.close()
        ndata= mass
        masses= True
    else:
        masses= False
    #Run through the pixels and gather
    plotthis= []
    errors= []
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(onefits):
                continue
            thisonefit= onefits[afeindx+fehindx*binned.npixafe()]
            thistwofit= twofits[afeindx+fehindx*binned.npixafe()]
            if thisonefit is None:
                    continue
            if len(data) < options.minndata:
                    continue
            #print tightbinned.feh(ii), tightbinned.afe(jj), numpy.exp(thisonefit), numpy.exp(thistwofit)
            #Which is the dominant two-exp component?
            if thistwofit[4] > 0.5: twoIndx= 1
            else: twoIndx= 0
            if options.type == 'hz':
                if masses:
                    plotthis.append([numpy.exp(thisonefit[0])*1000.,
                                     numpy.exp(thistwofit[twoIndx])*1000.,
                                     mass[afeindx+fehindx*binned.npixafe()]])
                else:
                    plotthis.append([numpy.exp(thisonefit[0])*1000.,
                                     numpy.exp(thistwofit[twoIndx])*1000.,
                                     len(data)])
                #Discrepant point
                if plotthis[-1][1] < 250. and plotthis[-1][0] > 500.:
                    print "strange point: ", tightbinned.feh(ii),tightbinned.afe(jj)
            elif options.type == 'hr':
                plotthis.append([numpy.exp(thisonefit[1]),numpy.exp(thistwofit[twoIndx+2]),len(data)])
            theseerrors= []
            if oneerrors:
                theseonesamples= onesamples[afeindx+fehindx*binned.npixafe()]
                if options.type == 'hz':
                    xs= numpy.array([s[0] for s in theseonesamples])
                    theseerrors.append(500.*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                elif options.type == 'hr':
                    xs= numpy.array([s[1] for s in theseonesamples])
                    theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
            if twoerrors:
                thesetwosamples= twosamples[afeindx+fehindx*binned.npixafe()]
                if options.type == 'hz':
                    xs= numpy.array([s[twoIndx] for s in thesetwosamples])
                    theseerrors.append(500.*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                elif options.type == 'hr':
                    xs= numpy.array([s[2+twoIndx] for s in thesetwosamples])
                    theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
            errors.append(theseerrors)
    x, y, ndata= [], [], []
    if oneerrors: x_err= []
    if twoerrors: y_err= []
    for ii in range(len(plotthis)):
        x.append(plotthis[ii][0])
        y.append(plotthis[ii][1])
        ndata.append(plotthis[ii][2])
        if oneerrors: x_err.append(errors[ii][0])
        if twoerrors: y_err.append(errors[ii][1])
    x= numpy.array(x)
    y= numpy.array(y)
    if oneerrors: x_err= numpy.array(x_err)
    if twoerrors: y_err= numpy.array(y_err)
    ndata= numpy.array(ndata)
    #Process ndata
    if not masses:
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        ndata= 20
    else:    
        ndata= _squeeze(ndata,numpy.amin(ndata),numpy.amax(ndata))
        ndata= ndata*200.+10.
    #Now plot
    if options.type == 'hz':
        xrange= [150,1200]
        xlabel=r'$\mathrm{single-exponential\ scale\ height}$'
        ylabel=r'$\mathrm{two-exponentials\ scale\ height}$'
    elif options.type == 'hr':
        xrange= [1.2,5.]
        xlabel=r'$\mathrm{single-exponential\ scale\ length}$'
        ylabel=r'$\mathrm{two-exponentials\ scale\ length}$'
    yrange=xrange
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(x,y,color='k',
                        s=ndata,
                        ylabel=ylabel,
                        xlabel=xlabel,
                        xrange=xrange,yrange=yrange,
                        scatter=True,edgecolors='none',
                        colorbar=False,zorder=2)
    bovy_plot.bovy_plot([xrange[0],xrange[1]],[xrange[0],xrange[1]],color='0.5',ls='--',overplot=True)
    if oneerrors:
        #Overplot errors
        for ii in range(len(x)):
            #                if (options.type == 'hr' and x[ii] < 5.) or options.type == 'hz':
            pyplot.errorbar(x[ii],y[ii],xerr=x_err[ii],color='k',
                            elinewidth=1.,capsize=3,zorder=0)
    if twoerrors:
        #Overplot errors
        for ii in range(len(x)):
            #                if (options.type == 'hr' and x[ii] < 5.) or options.type == 'hz':
            pyplot.errorbar(x[ii],y[ii],yerr=y_err[ii],color='k',
                            elinewidth=1.,capsize=3,zorder=0)
    bovy_plot.bovy_end_print(options.plotfile)
    return None   
Exemple #25
0
def plotPixelFitVel(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
    if not options.bmin is None:
        #Cut on |b|
        raw= raw[(numpy.fabs(raw.b) > options.bmin)]
    #print len(raw)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    #ndata= 0
    #maxndata= 0
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(fits):
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            thisfit= fits[afeindx+fehindx*binned.npixafe()]
            if thisfit is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            #if len(data) > maxndata: maxndata= len(data)
            #ndata+= len(data)
            if options.model.lower() == 'hwr':
                if options.type == 'sz':
                    plotthis[ii,jj]= numpy.exp(thisfit[1])
                elif options.type == 'sz2':
                    plotthis[ii,jj]= numpy.exp(2.*thisfit[1])
                elif options.type == 'hs':
                    plotthis[ii,jj]= numpy.exp(thisfit[4])
                elif options.type == 'hsm':
                    plotthis[ii,jj]= numpy.exp(-thisfit[4])
                elif options.type == 'pbad':
                    plotthis[ii,jj]= thisfit[0]
                elif options.type == 'slopes':
                    plotthis[ii,jj]= thisfit[2]
                elif options.type == 'slope':
                    plotthis[ii,jj]= thisfit[2]
                elif options.type == 'chi2dof':
                    plotthis[ii,jj]= thisfit[6]
                elif options.type.lower() == 'afe' \
                        or options.type.lower() == 'feh' \
                        or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    plotthis.append([tightbinned.feh(ii),
                                     tightbinned.afe(jj),
                                     numpy.exp(thisfit[1]),
                                     numpy.exp(thisfit[3]),
                                     len(data)])
    #print ndata
    #print maxndata
    #Set up plot
    #print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    if options.type == 'sz':
        if options.vr:
            vmin, vmax= 40.,80.
            zlabel= r'$\sigma_R(z = \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$'
        else:
            vmin, vmax= 10.,60.
            zlabel= r'$\sigma_z(z_{1/2})\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'sz2':
        if options.vr:
            vmin, vmax= 40.**2.,80.**2.
            zlabel= r'$\sigma_R^2(z= \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$'
        else:
            vmin, vmax= 15.**2.,50.**2.
            zlabel= r'$\sigma_z^2(z= \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'hs':
        if options.vr:
            vmin, vmax= 3.,25.
            zlabel= r'$R_\sigma\ [\mathrm{kpc}]$'
        else:
            vmin, vmax= 3.,15.
            zlabel= r'$h_\sigma\ [\mathrm{kpc}]$'
    elif options.type == 'hsm':
        if options.vr:
            vmin, vmax= 0.,0.3
            zlabel= r'$R^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
        else:
            vmin, vmax= 0.,0.3
            zlabel= r'$R^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
    elif options.type == 'slope':
        vmin, vmax= -5.,5.
        zlabel= r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type == 'pbad':
        vmin, vmax= 0.,0.1
        zlabel= r'$P_{\mathrm{bad}}$'
    elif options.type == 'chi2dof':
        vmin, vmax= 0.5,1.5
        zlabel= r'$\chi^2/\mathrm{dof}$'
    elif options.type == 'afe':
        vmin, vmax= 0.05,.4
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.5,0.
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.6]
        yrange=[-0.1,0.6]
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        print "Update!! Never used until now (afe etc. type fitting is in plotsz2hz"
        return None
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        #Gather hR and hz
        hz, hr,afe, feh, ndata= [], [], [], [], []
        for ii in range(len(plotthis)):
            hz.append(plotthis[ii][2])
            hr.append(plotthis[ii][3])
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][4])
        hz= numpy.array(hz)
        hr= numpy.array(hr)
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata))
        #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        yrange= [150,1200]
        xrange= [1.2,5.]
        bovy_plot.bovy_plot(hr,hz,s=ndata,c=plotc,
                            cmap='jet',
                            ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$',
                            xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$',
                            clabel=zlabel,
                            xrange=xrange,yrange=yrange,
                            vmin=vmin,vmax=vmax,
                            scatter=True,edgecolors='none',
                            colorbar=True)
    elif options.type.lower() == 'slopes':
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(plotthis.flatten(),
                            range=[-5.,5.],
                            bins=11,
                            histtype='step',
                            color='k',
                            xlabel=r'$\sigma_z(z)\ \mathrm{slope\ [km\ s}^{-1}\ \mathrm{kpc}^{-1}]$')
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              contours=False,
                              colorbar=True,shrink=0.78)
    if options.observed:
        bovy_plot.bovy_text(r'$\mathrm{observed}$',
                            top_right=True,size=18.)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
Exemple #26
0
def generate_fakeDFData(options,args):
    #Check whether the savefile already exists
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        print "Savefile already exists, not re-sampling and overwriting ..."
        return None
    #Read the data
    print "Reading the data ..."
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin,nosolar=True,nocoords=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin,nosolar=True,nocoords=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin,nosolar=True,nocoords=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin,nosolar=True,
                              nocoords=True)
    if not options.bmin is None:
        #Cut on |b|
        raw= raw[(numpy.fabs(raw.b) > options.bmin)]
    if not options.fehmin is None:
        raw= raw[(raw.feh >= options.fehmin)]
    if not options.fehmax is None:
        raw= raw[(raw.feh < options.fehmax)]
    if not options.afemin is None:
        raw= raw[(raw.afe >= options.afemin)]
    if not options.afemax is None:
        raw= raw[(raw.afe < options.afemax)]
    if not options.plate is None and not options.loo:
        raw= raw[(raw.plate == options.plate)]
    elif not options.plate is None:
        raw= raw[(raw.plate != options.plate)]
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    if not options.singlefeh is None:
        if options.loo:
            pass
        else:
            #Set up single feh
            indx= binned.callIndx(options.singlefeh,options.singleafe)
            if numpy.sum(indx) == 0:
                raise IOError("Bin corresponding to singlefeh and singleafe is empty ...")
            data= copy.copy(binned.data[indx])
            print "Using %i data points ..." % (len(data))
            #Bin again
            binned= pixelAfeFeh(data,dfeh=options.dfeh,dafe=options.dafe)
            fehs, afes= [], []
            for ii in range(len(binned.fehedges)-1):
                for jj in range(len(binned.afeedges)-1):
                    data= binned(binned.feh(ii),binned.afe(jj))
                    if len(data) < options.minndata:
                        continue
                    fehs.append(binned.feh(ii))
                    afes.append(binned.afe(jj))
            nabundancebins= len(fehs)
            fehs= numpy.array(fehs)
            afes= numpy.array(afes)
    #Setup the selection function
    #Load selection function
    plates= numpy.array(list(set(list(raw.plate))),dtype='int') #Only load plates that we use
    print "Using %i plates, %i stars ..." %(len(plates),len(raw))
    sf= segueSelect(plates=plates,type_faint='tanhrcut',
                    sample=options.sample,type_bright='tanhrcut',
                    sn=options.snmin,select=options.select,
                    indiv_brightlims=options.indiv_brightlims)
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.50001, 20.199999 #so we don't go out of the range
    if options.sample.lower() == 'k':
        grmin, grmax= 0.55, 0.75
        rmin,rmax= 14.50001, 18.999999
    colorrange=[grmin,grmax]
    mapfehs= monoAbundanceMW.fehs()
    mapafes= monoAbundanceMW.afes()
    #Setup params
    if not options.init is None:
        #Load initial parameters from file
        savefile= open(options.init,'rb')
        tparams= pickle.load(savefile)
        savefile.close()
        #Setup the correct form
        params= initialize(options,fehs,afes)
        params[0:6]= get_dfparams(tparams,options.index,options,log=True)
        params[6:11]= tparams[-5:len(tparams)]
    else:
        params= initialize(options,fehs,afes)
    #Setup potential
    if (options.potential.lower() == 'flatlog' or options.potential.lower() == 'flatlogdisk') \
            and not options.flatten is None:
        #Set flattening
        potparams= list(get_potparams(params,options,len(fehs)))
        potparams[0]= options.flatten
        params= set_potparams(potparams,params,options,len(fehs))
    pot= setup_potential(params,options,len(fehs))
    aA= setup_aA(pot,options)
    if not options.multi is None:
        binned= fakeDFData_abundance_singles(binned,options,args,fehs,afes)
    else:
        for ii in range(len(fehs)):
            print "Working on population %i / %i ..." % (ii+1,len(fehs))
            #Setup qdf
            dfparams= get_dfparams(params,ii,options,log=False)
            vo= get_vo(params,options,len(fehs))
            ro= get_ro(params,options)
            if options.dfmodel.lower() == 'qdf':
                #Normalize
                hr= dfparams[0]/ro
                sr= dfparams[1]/vo
                sz= dfparams[2]/vo
                hsr= dfparams[3]/ro
                hsz= dfparams[4]/ro
            print hr, sr, sz, hsr, hsz
            qdf= quasiisothermaldf(hr,sr,sz,hsr,hsz,pot=pot,aA=aA,cutcounter=True)
            #Some more selection stuff
            data= binned(fehs[ii],afes[ii])
            #feh and color
            feh= fehs[ii]
            fehrange= [feh-options.dfeh/2.,feh+options.dfeh/2.]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            #Re-sample
            binned= fakeDFData(binned,qdf,ii,params,fehs,afes,options,
                               rmin,rmax,
                               platelb,
                               grmin,grmax,
                               fehrange,
                               colordist,
                               fehdist,feh,sf,
                               mapfehs,mapafes,
                               ro=None,vo=None)
    #Save to new file
    fitsio.write(args[0],binned.data)
    return None
def plotDensComparisonDF(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    if not options.singlefeh is None:
        if True: #Just to keep indentation the same
            #Set up single feh
            indx= binned.callIndx(options.singlefeh,options.singleafe)
            if numpy.sum(indx) == 0:
                raise IOError("Bin corresponding to singlefeh and singleafe is empty ...")
            allraw= copy.copy(raw)
            raw= copy.copy(binned.data[indx])
            #newerrstuff= []
            #for ii in range(len(binned.data)):
            #    if indx[ii]: newerrstuff.append(errstuff[ii])
            #errstuff= newerrstuff
            print "Using %i data points ..." % (len(data))
            #Bin again
            binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
            fehs, afes= [], []
            for ii in range(len(binned.fehedges)-1):
                for jj in range(len(binned.afeedges)-1):
                    data= binned(binned.feh(ii),binned.afe(jj))
                    if len(data) < options.minndata:
                        continue
                    fehs.append(binned.feh(ii))
                    afes.append(binned.afe(jj))
            nabundancebins= len(fehs)
            fehs= numpy.array(fehs)
            afes= numpy.array(afes)
    if options.singles:
        run_abundance_singles_plotdens(options,args,fehs,afes)
        return None
    if options.andistances:
        data= binned(fehs[0],afes[0])
        distfac= AnDistance.AnDistance(data.dered_g-data.dered_r,
                                       data.feh)
        if options.fixdm is None:
            options.fixdm= numpy.log10(distfac)*5.
        else:
            options.fixdm= options.fixdm+numpy.log10(distfac)*5.
        options.andistances= False
        #Start over
        plotDensComparisonDF(options,args)
        return None
    #Setup everything for the selection function
    print "Setting up stuff for the normalization integral ..."
    normintstuff= setup_normintstuff(options,raw,binned,fehs,afes,allraw)
    ##########POTENTIAL PARAMETERS####################
    potparams1= numpy.array([numpy.log(2.5/8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.2,0.])
    potparams2= numpy.array([numpy.log(3./8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.466666666,0.])
    potparams3= numpy.array([numpy.log(2.5/8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.8,0.])
    options.potential=  'dpdiskplhalofixbulgeflatwgasalt'
    #Set up density models and their parameters
    pop= 0 #assume first population
    #Load savefile
    if not options.init is None:
        #Load initial parameters from file
        savename= options.init
#        spl= savename.split('.')
#        newname= ''
#        for ll in range(len(spl)-1):
#            newname+= spl[ll]
#            if not ll == len(spl)-2: newname+= '.'
#        newname+= '_%i.' % pop
#        newname+= spl[-1]
        savefile= open(savename,'rb')
        try:
            if not _NOTDONEYET:
                params= pickle.load(savefile)
                mlogl= pickle.load(savefile)
            logl= pickle.load(savefile)
        except:
            if savetopickle:
                save_pickles(tmpfiles[jj],None)
                return None
            else:
                return None
        finally:
            savefile.close()
    else:
        raise IOError("base filename not specified ...")
    #First model is best-fit for this particular bin
    marglogl= numpy.zeros((8,16))
    for ll in range(8):
        for kk in range(16):
            marglogl[ll,kk]= logsumexp(logl[ll,0,0,kk,:,:,:,0])
    indx= numpy.unravel_index(numpy.nanargmax(marglogl),(8,16))
    print "Maximum for %i at %i,%i" % (pop,indx[0],indx[1])
    rds= numpy.linspace(2.0,3.4,options.nrds)/_REFR0
    rds= numpy.log(rds)
    fhs= numpy.linspace(0.,1.,options.nfhs)
    potparams1[0]= rds[indx[0]]
    potparams1[3]= fhs[indx[1]]
    #######DF PARAMETER RANGES###########
    hrs, srs, szs=  setup_dfgrid(fehs,afes,options)
    dfindx= numpy.unravel_index(numpy.nanargmax(logl[indx[0],0,0,indx[1],:,:,:,0]),
                                (8,8,16))
    print "Maximum for %i at %i,%i,%i" % (pop,dfindx[0],dfindx[1],dfindx[2])
    tparams= initialize(options,fehs,afes)
    startindx= 0
    if options.fitdvt: startindx+= 1
    tparams[startindx]= hrs[dfindx[0]]
    tparams[startindx+4]= srs[dfindx[1]]
    tparams[startindx+2]= szs[dfindx[2]]
    tparams[startindx+5]= 0. #outlier fraction
    tparams= set_potparams(potparams1,tparams,options,1)
    #Set up density models and their parameters
    model1= interpDens#woutlier
    print "Working on model 1 ..."
    paramsInterp= calc_model(tparams,options,0,_retsurfz=False,
                             normintstuff=normintstuff)
    params1= paramsInterp
    if False:
        indx0= numpy.argmin((potparams2[0]-rds)**2.)
        indx1= numpy.argmin((potparams2[3]-fhs)**2.)
        #indx0= indx[0]
        #indx1= indx[1]
        dfindx= numpy.unravel_index(numpy.argmax(logl[indx0,0,0,indx1,:,:,:,0]),
                                    (8,8,16))
        tparams[startindx]= hrs[dfindx[0]]
        tparams[startindx+4]= srs[dfindx[1]]
        tparams[startindx+2]= szs[dfindx[2]]
        #print "BOVY: YOU HAVE MESSED WITH MODEL 2"
        tparams= set_potparams(potparams2,tparams,toptions,1)
        model2= interpDens
        print "Working on model 2 ..."
        paramsInterp, surfz= calc_model(tparams,toptions,0,_retsurfz=True)
        params2= paramsInterp
        indx0= numpy.argmin((potparams3[0]-rds)**2.)
        indx1= numpy.argmin((potparams3[3]-fhs)**2.)
        dfindx= numpy.unravel_index(numpy.argmax(logl[indx0,0,0,indx1,:,:,:,0]),
                                    (8,8,16))
        tparams[startindx]= hrs[dfindx[0]]
        tparams[startindx+4]= srs[dfindx[1]]
        tparams[startindx+2]= szs[dfindx[2]]
        tparams= set_potparams(potparams3,tparams,toptions,1)
        model3= interpDens
        print "Working on model 3 ..."
        paramsInterp, surfz= calc_model(tparams,toptions,0,_retsurfz=True)
        params3= paramsInterp
    else:
        model2= None
        params2= None
        model3= None
        params3= None
    data= binned(fehs[pop],afes[pop])
    #Setup everything for selection function
    thisnormintstuff= normintstuff[pop]
    if _PRECALCVSAMPLES:
        sf, plates,platel,plateb,platebright,platefaint,grmin,grmax,rmin,rmax,fehmin,fehmax,feh,colordist,fehdist,gr,rhogr,rhofeh,mr,dmin,dmax,ds, surfscale, hr, hz, colorfehfac,normR, normZ,surfnrs, surfnzs, surfRgrid, surfzgrid, surfvrs, surfvts, surfvzs= unpack_normintstuff(thisnormintstuff,options)
    else:
        sf, plates,platel,plateb,platebright,platefaint,grmin,grmax,rmin,rmax,fehmin,fehmax,feh,colordist,fehdist,gr,rhogr,rhofeh,mr,dmin,dmax,ds, surfscale, hr, hz, colorfehfac, normR, normZ= unpack_normintstuff(thisnormintstuff,options)
    if True:
        #Cut out bright stars on faint plates and vice versa
        indx= []
        nfaintbright, nbrightfaint= 0, 0
        for ii in range(len(data.feh)):
            if sf.platebright[str(data[ii].plate)] and data[ii].dered_r >= 17.8:
                indx.append(False)
                nbrightfaint+= 1
            elif not sf.platebright[str(data[ii].plate)] and data[ii].dered_r < 17.8:
                indx.append(False)
                nfaintbright+= 1
            else:
                indx.append(True)
        print "nbrightfaint, nfaintbright", nbrightfaint, nfaintbright
        indx= numpy.array(indx,dtype='bool')
        data= data[indx]
    #Ranges
    if options.type == 'z':
        xrange= [-0.1,5.]
    elif options.type == 'R':
        xrange= [4.8,14.2]
    elif options.type == 'r':
        xrange= [14.2,20.1]
    #We do bright/faint for 4 directions and all, all bright, all faint
    ls= [180,180,45,45]
    bs= [0,90,-23,23]
    bins= 21
    #Set up comparison
    if options.type == 'r':
        compare_func= compareDataModel.comparerdistPlate
    elif options.type == 'z':
        compare_func= compareDataModel.comparezdistPlate
    elif options.type == 'R':
        compare_func= compareDataModel.compareRdistPlate
    #First do R ranges for z
    if options.type.lower() == 'z' and _RRANGES:
        bins=21
        Rmins= [None,7.,9.]
        Rmaxs= [7.,9.,None]
        nameRmins= [4,7,9]
        nameRmaxs= [7,9,13]
        for ii in range(len(Rmins)):
            plate= 'all'
            if Rmins[ii] is None:
                thisleft_legend= r'$R \leq 7\,\mathrm{kpc\ plates}$'
            elif Rmins[ii] == 7.:
                thisleft_legend= r'$7\,\mathrm{kpc} < R \leq 9\,\mathrm{kpc\ plates}$'
            elif Rmaxs[ii] is None:
                thisleft_legend= r'$R \geq 9\,\mathrm{kpc\ plates}$'
            thisright_legend= None
            bovy_plot.bovy_print()
            compare_func(model1,params1,sf,colordist,fehdist,
                         data,plate,color='k',
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         bins=bins,ls='-',left_legend=thisleft_legend,
                         right_legend=thisright_legend,
                         Rmin=Rmins[ii],Rmax=Rmaxs[ii])
            if not params2 is None:
                compare_func(model2,params2,sf,colordist,fehdist,
                             data,plate,color='k',bins=bins,
                             rmin=14.5,rmax=rmax,
                             grmin=grmin,grmax=grmax,
                             fehmin=fehmin,fehmax=fehmax,feh=feh,
                             xrange=xrange,
                             overplot=True,ls='--',
                             Rmin=Rmins[ii],Rmax=Rmaxs[ii])
            if not params3 is None:
                compare_func(model3,params3,sf,colordist,fehdist,
                             data,plate,color='k',bins=bins,
                             rmin=14.5,rmax=rmax,
                             grmin=grmin,grmax=grmax,
                             fehmin=fehmin,fehmax=fehmax,feh=feh,
                             xrange=xrange,
                             overplot=True,ls=':',
                             Rmin=Rmins[ii],Rmax=Rmaxs[ii])
            if options.type == 'r':
                bovy_plot.bovy_end_print(args[0]+'model_data_g_%iR%i' % (nameRmins[ii],nameRmaxs[ii])+'.'+options.ext)
            else:
                bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_%iR%i' % (nameRmins[ii],nameRmaxs[ii])+'.'+options.ext)
    #all, faint, bright
    bins= [31,31,31]
    plates= ['all','bright','faint']
    for ii in range(len(plates)):
        plate= plates[ii]
        if plate == 'all':
#            thisleft_legend= left_legend
#            thisright_legend= right_legend
            thisleft_legend= None
            thisright_legend= None
        else:
            thisleft_legend= None
            thisright_legend= None
        bovy_plot.bovy_print()
        compare_func(model1,params1,sf,colordist,fehdist,
                     data,plate,color='k',
                     rmin=14.5,rmax=rmax,
                     grmin=grmin,grmax=grmax,
                     fehmin=fehmin,fehmax=fehmax,feh=feh,
                     xrange=xrange,
                     bins=bins[ii],ls='-',left_legend=thisleft_legend,
                     right_legend=thisright_legend)
        if not params2 is None:
            compare_func(model2,params2,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins[ii],
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins[ii],
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+plate+'.'+options.ext)
        else:
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_'+plate+'.'+options.ext)
        if options.all: return None
    bins= 16
    for ii in range(len(ls)):
        nodata= False
        #Bright
        plate= compareDataModel.similarPlatesDirection(ls[ii],bs[ii],20.,
                                                       sf,data,
                                                       faint=False)
        bovy_plot.bovy_print()
        try:
            compare_func(model1,params1,sf,colordist,fehdist,
                         data,plate,color='k',
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         bins=bins,ls='-')
        except IndexError:
            #no data
            nodata= True
        if not params2 is None and not nodata:
            compare_func(model2,params2,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None and not nodata:
            compare_func(model3,params3,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if not nodata:
            if options.type == 'r':
                bovy_plot.bovy_end_print(args[0]+'model_data_g_'+'l%i_b%i_bright.' % (ls[ii],bs[ii])+options.ext)
            else:
                bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_l%i_b%i_bright.' % (ls[ii],bs[ii])+options.ext)
        #Faint
        plate= compareDataModel.similarPlatesDirection(ls[ii],bs[ii],20.,
                                                       sf,data,
                                                       bright=False)
        bovy_plot.bovy_print()
        try:
            compare_func(model1,params1,sf,colordist,fehdist,
                         data,plate,color='k',
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         bins=bins,ls='-')
        except IndexError:
            #No data
            continue
        if not params2 is None:
            compare_func(model2,params2,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+'l%i_b%i_faint.' % (ls[ii],bs[ii])+options.ext)
        else:
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_l%i_b%i_faint.' % (ls[ii],bs[ii])+options.ext)
    return None
Exemple #28
0
def plot_DFRotcurves(options,args):
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    counter= 0
    abindx= numpy.zeros((len(binned.fehedges)-1,len(binned.afeedges)-1),
                        dtype='int')
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
            abindx[ii,jj]= counter
            counter+= 1
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    #Load each solutions
    sols= []
    savename= args[0]
    initname= options.init
    for ii in range(nabundancebins):
        spl= savename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        savefilename= newname
        #Read savefile
        try:
            savefile= open(savefilename,'rb')
        except IOError:
            print "WARNING: MISSING ABUNDANCE BIN"
            sols.append(None)
        else:
            sols.append(pickle.load(savefile))
            savefile.close()
        #Load samples as well
        if options.mcsample:
            #Do the same for init
            spl= initname.split('.')
            newname= ''
            for jj in range(len(spl)-1):
                newname+= spl[jj]
                if not jj == len(spl)-2: newname+= '.'
            newname+= '_%i.' % ii
            newname+= spl[-1]
            options.init= newname
    mapfehs= monoAbundanceMW.fehs()
    mapafes= monoAbundanceMW.afes()
    #Now plot
    #Run through the pixels and plot rotation curves
    if options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.6,0.4
        zlabel=r'$[\mathrm{Fe/H}]$'
    overplot= False
    if options.subtype is None or options.subtype.lower() != 'median':
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
    medianvc= []
    medianvc_disk= []
    medianvc_halo= []
    medianvc_bulge= []
    medianrs= numpy.linspace(0.001,2.,1001)
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            #Find abundance indx
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            solindx= abindx[fehindx,afeindx]
            monoabindx= numpy.argmin((tightbinned.feh(ii)-mapfehs)**2./0.01 \
                                         +(tightbinned.afe(jj)-mapafes)**2./0.0025)
            if sols[solindx] is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            s= get_potparams(sols[solindx],options,1)
            #Setup potential
            pot= setup_potential(sols[solindx],options,1,returnrawpot=True)
            vo= get_vo(sols[solindx],options,1)
            ro= get_ro(sols[solindx],options)
            if options.type.lower() == 'afe':
                plotc= tightbinned.afe(jj)
            elif options.type.lower() == 'feh':
                plotc= tightbinned.feh(jj)
            colormap = cm.jet
            if options.subtype is None or options.subtype.lower() == 'full':
                potential.plotRotcurve(pot,Rrange=[0.001,2.],
                                       overplot=overplot,ls='-',
                                       color=colormap(_squeeze(plotc,vmin,vmax)),
                                       yrange=[0.,1.29],
                                       ylabel= r"$V_c(R)/V_c(R_0)$",
                                       zorder=int(numpy.random.uniform()*100))
            elif options.subtype.lower() == 'disk':
                if 'mwpotential' in options.potential.lower():
                    diskpot= pot[0]
                elif 'wgas' in options.potential.lower():
                    diskpot= [pot[0],pot[-1]]
                elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                    diskpot= pot[0]
                elif 'dpdisk' in options.potential.lower():
                    diskpot= pot[0]
                potential.plotRotcurve(diskpot,Rrange=[0.001,2.],
                                       yrange=[0.,1.29],
                                       overplot=overplot,ls='-',
                                       color=colormap(_squeeze(plotc,vmin,vmax)),
                                       ylabel= r"$V_c(R)/V_c(R_0)$",
                                       zorder=int(numpy.random.uniform()*100))
            elif options.subtype.lower() == 'halo':
                halopot= pot[1]
                potential.plotRotcurve(halopot,Rrange=[0.001,2.],
                                       overplot=overplot,ls='-',
                                       yrange=[0.,1.29],
                                       ylabel= r"$V_c(R)/V_c(R_0)$",
                                       color=colormap(_squeeze(plotc,vmin,vmax)),
                                       zorder=int(numpy.random.uniform()*100))
            elif options.subtype.lower() == 'bulge':
                bulgepot= pot[2]
                potential.plotRotcurve(bulgepot,Rrange=[0.001,2.],
                                       overplot=overplot,ls='-',
                                       ylabel= r"$V_c(R)/V_c(R_0)$",
                                       yrange=[0.,1.29],
                                       color=colormap(_squeeze(plotc,vmin,vmax)),
                                       zorder=int(numpy.random.uniform()*100))
            elif options.subtype.lower() == 'median':
                if 'mwpotential' in options.potential.lower():
                    diskpot= pot[0]
                elif 'wgas' in options.potential.lower():
                    diskpot= [pot[0],pot[-1]]
                elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                    diskpot= pot[0]
                elif 'dpdisk' in options.potential.lower():
                    diskpot= pot[0]
                halopot= pot[1]
                bulgepot= pot[2]
                vo= get_vo(sols[solindx],options,1)
                medianvc.append(vo*potential.calcRotcurve(pot,medianrs))
                medianvc_disk.append(vo*potential.calcRotcurve(diskpot,medianrs))
                medianvc_halo.append(vo*potential.calcRotcurve(halopot,medianrs))
                medianvc_bulge.append(vo*potential.calcRotcurve(bulgepot,medianrs))
            overplot=True
    if options.subtype is None or options.subtype.lower() != 'median':
    #Add colorbar
        m = cm.ScalarMappable(cmap=cm.jet)
        m.set_array(plotc)
        m.set_clim(vmin=vmin,vmax=vmax)
        cbar= pyplot.colorbar(m,fraction=0.15)
        cbar.set_clim((vmin,vmax))
        cbar.set_label(zlabel)
        if options.subtype is None:
            pass
        elif options.subtype.lower() == 'disk':
            bovy_plot.bovy_text(r'$\mathrm{Disk}$',bottom_right=True,size=_legendsize)
        elif options.subtype.lower() == 'halo':
            bovy_plot.bovy_text(r'$\mathrm{Halo}$',bottom_right=True,size=_legendsize)
        elif options.subtype.lower() == 'bulge':
            bovy_plot.bovy_text(r'$\mathrm{Bulge}$',bottom_right=True,size=_legendsize)
    else:
        #Calc medians
        nbins= len(medianvc)
        vc= numpy.empty((len(medianrs),nbins))
        vc_disk= numpy.empty((len(medianrs),nbins))
        vc_bulge= numpy.empty((len(medianrs),nbins))
        vc_halo= numpy.empty((len(medianrs),nbins))
        for ii in range(nbins):
            vc[:,ii]= medianvc[ii]
            vc_disk[:,ii]= medianvc_disk[ii]
            vc_halo[:,ii]= medianvc_halo[ii]
            vc_bulge[:,ii]= medianvc_bulge[ii]
        vc= numpy.median(vc,axis=1)*_REFV0
        #vcro= vc[numpy.argmin(numpy.fabs(medianrs-1.))]
        #vc/= vcro
        vc_disk= numpy.median(vc_disk,axis=1)*_REFV0
        vc_halo= numpy.median(vc_halo,axis=1)*_REFV0
        vc_bulge= numpy.median(vc_bulge,axis=1)*_REFV0
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        bovy_plot.bovy_plot(medianrs,vc,'k-',
                            xlabel=r"$R/R_0$",
                            ylabel= r"$V_c(R)\ [\mathrm{km\,s}^{-1}]$",
                            yrange=[0.,1.29*_REFV0],
                            xrange=[0.,2.])
        linedisk= bovy_plot.bovy_plot(medianrs,vc_disk,'k--',
                                      overplot=True)
        linedisk[0].set_dashes([5,5])
        bovy_plot.bovy_plot(medianrs,vc_halo,'k:',
                            overplot=True)
        linebulge= bovy_plot.bovy_plot(medianrs,vc_bulge,'k--',
                                       overplot=True)
        linebulge[0].set_dashes([10,4])
        bovy_plot.bovy_text(1.95,120.,r'$\mathrm{Disk}$',size=_legendsize,
                            horizontalalignment='right')
        bovy_plot.bovy_text(1.95,193.,r'$\mathrm{Halo}$',size=_legendsize,
                            horizontalalignment='right')
        bovy_plot.bovy_text(1.95,28.,r'$\mathrm{Bulge}$',size=_legendsize,
                            horizontalalignment='right')
    bovy_plot.bovy_end_print(options.outfilename)
Exemple #29
0
def calcMass(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        elif options.select.lower() == 'fakebimodal':
            raw= read_gdwarfs(_FAKEBIMODALGDWARFFILE,
                              logg=True,ebv=True,sn=True)
            options.select= 'all'
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        mass= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        mass= []
        ii, jj= 0, 0
    #parameters
    if os.path.exists(args[1]):#Load initial
        savefile= open(args[1],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    else:
        print "Error: must provide parameters of best fits"
        print "Returning ..."
        return None
    #Sample?
    if options.mcsample:
        if ii < len(binned.fehedges)-1 and jj < len(binned.afeedges)-1:
            print "First do all of the best-fit mass estimates ..."
            print "Returning ..."
            return None
        if os.path.exists(args[2]): #Load savefile
            savefile= open(args[2],'rb')
            masssamples= pickle.load(savefile)
            ii= pickle.load(savefile)
            jj= pickle.load(savefile)
            savefile.close()
        else:
            masssamples= []
            ii, jj= 0, 0
        if os.path.exists(args[3]): #Load savefile
            savefile= open(args[3],'rb')
            denssamples= pickle.load(savefile)
            savefile.close()
        else:
            print "If mcsample you need to provide the file with the density samples ..."
            print "Returning ..."
            return None
    #Set up model etc.
    if options.model.lower() == 'hwr':
        densfunc= _HWRDensity
    elif options.model.lower() == 'twodblexp':
        densfunc= _TwoDblExpDensity
    like_func= _HWRLikeMinus
    pdf_func= _HWRLike
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
    #Load selection function
    plates= numpy.array(list(set(list(raw.plate))),dtype='int') #Only load plates that we use
    print "Using %i plates, %i stars ..." %(len(plates),len(raw))
    sf= segueSelect(plates=plates,type_faint='tanhrcut',
                    sample=options.sample,type_bright='tanhrcut',
                    sn=True,select=options.select)
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    indx= [not 'faint' in name for name in sf.platestr.programname]
    platebright= numpy.array(indx,dtype='bool')
    indx= ['faint' in name for name in sf.platestr.programname]
    platefaint= numpy.array(indx,dtype='bool')
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.5, 20.2
    #Run through the bins
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                if options.mcsample: masssamples.append(None)
                else: mass.append(None)
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            print binned.feh(ii), binned.afe(jj), len(data)
            fehindx= binned.fehindx(binned.feh(ii))
            afeindx= binned.afeindx(binned.afe(jj))
            #set up feh and color
            feh= binned.feh(ii)
            fehrange= [binned.fehedges[ii],binned.fehedges[ii+1]]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            
            #Age marginalization
            afe= binned.afe(jj)
            if options.simpleage:
                agemin, agemax= 0.5, 10.
            else:
                if afe > 0.25: agemin, agemax= 7.,10.
                else: agemin,agemax= 1.,8.
            if options.mcsample:
                #Loop over samples
                thissamples= denssamples[afeindx+fehindx*binned.npixafe()]
                if options.nsamples < len(thissamples):
                    print "Taking random ..."
                    #Random permutation
                    thissamples= numpy.random.permutation(thissamples)[0:options.nsamples]
                thismasssamples= []
                print "WARNING: DISK MASS IN CALCMASS ONLY FOR G COLORS"
                for kk in range(len(thissamples)):
                    thisparams= thissamples[kk]
                    thismasssamples.append(predictDiskMass(densfunc,
                                                           thisparams,sf,
                                                           colordist,fehdist,
                                                           fehrange[0],
                                                           fehrange[1],feh,
                                                           data,0.45,
                                                           0.58,
                                                           agemin,agemax,
                                                           normalize=options.normalize,
                                                           imfmodel=options.imfmodel))
                #Print some stuff
                print numpy.mean(numpy.array(thismasssamples)), numpy.std(numpy.array(thismasssamples))
                masssamples.append(thismasssamples)
            else:
                thisparams= fits[afeindx+fehindx*binned.npixafe()]
                print "WARNING: DISK MASS IN CALCMASS ONLY FOR G COLORS"
                mass.append(predictDiskMass(densfunc,
                                            thisparams,sf,
                                            colordist,fehdist,
                                            fehrange[0],
                                            fehrange[1],feh,
                                            data,0.45,
                                            0.58,
                                            agemin,agemax,
                                            normalize=options.normalize,
                                            imfmodel=options.imfmodel))
                print mass[-1]
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
            if options.mcsample: save_pickles(args[2],masssamples,ii,jj)
            else: save_pickles(args[0],mass,ii,jj)
            if jj == 0: #this means we've reset the counter 
                break
    if options.mcsample: save_pickles(args[2],masssamples,ii,jj)
    else: save_pickles(args[0],mass,ii,jj)
    return None
Exemple #30
0
def plotVelPDFs(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile1
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
    if os.path.exists(args[1]):#Load savefile
        savefile= open(args[1],'rb')
        densfits= pickle.load(savefile)
        savefile.close()
    #Uncertainties are in savefile3 and 4
    if len(args) > 3 and os.path.exists(args[3]):
        savefile= open(args[3],'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
        denserrors= True
    else:
        denssamples= None
        denserrors= False
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
        velerrors= True
    else:
        velsamples= None            
        velerrors= False
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'zfunc' \
            or options.type.lower() == 'afefeh':
        plotthis= []
        errors= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    if options.kde: allsamples= []
    sausageFehAfe= [options.feh,options.afe]#-0.15,0.075]#[[-0.85,0.425],[-0.45,0.275],[-0.15,0.075]]
    if options.subtype.lower() == 'sausage':
        sausageSamples= []
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if not (numpy.fabs(tightbinned.feh(ii)-sausageFehAfe[0])< 0.01 and numpy.fabs(tightbinned.afe(jj) - sausageFehAfe[1]) < 0.01):
                continue
            thisdensfit= densfits[afeindx+fehindx*binned.npixafe()]
            thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            if options.velmodel.lower() == 'hwr':
                thisplot=[tightbinned.feh(ii),
                              tightbinned.afe(jj),
                              numpy.exp(thisvelfit[1]),
                              numpy.exp(thisvelfit[4]),
                              len(data),
                              thisvelfit[2],
                              thisvelfit[3]]
                #Als find min and max z for this data bin, and median
                zsorted= sorted(numpy.fabs(data.zc+_ZSUN))
                zmin= zsorted[int(numpy.ceil(0.16*len(zsorted)))]
                zmax= zsorted[int(numpy.floor(0.84*len(zsorted)))]
                thisplot.extend([zmin,zmax,numpy.mean(numpy.fabs(data.zc+_ZSUN))])
                #Errors
                if velerrors:
                    thesesamples= velsamples[afeindx+fehindx*binned.npixafe()]
                break
    #Now plot
    if options.type.lower() == 'slopequad':
        plotx= numpy.array([thesesamples[ii][3] for ii in range(len(thesesamples))])
        ploty= numpy.array([thesesamples[ii][2] for ii in range(len(thesesamples))])
        xrange= [-10.,10.]
        yrange= [-20.,20.]
        xlabel=r'$\frac{\mathrm{d}^2 \sigma_z}{\mathrm{d} z^2}(z_{1/2})\ [\mathrm{km}\ \mathrm{s}^{-1}\ \mathrm{kpc}^{-2}]$'
        ylabel=r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type.lower() == 'slopehsm':
        ploty= numpy.array([thesesamples[ii][2] for ii in range(len(thesesamples))])
        plotx= numpy.exp(-numpy.array([thesesamples[ii][4] for ii in range(len(thesesamples))]))
        xrange= [0.,0.3]
        yrange= [-20.,20.]
        xlabel=r'$h^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
        ylabel=r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type.lower() == 'slopesz':
        ploty= numpy.array([thesesamples[ii][2] for ii in range(len(thesesamples))])
        plotx= numpy.exp(numpy.array([thesesamples[ii][1] for ii in range(len(thesesamples))]))
        xrange= [0.,60.]
        yrange= [-20.,20.]
        xlabel=r'$\sigma_z(z_{1/2}) [\mathrm{km\ s}^{-1}$'
        ylabel=r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type.lower() == 'szhsm':
        plotx= numpy.exp(-numpy.array([thesesamples[ii][4] for ii in range(len(thesesamples))]))
        ploty= numpy.exp(numpy.array([thesesamples[ii][1] for ii in range(len(thesesamples))]))
        yrange= [0.,60.]
        xrange= [0.,0.3]
        xlabel=r'$h^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
        ylabel=r'$\sigma_z(z_{1/2}) [\mathrm{km\ s}^{-1}$'
    bovy_plot.bovy_print()
    axScatter, axHistx, axHisty= bovy_plot.scatterplot(plotx,ploty,'k,',
                                                       onedhists=True,
                                                       bins=31,
                                                       xlabel=xlabel,ylabel=ylabel,
                                                       xrange=xrange,
                                                       onedhistynormed=True,
                                                       yrange=yrange,
                                                       retAxes=True)
    if options.type.lower() == 'slopequad':
        #Also add `quadratic term = 0' to vertical histogram
        ploty= ploty[(numpy.fabs(plotx) < 0.5)]
        histy, edges, patches= axHisty.hist(ploty,
                                            bins=51,
                                            orientation='horizontal',
                                            weights=numpy.ones(len(ploty))/float(len(ploty))/2.,
                                            histtype='step',
                                            range=sorted(yrange),
                                            color='0.6',
                                            lw=2.)
    #Label
    bovy_plot.bovy_text(r'$[\mathrm{Fe/H}]\ =\ %.2f$' % options.feh
                        +'\n'
                        +r'$[\alpha/\mathrm{Fe}]\ =\ %.3f$' % options.afe,
                        top_right=True,
                        size=18)                     
    bovy_plot.bovy_end_print(options.plotfile)