Exemplo n.º 1
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)
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
0
def fakeDFData(binned,qdf,ii,params,fehs,afes,options,
               rmin,rmax,
               platelb,
               grmin,grmax,
               fehrange,
               colordist,
               fehdist,feh,sf,
               mapfehs,mapafes,
               ro=None,vo=None,
               ndata=None,#If set, supersedes binned, only to be used w/ returnlist=True
               returnlist=False): #last one useful for pixelFitDF normintstuff
    if ro is None:
        ro= get_ro(params,options)
    if vo is None:
        vo= get_vo(params,options,len(fehs))
    thishr= qdf.estimate_hr(1.,z=0.125)*_REFR0*ro #qdf._hr*_REFR0*ro
    thishz= qdf.estimate_hz(1.,z=0.125)*_REFR0*ro
    if thishr < 0.: thishr= 10. #Probably close to flat
    if thishz  < 0.1: thishz= 0.2
    thissr= qdf._sr*_REFV0*vo
    thissz= qdf._sz*_REFV0*vo
    thishsr= qdf._hsr*_REFR0*ro
    thishsz= qdf._hsz*_REFR0*ro
    if True:
        if options.aAmethod.lower() == 'staeckel':
            #Make everything 10% larger
            thishr*= 1.2
            thishz*= 1.2
            thishsr*= 1.2
            thishsz*= 1.2
            thissr*= 2.
            thissz*= 2.
        else:
            #Make everything 20% larger
            thishr*= 1.2
            thishz*= 1.2
            thishsr*= 1.2
            thishsz*= 1.2
            thissr*= 2.
            thissz*= 2.
    #Find nearest mono-abundance bin that has a measurement
    abindx= numpy.argmin((fehs[ii]-mapfehs)**2./0.01 \
                             +(afes[ii]-mapafes)**2./0.0025)
    #Calculate the r-distribution for each plate
    nrs= 1001
    ngr, nfeh= 11, 11 #BOVY: INCREASE?
    tgrs= numpy.linspace(grmin,grmax,ngr)
    tfehs= numpy.linspace(fehrange[0]+0.00001,fehrange[1]-0.00001,nfeh)
    #Calcuate FeH and gr distriutions
    fehdists= numpy.zeros(nfeh)
    for jj in range(nfeh): fehdists[jj]= fehdist(tfehs[jj])
    fehdists= numpy.cumsum(fehdists)
    fehdists/= fehdists[-1]
    colordists= numpy.zeros(ngr)
    for jj in range(ngr): colordists[jj]= colordist(tgrs[jj])
    colordists= numpy.cumsum(colordists)
    colordists/= colordists[-1]
    rs= numpy.linspace(rmin,rmax,nrs)
    rdists= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
    #outlier model that we want to sample (not the one to aid in the sampling)
    srhalo= _SRHALO/vo/_REFV0
    sphihalo= _SPHIHALO/vo/_REFV0
    szhalo= _SZHALO/vo/_REFV0
    logoutfrac= numpy.log(get_outfrac(params,ii,options))
    loghalodens= numpy.log(ro*outDens(1.,0.,None))
    #Calculate surface(R=1.) for relative outlier normalization
    logoutfrac+= numpy.log(qdf.surfacemass_z(1.,ngl=options.ngl))
    if options.mcout:
        fidoutfrac= get_outfrac(params,ii,options)
        rdistsout= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
    lagoutfrac= 0.15 #.0000000000000000000000001 #seems good
    #Setup density model
    use_real_dens= True
    if use_real_dens:
        #nrs, nzs= 101, 101
        nrs, nzs= 64, 64
        thisRmin, thisRmax= 4./_REFR0, 15./_REFR0
        thiszmin, thiszmax= 0., .8
        Rgrid= numpy.linspace(thisRmin,thisRmax,nrs)
        zgrid= numpy.linspace(thiszmin,thiszmax,nzs)
        surfgrid= numpy.empty((nrs,nzs))
        for ll in range(nrs):
            for jj in range(nzs):
                sys.stdout.write('\r'+"Working on grid-point %i/%i" % (jj+ll*nzs+1,nzs*nrs))
                sys.stdout.flush()
                surfgrid[ll,jj]= qdf.density(Rgrid[ll],zgrid[jj],
                                             nmc=options.nmcv,
                                             ngl=options.ngl)
        sys.stdout.write('\r'+_ERASESTR+'\r')
        sys.stdout.flush()
        if _SURFSUBTRACTEXPON:
            Rs= numpy.tile(Rgrid,(nzs,1)).T
            Zs= numpy.tile(zgrid,(nrs,1))
            ehr= qdf.estimate_hr(1.,z=0.125)
#            ehz= qdf.estimate_hz(1.,zmin=0.5,zmax=0.7)#Get large z behavior right
            ehz= qdf.estimate_hz(1.,z=0.125)
            surfInterp= interpolate.RectBivariateSpline(Rgrid,zgrid,
                                                        numpy.log(surfgrid)
                                                        +Rs/ehr+numpy.fabs(Zs)/ehz,
                                                        kx=3,ky=3,
                                                        s=0.)
