Example #1
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
Example #2
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 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   
Example #4
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)
Example #5
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