#                                                        s=10.*float(nzs*nrs))
        else:
            surfInterp= interpolate.RectBivariateSpline(Rgrid,zgrid,
                                                        numpy.log(surfgrid),
                                                        kx=3,ky=3,
                                                        s=0.)
#                                                        s=10.*float(nzs*nrs))
        if _SURFSUBTRACTEXPON:
            compare_func= lambda x,y,du: numpy.exp(surfInterp.ev(x/ro/_REFR0,numpy.fabs(y)/ro/_REFR0)-x/ro/_REFR0/ehr-numpy.fabs(y)/ehz/ro/_REFR0)
        else:
            compare_func= lambda x,y,du: numpy.exp(surfInterp.ev(x/ro/_REFR0,numpy.fabs(y)/ro/_REFR0))
    else:
        compare_func= lambda x,y,z: fidDens(x,y,thishr,thishz,z)
    for jj in range(len(sf.plates)):
        p= sf.plates[jj]
        sys.stdout.write('\r'+"Working on plate %i (%i/%i)" % (p,jj+1,len(sf.plates)))
        sys.stdout.flush()
        rdists[jj,:,:,:]= _predict_rdist_plate(rs,
                                               compare_func,
                                               None,rmin,rmax,
                                               platelb[jj,0],platelb[jj,1],
                                               grmin,grmax,
                                               fehrange[0],fehrange[1],feh,
                                               colordist,
                                               fehdist,sf,sf.plates[jj],
                                               dontmarginalizecolorfeh=True,
                                               ngr=ngr,nfeh=nfeh)
        if options.mcout:
            rdistsout[jj,:,:,:]= _predict_rdist_plate(rs,
                                                      lambda x,y,z: outDens(x,y,z),
                                                      None,rmin,rmax,
                                                      platelb[jj,0],platelb[jj,1],
                                                      grmin,grmax,
                                                      fehrange[0],fehrange[1],feh,
                                                      colordist,
                                                      fehdist,sf,sf.plates[jj],
                                                      dontmarginalizecolorfeh=True,
                                                      ngr=ngr,nfeh=nfeh)
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    numbers= numpy.sum(rdists,axis=3)
    numbers= numpy.sum(numbers,axis=2)
    numbers= numpy.sum(numbers,axis=1)
    numbers= numpy.cumsum(numbers)
    if options.mcout:
        totfid= numbers[-1]
    numbers/= numbers[-1]
    rdists= numpy.cumsum(rdists,axis=1)
    for ll in range(len(sf.plates)):
        for jj in range(ngr):
            for kk in range(nfeh):
                rdists[ll,:,jj,kk]/= rdists[ll,-1,jj,kk]
    if options.mcout:
        numbersout= numpy.sum(rdistsout,axis=3)
        numbersout= numpy.sum(numbersout,axis=2)
        numbersout= numpy.sum(numbersout,axis=1)
        numbersout= numpy.cumsum(numbersout)
        totout= fidoutfrac*numbersout[-1]
        totnumbers= totfid+totout
        totfid/= totnumbers
        totout/= totnumbers
        if _DEBUG:
            print totfid, totout
        numbersout/= numbersout[-1]
        rdistsout= numpy.cumsum(rdistsout,axis=1)
        for ll in range(len(sf.plates)):
            for jj in range(ngr):
                for kk in range(nfeh):
                    rdistsout[ll,:,jj,kk]/= rdistsout[ll,-1,jj,kk]
    #Now sample
    thisout= []
    newrs= []
    newls= []
    newbs= []
    newplate= []
    newgr= []
    newfeh= []
    newds= []
    newzs= []
    newvas= []
    newRs= []
    newphi= []
    newvr= []
    newvt= []
    newvz= []
    newlogratio= []
    newfideval= []
    newqdfeval= []
    newpropeval= []
    if ndata is None:
        thisdata= binned(fehs[ii],afes[ii])
        thisdataIndx= binned.callIndx(fehs[ii],afes[ii])
        ndata= len(thisdata)
    #First sample from spatial density
    for ll in range(ndata):
        #First sample a plate
        ran= numpy.random.uniform()
        kk= 0
        while numbers[kk] < ran: kk+= 1
        #Also sample a FeH and a color
        ran= numpy.random.uniform()
        ff= 0
        while fehdists[ff] < ran: ff+= 1
        ran= numpy.random.uniform()
        cc= 0
        while colordists[cc] < ran: cc+= 1
        #plate==kk, feh=ff,color=cc; now sample from the rdist of this plate
        ran= numpy.random.uniform()
        jj= 0
        if options.mcout and numpy.random.uniform() < totout: #outlier
            while rdistsout[kk,jj,cc,ff] < ran: jj+= 1
            thisoutlier= True
        else:
            while rdists[kk,jj,cc,ff] < ran: jj+= 1
            thisoutlier= False
        #r=jj
        newrs.append(rs[jj])
        newls.append(platelb[kk,0])
        newbs.append(platelb[kk,1])
        newplate.append(sf.plates[kk])
        newgr.append(tgrs[cc])
        newfeh.append(tfehs[ff])
        dist= _ivezic_dist(tgrs[cc],rs[jj],tfehs[ff])
        newds.append(dist)
        #calculate R,z
        XYZ= bovy_coords.lbd_to_XYZ(platelb[kk,0],platelb[kk,1],
                                    dist,degree=True)
        R= ((_REFR0-XYZ[0])**2.+XYZ[1]**2.)**(0.5)
        newRs.append(R)
        phi= numpy.arcsin(XYZ[1]/R)
        if (_REFR0-XYZ[0]) < 0.:
            phi= numpy.pi-phi
        newphi.append(phi)
        z= XYZ[2]+_ZSUN
        newzs.append(z)
    newrs= numpy.array(newrs)
    newls= numpy.array(newls)
    newbs= numpy.array(newbs)
    newplate= numpy.array(newplate)
    newgr= numpy.array(newgr)
    newfeh= numpy.array(newfeh)
    newds= numpy.array(newds)
    newRs= numpy.array(newRs)
    newzs= numpy.array(newzs)
    newphi= numpy.array(newphi)
    #Add mock velocities
    newvr= numpy.empty_like(newrs)
    newvt= numpy.empty_like(newrs)
    newvz= numpy.empty_like(newrs)
    use_sampleV= True
    if use_sampleV:
        for kk in range(ndata):
            newv= qdf.sampleV(newRs[kk]/_REFR0,newzs[kk]/_REFR0,n=1)
            newvr[kk]= newv[0,0]*_REFV0*vo
            newvt[kk]= newv[0,1]*_REFV0*vo
            newvz[kk]= newv[0,2]*_REFV0*vo
    else:
        accept_v= numpy.zeros(ndata,dtype='bool')
        naccept= numpy.sum(accept_v)
        sigz= thissz*numpy.exp(-(newRs-_REFR0)/thishsz)
        sigr= thissr*numpy.exp(-(newRs-_REFR0)/thishsr)
        va= numpy.empty_like(newrs)
        sigphi= numpy.empty_like(newrs)
        maxqdf= numpy.empty_like(newrs)
        nvt= 101
        tvt= numpy.linspace(0.1,1.2,nvt)
        for kk in range(ndata):
            #evaluate qdf for vt
            pvt= qdf(newRs[kk]/ro/_REFR0+numpy.zeros(nvt),
                     numpy.zeros(nvt),
                     tvt,
                     newzs[kk]/ro/_REFR0+numpy.zeros(nvt),
                     numpy.zeros(nvt),log=True)
            pvt_maxindx= numpy.argmax(pvt)
            va[kk]= (1.-tvt[pvt_maxindx])*_REFV0*vo
            if options.aAmethod.lower() == 'adiabaticgrid' and options.flatten >= 0.9:
                maxqdf[kk]= pvt[pvt_maxindx]+numpy.log(250.)
            elif options.aAmethod.lower() == 'adiabaticgrid' and options.flatten >= 0.8:
                maxqdf[kk]= pvt[pvt_maxindx]+numpy.log(250.)
            else:
                maxqdf[kk]= pvt[pvt_maxindx]+numpy.log(40.)
            sigphi[kk]= _REFV0*vo*4.*numpy.sqrt(numpy.sum(numpy.exp(pvt)*tvt**2.)/numpy.sum(numpy.exp(pvt))-(numpy.sum(numpy.exp(pvt)*tvt)/numpy.sum(numpy.exp(pvt)))**2.)
        ntries= 0
        ngtr1= 0
        while naccept < ndata:
            sys.stdout.write('\r %i %i %i \r' % (ntries,naccept,ndata))
            sys.stdout.flush()
            #print ntries, naccept, ndata
            ntries+= 1
            accept_v_comp= True-accept_v
            prop_vr= numpy.random.normal(size=ndata)*sigr
            prop_vt= numpy.random.normal(size=ndata)*sigphi+vo*_REFV0-va
            prop_vz= numpy.random.normal(size=ndata)*sigz
            qoverp= numpy.zeros(ndata)-numpy.finfo(numpy.dtype(numpy.float64)).max
            qoverp[accept_v_comp]= (qdf(newRs[accept_v_comp]/ro/_REFR0,
                                        prop_vr[accept_v_comp]/vo/_REFV0,
                                        prop_vt[accept_v_comp]/vo/_REFV0,
                                        newzs[accept_v_comp]/ro/_REFR0,
                                        prop_vz[accept_v_comp]/vo/_REFV0,log=True)
                                    -maxqdf[accept_v_comp] #normalize max to 1
                                    -(-0.5*(prop_vr[accept_v_comp]**2./sigr[accept_v_comp]**2.+prop_vz[accept_v_comp]**2./sigz[accept_v_comp]**2.+(prop_vt[accept_v_comp]-_REFV0*vo+va[accept_v_comp])**2./sigphi[accept_v_comp]**2.)))
            if numpy.any(qoverp > 0.):
                ngtr1+= numpy.sum((qoverp > 0.))
                if ngtr1 > 5:
                    qindx= (qoverp > 0.)
                    print naccept, ndata, newRs[qindx], newzs[qindx], prop_vr[qindx], va[qindx], sigphi[qindx], prop_vt[qindx], prop_vz[qindx], qoverp[qindx]
                    raise RuntimeError("max qoverp = %f > 1, but shouldn't be" % (numpy.exp(numpy.amax(qoverp))))
            accept_these= numpy.log(numpy.random.uniform(size=ndata))
            #print accept_these, (accept_these < qoverp)
            accept_these= (accept_these < qoverp)        
            newvr[accept_these]= prop_vr[accept_these]
            newvt[accept_these]= prop_vt[accept_these]
            newvz[accept_these]= prop_vz[accept_these]
            accept_v[accept_these]= True
            naccept= numpy.sum(accept_v)
        sys.stdout.write('\r'+_ERASESTR+'\r')
        sys.stdout.flush()
    """
    ntot= 0
    nsamples= 0
    itt= 0
    fracsuccess= 0.
    fraccomplete= 0.
    while fraccomplete < 1.:
        if itt == 0:
            nthis= numpy.amax([ndata,_NMIN])
        else:
            nthis= int(numpy.ceil((1-fraccomplete)/fracsuccess*ndata))
        itt+= 1
        count= 0
        while count < nthis:
            count+= 1
            sigz= thissz*numpy.exp(-(R-_REFR0)/thishsz)
            sigr= thissr*numpy.exp(-(R-_REFR0)/thishsr)
            sigphi= sigr #/numpy.sqrt(2.) #BOVY: FOR NOW
            #Estimate asymmetric drift
            va= sigr**2./2./_REFV0/vo\
                *(-.5+R*(1./thishr+2./thishsr))+10.*numpy.fabs(z)
            newvas.append(va)
            if options.mcout and thisoutlier:
                #Sample from outlier gaussian
                newvz.append(numpy.random.normal()*_SZHALOFAKE*2.)
                newvr.append(numpy.random.normal()*_SRHALOFAKE*2.)
                newvt.append(numpy.random.normal()*_SPHIHALOFAKE*2.)
            elif numpy.random.uniform() < lagoutfrac:
                #Sample from lagging gaussian
                newvz.append(numpy.random.normal()*_SZHALOFAKE)
                newvr.append(numpy.random.normal()*_SRHALOFAKE)
                newvt.append(numpy.random.normal()*_SPHIHALOFAKE*2.+_REFV0*vo/4.)
            else:
                #Sample from disk gaussian
                newvz.append(numpy.random.normal()*sigz)
                newvr.append(numpy.random.normal()*sigr)
                newvt.append(numpy.random.normal()*sigphi+_REFV0*vo-va)
            newlogratio= list(newlogratio)
            fidlogeval= numpy.log(1.-lagoutfrac)\
                     -numpy.log(sigr)-numpy.log(sigphi)-numpy.log(sigz)-0.5*(newvr[-1]**2./sigr**2.+newvz[-1]**2./sigz**2.+(newvt[-1]-_REFV0*vo+va)**2./sigphi**2.)
            lagoutlogeval= numpy.log(lagoutfrac)\
                     -numpy.log(_SRHALOFAKE)\
                     -numpy.log(_SPHIHALOFAKE*2.)\
                     -numpy.log(_SZHALOFAKE)\
                     -0.5*(newvr[-1]**2./_SRHALOFAKE**2.+newvz[-1]**2./_SZHALOFAKE**2.+(newvt[-1]-_REFV0*vo/4.)**2./_SPHIHALOFAKE**2./4.)
            if use_real_dens:
                fidlogeval+= numpy.log(compare_func(R,z,None)[0])
                lagoutlogeval+= numpy.log(compare_func(R,z,None)[0])
            else:
                fidlogeval+= numpy.log(fidDens(R,z,thishr,thishz,None))
                lagoutlogeval+= numpy.log(fidDens(R,z,thishr,thishz,None))
            newfideval.append(fidlogeval)
            if options.mcout:
                fidoutlogeval= numpy.log(fidoutfrac)\
                    +numpy.log(outDens(R,z,None))\
                    -numpy.log(_SRHALOFAKE*2.)\
                    -numpy.log(_SPHIHALOFAKE*2.)\
                    -numpy.log(_SZHALOFAKE*2.)\
                    -0.5*(newvr[-1]**2./_SRHALOFAKE**2./4.+newvz[-1]**2./_SZHALOFAKE**2./4.+newvt[-1]**2./_SPHIHALOFAKE**2./4.)
                newpropeval.append(logsumexp([fidoutlogeval,fidlogeval,
                                              lagoutlogeval]))
            else:
                newpropeval.append(logsumexp([lagoutlogeval,fidlogeval]))
            qdflogeval= qdf(R/ro/_REFR0,newvr[-1]/vo/_REFV0,newvt[-1]/vo/_REFV0,z/ro/_REFR0,newvz[-1]/vo/_REFV0,log=True)
            if isinstance(qdflogeval,(list,numpy.ndarray)):
                qdflogeval= qdflogeval[0]
            if options.mcout:
                outlogeval= logoutfrac+loghalodens\
                    -numpy.log(srhalo)-numpy.log(sphihalo)-numpy.log(szhalo)\
                    -0.5*((newvr[-1]/vo/_REFV0)**2./srhalo**2.+(newvz[-1]/vo/_REFV0)**2./szhalo**2.+(newvt[-1]/vo/_REFV0)**2./sphihalo**2.)\
                    -1.5*numpy.log(2.*numpy.pi)
                newqdfeval.append(logsumexp([qdflogeval,outlogeval]))
            else:
                newqdfeval.append(qdflogeval)
            newlogratio.append(qdflogeval
                               -newpropeval[-1])#logsumexp([fidlogeval,fidoutlogeval]))
        newlogratio= numpy.array(newlogratio)
        thisnewlogratio= copy.copy(newlogratio)
        maxnewlogratio= numpy.amax(thisnewlogratio)
        if False:
            argsort_thisnewlogratio= numpy.argsort(thisnewlogratio)[::-1]
            thisnewlogratio-= thisnewlogratio[argsort_thisnewlogratio[2]] #3rd largest
        else:
            thisnewlogratio-= numpy.amax(thisnewlogratio)
        thisnewratio= numpy.exp(thisnewlogratio)
        if len(thisnewratio.shape) > 1 and thisnewratio.shape[1] == 1:
            thisnewratio= numpy.reshape(thisnewratio,(thisnewratio.shape[0]))
        #Rejection sample
        accept= numpy.random.uniform(size=len(thisnewratio))
        accept= (accept < thisnewratio)
        fraccomplete= float(numpy.sum(accept))/ndata
        fracsuccess= float(numpy.sum(accept))/len(thisnewratio)
        if _DEBUG:
            print fraccomplete, fracsuccess, ndata
            print numpy.histogram(thisnewratio,bins=16)
            indx= numpy.argmax(thisnewratio)
            print numpy.array(newvr)[indx], \
                numpy.array(newvt)[indx], \
                numpy.array(newvz)[indx], \
                numpy.array(newrs)[indx], \
                numpy.array(newds)[indx], \
                numpy.array(newls)[indx], \
                numpy.array(newbs)[indx], \
                numpy.array(newfideval)[indx]
            bovy_plot.bovy_print()
            bovy_plot.bovy_plot(numpy.array(newvt),
                                numpy.exp(numpy.array(newqdfeval)),'b,',
                                xrange=[-300.,500.],yrange=[0.,1.])
            bovy_plot.bovy_plot(newvt,
                                numpy.exp(numpy.array(newpropeval+maxnewlogratio)),
                                'g,',
                                overplot=True)
            bovy_plot.bovy_plot(numpy.array(newvt),
                                numpy.exp(numpy.array(newlogratio-maxnewlogratio)),
                                'b,',
                                xrange=[-300.,500.],
                                #                            xrange=[0.,20.],
                                #                            xrange=[0.,3.],
                                #                            xrange=[6.,9.],
                                yrange=[0.001,1.],semilogy=True)
            bovy_plot.bovy_end_print('/home/bovy/public_html/segue-local/test.png')
    #Now collect the samples
    newrs= numpy.array(newrs)[accept][0:ndata]
    newls= numpy.array(newls)[accept][0:ndata]
    newbs= numpy.array(newbs)[accept][0:ndata]
    newplate= numpy.array(newplate)[accept][0:ndata]
    newgr= numpy.array(newgr)[accept][0:ndata]
    newfeh= numpy.array(newfeh)[accept][0:ndata]
    newvr= numpy.array(newvr)[accept][0:ndata]
    newvt= numpy.array(newvt)[accept][0:ndata]
    newvz= numpy.array(newvz)[accept][0:ndata]
    newphi= numpy.array(newphi)[accept][0:ndata]
    newds= numpy.array(newds)[accept][0:ndata]
    newqdfeval= numpy.array(newqdfeval)[accept][0:ndata]
    """
    vx, vy, vz= bovy_coords.galcencyl_to_vxvyvz(newvr,newvt,newvz,newphi,
                                                vsun=[_VRSUN,_VTSUN,_VZSUN])
    vrpmllpmbb= bovy_coords.vxvyvz_to_vrpmllpmbb(vx,vy,vz,newls,newbs,newds,
                                                 XYZ=False,degree=True)
    pmrapmdec= bovy_coords.pmllpmbb_to_pmrapmdec(vrpmllpmbb[:,1],
                                                 vrpmllpmbb[:,2],
                                                 newls,newbs,
                                                 degree=True)
    #Dump everything for debugging the coordinate transformation
    from galpy.util import save_pickles
    save_pickles('dump.sav',
                 newds,newls,newbs,newphi,
                 newvr,newvt,newvz,
                 vx, vy, vz,
                 vrpmllpmbb,
                 pmrapmdec)
    if returnlist:
        out= []
        for ii in range(ndata):
            out.append([newrs[ii],
                        newgr[ii],
                        newfeh[ii],
                        newls[ii],
                        newbs[ii],
                        newplate[ii],
                        newds[ii],
                        False, #outlier?
                        vrpmllpmbb[ii,0],
                        vrpmllpmbb[ii,1],
                        vrpmllpmbb[ii,2]])#,
#                        newqdfeval[ii]])
        return out
    #Load into data
    binned.data.feh[thisdataIndx]= newfeh
    oldgr= thisdata.dered_g-thisdata.dered_r
    oldr= thisdata.dered_r
    if options.noerrs:
        binned.data.dered_r[thisdataIndx]= newrs
    else:
        binned.data.dered_r[thisdataIndx]= newrs\
            +numpy.random.normal(size=numpy.sum(thisdataIndx))\
            *ivezic_dist_gr(oldgr,0., #g-r is all that counts
                            binned.data.feh[thisdataIndx],
                            dg=binned.data[thisdataIndx].g_err,
                            dr=binned.data[thisdataIndx].r_err,
                            dfeh=binned.data[thisdataIndx].feh_err,
                            return_error=True,
                            _returndmr=True)
    binned.data.dered_r[(binned.data.dered_r >= rmax)]= rmax #tweak to make sure everything stays within the observed range
    if False:
        binned.data.dered_r[(binned.data.dered_r <= rmin)]= rmin
    binned.data.dered_g[thisdataIndx]= oldgr+binned.data[thisdataIndx].dered_r
    #Also change plate and l and b
    binned.data.plate[thisdataIndx]= newplate
    radec= bovy_coords.lb_to_radec(newls,newbs,degree=True)
    binned.data.ra[thisdataIndx]= radec[:,0]
    binned.data.dec[thisdataIndx]= radec[:,1]
    binned.data.l[thisdataIndx]= newls
    binned.data.b[thisdataIndx]= newbs
    if options.noerrs:
        binned.data.vr[thisdataIndx]= vrpmllpmbb[:,0]
        binned.data.pmra[thisdataIndx]= pmrapmdec[:,0]
        binned.data.pmdec[thisdataIndx]= pmrapmdec[:,1]
    else:
        binned.data.vr[thisdataIndx]= vrpmllpmbb[:,0]+numpy.random.normal(size=numpy.sum(thisdataIndx))*binned.data.vr_err[thisdataIndx]
        binned.data.pmra[thisdataIndx]= pmrapmdec[:,0]+numpy.random.normal(size=numpy.sum(thisdataIndx))*binned.data.pmra_err[thisdataIndx]
        binned.data.pmdec[thisdataIndx]= pmrapmdec[:,1]+numpy.random.normal(size=numpy.sum(thisdataIndx))*binned.data.pmdec_err[thisdataIndx]
    return binned
Exemplo n.º 5
0
def calcDFResults(options,args,boot=True,nomedian=False):
    if len(args) == 2 and options.sample == 'gk':
        toptions= copy.copy(options)
        toptions.sample= 'g'
        toptions.select= 'all'
        outg= calcDFResults(toptions,[args[0]],boot=boot,nomedian=True)
        toptions.sample= 'k'
        toptions.select= 'program'
        outk= calcDFResults(toptions,[args[1]],boot=boot,nomedian=True)
        #Combine
        out= {}
        for k in outg.keys():
            valg= outg[k]
            valk= outk[k]
            val= numpy.zeros(len(valg)+len(valk))
            val[0:len(valg)]= valg
            val[len(valg):len(valg)+len(valk)]= valk
            out[k]= val
        if nomedian: return out
        else: return add_median(out,boot=boot)
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    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 of the solutions
    sols= []
    chi2s= []
    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)
            chi2s.append(None)
        else:
            sols.append(pickle.load(savefile))
            chi2s.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
    fehs= []
    afes= []
    ndatas= []
    zmedians= []
    #Basic parameters
    hrs= []
    srs= []
    szs= []
    hsrs= []
    hszs= []
    outfracs= []
    rds= []
    rdexps= []
    vcs= []
    zhs= []
    zhexps= []
    dlnvcdlnrs= []
    plhalos= []
    rorss= []
    dvts= []
    #derived parameters
    surfzs= []
    surfz800s= []
    surfzdisks= []
    massdisks= []
    rhoos= []
    rhooalts= []
    rhodms= []
    vcdvcros= []
    vcdvcs= []
    vescs= []
    mloglikemins= []
    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:
                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:
                continue
            try:
                pot= setup_potential(sols[solindx],options,1,interpDens=True,
                                     interpdvcircdr=True,returnrawpot=True)
            except RuntimeError:
                print "A bin has an unphysical potential ..."
                continue
#            if 'dpdisk' in options.potential.lower():
#                try:
#                    rawpot= setup_potential(sols[solindx],options,1,
#                                            returnrawpot=True)
#                except RuntimeError:
#                    print "A bin has an unphysical potential ..."
#                    continue
            fehs.append(tightbinned.feh(ii))
            afes.append(tightbinned.afe(jj))
            zmedians.append(numpy.median(numpy.fabs(data.zc+_ZSUN)))
            #vc
            s= get_potparams(sols[solindx],options,1)
            ro= get_ro(sols[solindx],options)
            if options.fixvo:
                vcs.append(options.fixvo*_REFV0)
            else:
                vcs.append(s[1]*_REFV0)
            #rd
            rds.append(numpy.exp(s[0]))
            #zh
            zhs.append(numpy.exp(s[2-(1-(options.fixvo is None))]))
            #rdexp & zhexp
            if options.sample == 'g': tz= 1.1/_REFR0/ro
            elif options.sample == 'k': tz= 0.84/_REFR0/ro
            if 'mpdisk' in options.potential.lower() or 'mwpotential' in options.potential.lower():
                mp= potential.MiyamotoNagaiPotential(a=rds[-1],b=zhs[-1])
                #rdexp
                f= mp.dens(1.,0.125)
                dr= 10.**-3.
                df= (mp.dens(1.+dr/2.,0.125)-mp.dens(1.-dr/2.,0.125))/dr
                rdexps.append(-f/df)
                #zhexp
                f= mp.dens(1.,tz)
                dz= 10.**-3.
                df= (mp.dens(1.,tz+dz/2.)-mp.dens(1.,tz-dz/2.))/dz
                zhexps.append(-f/df)
            elif 'dpdisk' in options.potential.lower():
                rdexps.append(numpy.exp(s[0]))
                zhexps.append(numpy.exp(s[2-(1-(options.fixvo is None))]))
            #ndata
            ndatas.append(len(data))
            #hr
            dfparams= get_dfparams(sols[solindx],0,options)
            if options.relative:
                thishr= monoAbundanceMW.hr(mapfehs[monoabindx],mapafes[monoabindx])
                hrs.append(dfparams[0]*_REFR0/thishr)
            else:
                hrs.append(dfparams[0]*_REFR0)
            #sz
            if options.relative:
                thissz= monoAbundanceMW.sigmaz(mapfehs[monoabindx],mapafes[monoabindx])
                szs.append(dfparams[2]*_REFV0/thissz)
            else:
                szs.append(dfparams[2]*_REFV0)
            #sr
            if options.relative:
                thissr= monoAbundanceMW.sigmaz(mapfehs[monoabindx],mapafes[monoabindx])*2.#BOVY: UPDATE
                srs.append(dfparams[1]*_REFV0/thissr)
            else:
                srs.append(dfparams[1]*_REFV0)
            #hsr
            hsrs.append(dfparams[3]*_REFR0)
            #hsz
            hszs.append(dfparams[4]*_REFR0)
            #outfrac
            outfracs.append(dfparams[5])
            #rhodm
            #Setup potential
            vo= get_vo(sols[solindx],options,1)
            if 'mwpotential' in options.potential.lower():
                rhodms.append(pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.)
            elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                rhodms.append(pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.)
            elif options.potential.lower() == 'mpdiskflplhalofixplfixbulgeflat':
                rhodms.append(pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.)
            elif options.potential.lower() == 'dpdiskplhalofixbulgeflat' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgas' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgasalt' \
                    or options.potential.lower() == 'dpdiskflplhalofixbulgeflatwgas':
                rhodms.append(pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.)
            #rhoo
            rhoos.append(potential.evaluateDensities(1.,0.,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.)
            #surfz
            surfzs.append(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)
            #surfz800
            surfz800s.append(2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,0.8/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro)
            #surzdisk
            if 'mpdisk' in options.potential.lower() or 'mwpotential' in options.potential.lower():
                surfzdisks.append(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)
                surfzdiskzm= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot[0])),0.,tz)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
            elif 'dpdisk' in options.potential.lower():
                surfzdisks.append(2.*pot[0].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.*zhexps[-1]*ro*_REFR0*1000.)
            #rhooalt
            if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                rhooalts.append(rhoos[-1]-pot[0].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.+surfzdiskzm/2./zhexps[-1]/ro/_REFR0/1000./(1.-numpy.exp(-tz/zhexps[-1])))
            elif options.potential.lower() == 'dpdiskplhalofixbulgeflat' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgas' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgasalt' \
                    or options.potential.lower() == 'dpdiskflplhalofixbulgeflatwgas':
                rhooalts.append(rhoos[-1])
            #massdisk
            if options.potential.lower() == 'dpdiskplhalofixbulgeflat' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgas' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgasalt' \
                    or options.potential.lower() == 'dpdiskflplhalofixbulgeflatwgas':
                rhod= pot[0].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
            else:
                rhod= surfzdiskzm/2./zhexps[-1]/ro/_REFR0/1000./(1.-numpy.exp(-tz/zhexps[-1]))
            massdisks.append(rhod*2.*zhexps[-1]*numpy.exp(1./rdexps[-1])*rdexps[-1]**2.*2.*numpy.pi*(ro*_REFR0)**3./10.)
            #plhalo
            if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                plhalos.append(pot[1].alpha)
                plhalos.append((1.-pot[1].alpha)/(pot[1].alpha-3.))
            elif options.potential.lower() == 'dpdiskplhalofixbulgeflat' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgas' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgasalt' \
                    or options.potential.lower() == 'dpdiskflplhalofixbulgeflatwgas':
                plhalos.append(pot[1].alpha)
                rorss.append((1.-pot[1].alpha)/(pot[1].alpha-3.))
            #dlnvcdlnr
            if options.potential.lower() == 'dpdiskplhalofixbulgeflat' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgas' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgasalt' \
                    or options.potential.lower() == 'dpdiskflplhalofixbulgeflatwgas':
                dlnvcdlnrs.append(potential.dvcircdR(pot,1.))
            else:
                dlnvcdlnrs.append(potential.dvcircdR(pot,1.))
            #vcdvc
            if options.potential.lower() == 'dpdiskplhalofixbulgeflat' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgas' \
                    or options.potential.lower() == 'dpdiskplhalofixbulgeflatwgasalt' \
                    or options.potential.lower() == 'dpdiskflplhalofixbulgeflatwgas':
                vcdvcros.append(pot[0].vcirc(1.)/potential.vcirc(pot,1.))
                vcdvcs.append(pot[0].vcirc(2.2*rdexps[-1])/potential.vcirc(pot,2.2*rdexps[-1]))
            else:
                vcdvcros.append(pot[0].vcirc(1.)/potential.vcirc(pot,1.))
                vcdvcs.append(pot[0].vcirc(2.2*rdexps[-1])/potential.vcirc(pot,2.2*rdexps[-1]))
            #mloglike
            mloglikemins.append(chi2s[solindx])
            #escape velocity
            vescs.append(potential.vesc(pot,1.)*_REFV0)
            if options.fitdvt:
                dvts.append(sols[solindx][0])
    #Gather
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    zmedians= numpy.array(zmedians)
    ndatas= numpy.array(ndatas)
    #Basic parameters
    hrs= numpy.array(hrs)
    srs= numpy.array(srs)
    szs= numpy.array(szs)
    hsrs= numpy.array(hsrs)
    hszs= numpy.array(hszs)
    outfracs= numpy.array(outfracs)
    vcs= numpy.array(vcs)
    rds= numpy.array(rds)
    zhs= numpy.array(zhs)
    rdexps= numpy.array(rdexps)
    zhexps= numpy.array(zhexps)
    dlnvcdlnrs= numpy.array(dlnvcdlnrs)
    plhalos= numpy.array(plhalos)
    rorss= numpy.array(rorss)
    if options.fitdvt:
        dvts= numpy.array(dvts)
    #derived parameters
    surfzs= numpy.array(surfzs)
    surfz800s= numpy.array(surfz800s)
    surfzdisks= numpy.array(surfzdisks)
    massdisks= numpy.array(massdisks)
    rhoos= numpy.array(rhoos)
    rhooalts= numpy.array(rhooalts)
    rhodms= numpy.array(rhodms)
    vcdvcros= numpy.array(vcdvcros)
    vcdvcs= numpy.array(vcdvcs)
    rexps= numpy.sqrt(2.)*(rds+zhs)/2.2
    mloglikemins= numpy.array(mloglikemins)
    vescs= numpy.array(vescs)
    #Load into dictionary
    out= {}
    out['feh']= fehs
    out['afe']= afes
    out['zmedian']= zmedians
    out['ndata']= ndatas
    out['hr']= hrs
    out['sr']= srs
    out['sz']= szs
    out['hsr']= hsrs
    out['hsz']= hszs
    out['outfrac']= outfracs
    out['vc']= vcs
    out['rd']= rds
    out['zh']= zhs
    out['rdexp']= rdexps
    out['zhexp']= zhexps
    out['dlnvcdlnr']= dlnvcdlnrs
    out['plhalo']= plhalos
    out['rors']= rorss
    out['surfz']= surfzs
    out['surfz800']= surfz800s
    out['surfzdisk']= surfzdisks
    out['massdisk']= massdisks
    out['rhoo']= rhoos
    out['rhooalt']= rhooalts
    out['rhodm']= rhodms
    out['vcdvc']= vcdvcs
    out['vcdvcro']= vcdvcros
    out['rexp']= rexps
    out['mloglikemin']= mloglikemins
    out['vesc']= vescs
    if options.fitdvt:
        out['dvt']= dvts
    if nomedian: return out
    else: return add_median(out,boot=boot)