def plotDensComparisonDFMulti(options, args):
    # Read data etc.
    print "Reading the data ..."
    raw = read_rawdata(options)
    # Bin the data
    binned = pixelAfeFeh(raw, dfeh=options.dfeh, dafe=options.dafe)
    # Map the bins with ndata > minndata in 1D
    fehs, afes = [], []
    for ii in range(len(binned.fehedges) - 1):
        for jj in range(len(binned.afeedges) - 1):
            data = binned(binned.feh(ii), binned.afe(jj))
            if len(data) < options.minndata:
                continue
            # print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins = len(fehs)
    fehs = numpy.array(fehs)
    afes = numpy.array(afes)
    gafes, gfehs, left_legend = getMultiComparisonBins(options)
    if options.usemedianpotential:
        potparams = get_median_potential(options, nabundancebins)
        print "Median potential parameters: ", potparams
    # Setup everything for the selection function
    print "Setting up stuff for the normalization integral ..."
    normintstuff = setup_normintstuff(options, raw, binned, fehs, afes)
    M = len(gfehs)
    # Check whether fits exist, if not, pop
    removeBins = numpy.ones(M, dtype="bool")
    for jj in range(M):
        # Find pop corresponding to this bin
        pop = numpy.argmin((gfehs[jj] - fehs) ** 2.0 / 0.1 + (gafes[jj] - afes) ** 2.0 / 0.0025)
        # Load savefile
        if not options.init is None:
            # Load initial parameters from file
            savename = options.init
            spl = savename.split(".")
            newname = ""
            for ll in range(len(spl) - 1):
                newname += spl[ll]
                if not ll == len(spl) - 2:
                    newname += "."
            newname += "_%i." % pop
            newname += spl[-1]
            if not os.path.exists(newname):
                removeBins[jj] = False
        else:
            raise IOError("base filename not specified ...")
    if numpy.sum(removeBins) == 0:
        raise IOError("None of the group bins have been fit ...")
    elif numpy.sum(removeBins) < M:
        # Some bins have not been fit yet, and have to be removed
        gfehs = list((numpy.array(gfehs))[removeBins])
        gafes = list((numpy.array(gafes))[removeBins])
        print "Only using %i bins out of %i ..." % (numpy.sum(removeBins), M)
        M = len(gfehs)
    model1s = []
    model2s = []
    model3s = []
    params1 = []
    params2 = []
    params3 = []
    data = []
    colordists = []
    fehdists = []
    fehmins = []
    fehmaxs = []
    cfehs = []
    for jj in range(M):
        print "Working on group %i / %i ..." % (jj + 1, M)
        # Find pop corresponding to this bin
        pop = numpy.argmin((gfehs[jj] - fehs) ** 2.0 / 0.1 + (gafes[jj] - afes) ** 2.0 / 0.0025)
        # Load savefile
        if not options.init is None:
            # Load initial parameters from file
            savename = options.init
            spl = savename.split(".")
            newname = ""
            for ll in range(len(spl) - 1):
                newname += spl[ll]
                if not ll == len(spl) - 2:
                    newname += "."
            newname += "_%i." % pop
            newname += spl[-1]
            savefile = open(newname, "rb")
            tparams = pickle.load(savefile)
            savefile.close()
        else:
            raise IOError("base filename not specified ...")
        if options.usemedianpotential:
            tparams = set_potparams(potparams, tparams, options, 1)
        print tparams
        # Set up density models and their parameters
        model1s.append(interpDens)
        paramsInterp, surfz = calc_model(tparams, options, 0, _retsurfz=True)
        params1.append(paramsInterp)
        if True:
            # Add outlier and plot sum
            if not options.usemedianpotential:
                potparams = get_potparams(tparams, options, 1)
            logoutfrac = numpy.log(get_outfrac(tparams, 0, options))
            logoutfrac += numpy.log(surfz)
            outfrac = numpy.exp(logoutfrac)
            ro = get_ro(tparams, options)
            halodens = ro * outDens(1.0, 0.0, None)
            model2s.append(interpDenswoutlier)
            params2.append([paramsInterp, outfrac * halodens])
            model3s.append(None)
            params3.append(None)
        elif False:
            if not options.usemedianpotential:
                potparams = get_potparams(tparams, options, 1)
            if options.potential.lower() == "flatlog":
                tparams = set_potparams([potparams[0] * 1.05, potparams[1]], tparams, options, 1)
                model2s.append(interpDens)
                params2.append(calc_model(tparams, options, 0))
                tparams = set_potparams([potparams[0] * 0.95, potparams[1]], tparams, options, 1)
                model3s.append(interpDens)
                params3.append(calc_model(tparams, options, 0))
            elif options.potential.lower() == "mwpotentialfixhalo":
                tparams = set_potparams(
                    [numpy.log(2.0 / _REFR0), potparams[1], potparams[2], potparams[3], potparams[4]],
                    tparams,
                    options,
                    1,
                )
                model2s.append(interpDens)
                params2.append(calc_model(tparams, options, 0))
                tparams = set_potparams(
                    [numpy.log(3.0 / 8.0), potparams[1], potparams[2], potparams[3], potparams[4]], tparams, options, 1
                )
                model3s.append(interpDens)
                params3.append(calc_model(tparams, options, 0))
        else:
            model2s.append(None)
            params2.append(None)
            model3s.append(None)
            params3.append(None)
        data.append(binned(fehs[pop], afes[pop]))
        # Setup everything for selection function
        thisnormintstuff = normintstuff[pop]
        if _PRECALCVSAMPLES:
            sf, plates, platel, plateb, platebright, platefaint, grmin, grmax, rmin, rmax, fehmin, fehmax, feh, colordist, fehdist, gr, rhogr, rhofeh, mr, dmin, dmax, ds, surfscale, hr, hz, surfnrs, surfnzs, surfRgrid, surfzgrid, surfvrs, surfvts, surfvzs = unpack_normintstuff(
                thisnormintstuff, options
            )
        else:
            sf, plates, platel, plateb, platebright, platefaint, grmin, grmax, rmin, rmax, fehmin, fehmax, feh, colordist, fehdist, gr, rhogr, rhofeh, mr, dmin, dmax, ds, surfscale, hr, hz = unpack_normintstuff(
                thisnormintstuff, options
            )
        colordists.append(colordist)
        fehdists.append(fehdist)
        fehmins.append(fehmin)
        fehmaxs.append(fehmax)
        cfehs.append(feh)
        if True:
            # Cut out bright stars on faint plates and vice versa
            indx = []
            nfaintbright, nbrightfaint = 0, 0
            for ii in range(len(data[jj].feh)):
                if sf.platebright[str(data[jj][ii].plate)] and data[jj][ii].dered_r >= 17.8:
                    indx.append(False)
                    nbrightfaint += 1
                elif not sf.platebright[str(data[jj][ii].plate)] and data[jj][ii].dered_r < 17.8:
                    indx.append(False)
                    nfaintbright += 1
                else:
                    indx.append(True)
            print "nbrightfaint, nfaintbright", nbrightfaint, nfaintbright
            indx = numpy.array(indx, dtype="bool")
            if numpy.sum(indx) > 0:
                data[jj] = data[jj][indx]
    # Ranges
    if options.type == "z":
        xrange = [-0.1, 5.0]
    elif options.type == "R":
        xrange = [4.8, 14.2]
    elif options.type == "r":
        xrange = [14.2, 20.1]
    # We do bright/faint for 4 directions and all, all bright, all faint
    ls = [180, 180, 45, 45]
    bs = [0, 90, -23, 23]
    bins = 21
    # Set up comparison
    if options.type == "r":
        compare_func = compareDataModel.comparerdistPlateMulti
    elif options.type == "z":
        compare_func = compareDataModel.comparezdistPlateMulti
    elif options.type == "R":
        compare_func = compareDataModel.compareRdistPlateMulti
    # all, faint, bright
    bins = [31, 31, 31]
    plates = ["all", "bright", "faint"]
    for ii in range(len(plates)):
        plate = plates[ii]
        if plate == "all":
            thisleft_legend = left_legend
            #            thisright_legend= right_legend
            #            thisleft_legend= None
            thisright_legend = None
        else:
            thisleft_legend = None
            thisright_legend = None
        bovy_plot.bovy_print()
        compare_func(
            model1s,
            params1,
            sf,
            colordists,
            fehdists,
            data,
            plate,
            color="k",
            rmin=14.5,
            rmax=rmax,
            grmin=grmin,
            grmax=grmax,
            fehmin=fehmins,
            fehmax=fehmaxs,
            feh=cfehs,
            xrange=xrange,
            bins=bins[ii],
            ls="-",
            left_legend=thisleft_legend,
            right_legend=thisright_legend,
        )
        if not params2[0] is None:
            compare_func(
                model2s,
                params2,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins[ii],
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls="--",
            )
        if not params3[0] is None:
            compare_func(
                model3s,
                params3,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins[ii],
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls=":",
            )
        if options.type == "r":
            bovy_plot.bovy_end_print(args[0] + "model_data_g_" + options.group + "_" + plate + "." + options.ext)
        else:
            bovy_plot.bovy_end_print(
                args[0] + "model_data_g_" + options.group + "_" + options.type + "dist_" + plate + "." + options.ext
            )
        if options.all:
            return None
    bins = 16
    for ii in range(len(ls)):
        # Bright
        plate = compareDataModel.similarPlatesDirection(ls[ii], bs[ii], 20.0, sf, data, faint=False)
        bovy_plot.bovy_print()
        compare_func(
            model1s,
            params1,
            sf,
            colordists,
            fehdists,
            data,
            plate,
            color="k",
            rmin=14.5,
            rmax=rmax,
            grmin=grmin,
            grmax=grmax,
            fehmin=fehmins,
            fehmax=fehmaxs,
            feh=cfehs,
            xrange=xrange,
            bins=bins,
            ls="-",
        )
        if not params2[0] is None:
            compare_func(
                model2s,
                params2,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls="--",
            )
        if not params3[0] is None:
            compare_func(
                model3s,
                params3,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls=":",
            )
        if options.type == "r":
            bovy_plot.bovy_end_print(
                args[0] + "model_data_g_" + options.group + "_" + "l%i_b%i_bright." % (ls[ii], bs[ii]) + options.ext
            )
        else:
            bovy_plot.bovy_end_print(
                args[0]
                + "model_data_g_"
                + options.group
                + "_"
                + options.type
                + "dist_l%i_b%i_bright." % (ls[ii], bs[ii])
                + options.ext
            )
        # Faint
        plate = compareDataModel.similarPlatesDirection(ls[ii], bs[ii], 20.0, sf, data, bright=False)
        bovy_plot.bovy_print()
        compare_func(
            model1s,
            params1,
            sf,
            colordists,
            fehdists,
            data,
            plate,
            color="k",
            rmin=14.5,
            rmax=rmax,
            grmin=grmin,
            grmax=grmax,
            fehmin=fehmins,
            fehmax=fehmaxs,
            feh=cfehs,
            xrange=xrange,
            bins=bins,
            ls="-",
        )
        if not params2[0] is None:
            compare_func(
                model2s,
                params2,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls="--",
            )
        if not params3[0] is None:
            compare_func(
                model3s,
                params3,
                sf,
                colordists,
                fehdists,
                data,
                plate,
                color="k",
                bins=bins,
                rmin=14.5,
                rmax=rmax,
                grmin=grmin,
                grmax=grmax,
                fehmin=fehmins,
                fehmax=fehmaxs,
                feh=cfehs,
                xrange=xrange,
                overplot=True,
                ls=":",
            )
        if options.type == "r":
            bovy_plot.bovy_end_print(
                args[0] + "model_data_g_" + options.group + "_" + "l%i_b%i_faint." % (ls[ii], bs[ii]) + options.ext
            )
        else:
            bovy_plot.bovy_end_print(
                args[0]
                + "model_data_g_"
                + options.group
                + "_"
                + options.type
                + "dist_l%i_b%i_faint." % (ls[ii], bs[ii])
                + options.ext
            )
    return None
def plotDensComparisonDF(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    if not options.singlefeh is None:
        if True: #Just to keep indentation the same
            #Set up single feh
            indx= binned.callIndx(options.singlefeh,options.singleafe)
            if numpy.sum(indx) == 0:
                raise IOError("Bin corresponding to singlefeh and singleafe is empty ...")
            allraw= copy.copy(raw)
            raw= copy.copy(binned.data[indx])
            #newerrstuff= []
            #for ii in range(len(binned.data)):
            #    if indx[ii]: newerrstuff.append(errstuff[ii])
            #errstuff= newerrstuff
            print "Using %i data points ..." % (len(data))
            #Bin again
            binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
            fehs, afes= [], []
            for ii in range(len(binned.fehedges)-1):
                for jj in range(len(binned.afeedges)-1):
                    data= binned(binned.feh(ii),binned.afe(jj))
                    if len(data) < options.minndata:
                        continue
                    fehs.append(binned.feh(ii))
                    afes.append(binned.afe(jj))
            nabundancebins= len(fehs)
            fehs= numpy.array(fehs)
            afes= numpy.array(afes)
    if options.singles:
        run_abundance_singles_plotdens(options,args,fehs,afes)
        return None
    if options.andistances:
        data= binned(fehs[0],afes[0])
        distfac= AnDistance.AnDistance(data.dered_g-data.dered_r,
                                       data.feh)
        if options.fixdm is None:
            options.fixdm= numpy.log10(distfac)*5.
        else:
            options.fixdm= options.fixdm+numpy.log10(distfac)*5.
        options.andistances= False
        #Start over
        plotDensComparisonDF(options,args)
        return None
    #Setup everything for the selection function
    print "Setting up stuff for the normalization integral ..."
    normintstuff= setup_normintstuff(options,raw,binned,fehs,afes,allraw)
    ##########POTENTIAL PARAMETERS####################
    potparams1= numpy.array([numpy.log(2.5/8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.2,0.])
    potparams2= numpy.array([numpy.log(3./8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.466666666,0.])
    potparams3= numpy.array([numpy.log(2.5/8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.8,0.])
    options.potential=  'dpdiskplhalofixbulgeflatwgasalt'
    #Set up density models and their parameters
    pop= 0 #assume first population
    #Load savefile
    if not options.init is None:
        #Load initial parameters from file
        savename= options.init
#        spl= savename.split('.')
#        newname= ''
#        for ll in range(len(spl)-1):
#            newname+= spl[ll]
#            if not ll == len(spl)-2: newname+= '.'
#        newname+= '_%i.' % pop
#        newname+= spl[-1]
        savefile= open(savename,'rb')
        try:
            if not _NOTDONEYET:
                params= pickle.load(savefile)
                mlogl= pickle.load(savefile)
            logl= pickle.load(savefile)
        except:
            if savetopickle:
                save_pickles(tmpfiles[jj],None)
                return None
            else:
                return None
        finally:
            savefile.close()
    else:
        raise IOError("base filename not specified ...")
    #First model is best-fit for this particular bin
    marglogl= numpy.zeros((8,16))
    for ll in range(8):
        for kk in range(16):
            marglogl[ll,kk]= logsumexp(logl[ll,0,0,kk,:,:,:,0])
    indx= numpy.unravel_index(numpy.nanargmax(marglogl),(8,16))
    print "Maximum for %i at %i,%i" % (pop,indx[0],indx[1])
    rds= numpy.linspace(2.0,3.4,options.nrds)/_REFR0
    rds= numpy.log(rds)
    fhs= numpy.linspace(0.,1.,options.nfhs)
    potparams1[0]= rds[indx[0]]
    potparams1[3]= fhs[indx[1]]
    #######DF PARAMETER RANGES###########
    hrs, srs, szs=  setup_dfgrid(fehs,afes,options)
    dfindx= numpy.unravel_index(numpy.nanargmax(logl[indx[0],0,0,indx[1],:,:,:,0]),
                                (8,8,16))
    print "Maximum for %i at %i,%i,%i" % (pop,dfindx[0],dfindx[1],dfindx[2])
    tparams= initialize(options,fehs,afes)
    startindx= 0
    if options.fitdvt: startindx+= 1
    tparams[startindx]= hrs[dfindx[0]]
    tparams[startindx+4]= srs[dfindx[1]]
    tparams[startindx+2]= szs[dfindx[2]]
    tparams[startindx+5]= 0. #outlier fraction
    tparams= set_potparams(potparams1,tparams,options,1)
    #Set up density models and their parameters
    model1= interpDens#woutlier
    print "Working on model 1 ..."
    paramsInterp= calc_model(tparams,options,0,_retsurfz=False,
                             normintstuff=normintstuff)
    params1= paramsInterp
    if False:
        indx0= numpy.argmin((potparams2[0]-rds)**2.)
        indx1= numpy.argmin((potparams2[3]-fhs)**2.)
        #indx0= indx[0]
        #indx1= indx[1]
        dfindx= numpy.unravel_index(numpy.argmax(logl[indx0,0,0,indx1,:,:,:,0]),
                                    (8,8,16))
        tparams[startindx]= hrs[dfindx[0]]
        tparams[startindx+4]= srs[dfindx[1]]
        tparams[startindx+2]= szs[dfindx[2]]
        #print "BOVY: YOU HAVE MESSED WITH MODEL 2"
        tparams= set_potparams(potparams2,tparams,toptions,1)
        model2= interpDens
        print "Working on model 2 ..."
        paramsInterp, surfz= calc_model(tparams,toptions,0,_retsurfz=True)
        params2= paramsInterp
        indx0= numpy.argmin((potparams3[0]-rds)**2.)
        indx1= numpy.argmin((potparams3[3]-fhs)**2.)
        dfindx= numpy.unravel_index(numpy.argmax(logl[indx0,0,0,indx1,:,:,:,0]),
                                    (8,8,16))
        tparams[startindx]= hrs[dfindx[0]]
        tparams[startindx+4]= srs[dfindx[1]]
        tparams[startindx+2]= szs[dfindx[2]]
        tparams= set_potparams(potparams3,tparams,toptions,1)
        model3= interpDens
        print "Working on model 3 ..."
        paramsInterp, surfz= calc_model(tparams,toptions,0,_retsurfz=True)
        params3= paramsInterp
    else:
        model2= None
        params2= None
        model3= None
        params3= None
    data= binned(fehs[pop],afes[pop])
    #Setup everything for selection function
    thisnormintstuff= normintstuff[pop]
    if _PRECALCVSAMPLES:
        sf, plates,platel,plateb,platebright,platefaint,grmin,grmax,rmin,rmax,fehmin,fehmax,feh,colordist,fehdist,gr,rhogr,rhofeh,mr,dmin,dmax,ds, surfscale, hr, hz, colorfehfac,normR, normZ,surfnrs, surfnzs, surfRgrid, surfzgrid, surfvrs, surfvts, surfvzs= unpack_normintstuff(thisnormintstuff,options)
    else:
        sf, plates,platel,plateb,platebright,platefaint,grmin,grmax,rmin,rmax,fehmin,fehmax,feh,colordist,fehdist,gr,rhogr,rhofeh,mr,dmin,dmax,ds, surfscale, hr, hz, colorfehfac, normR, normZ= unpack_normintstuff(thisnormintstuff,options)
    if True:
        #Cut out bright stars on faint plates and vice versa
        indx= []
        nfaintbright, nbrightfaint= 0, 0
        for ii in range(len(data.feh)):
            if sf.platebright[str(data[ii].plate)] and data[ii].dered_r >= 17.8:
                indx.append(False)
                nbrightfaint+= 1
            elif not sf.platebright[str(data[ii].plate)] and data[ii].dered_r < 17.8:
                indx.append(False)
                nfaintbright+= 1
            else:
                indx.append(True)
        print "nbrightfaint, nfaintbright", nbrightfaint, nfaintbright
        indx= numpy.array(indx,dtype='bool')
        data= data[indx]
    #Ranges
    if options.type == 'z':
        xrange= [-0.1,5.]
    elif options.type == 'R':
        xrange= [4.8,14.2]
    elif options.type == 'r':
        xrange= [14.2,20.1]
    #We do bright/faint for 4 directions and all, all bright, all faint
    ls= [180,180,45,45]
    bs= [0,90,-23,23]
    bins= 21
    #Set up comparison
    if options.type == 'r':
        compare_func= compareDataModel.comparerdistPlate
    elif options.type == 'z':
        compare_func= compareDataModel.comparezdistPlate
    elif options.type == 'R':
        compare_func= compareDataModel.compareRdistPlate
    #First do R ranges for z
    if options.type.lower() == 'z' and _RRANGES:
        bins=21
        Rmins= [None,7.,9.]
        Rmaxs= [7.,9.,None]
        nameRmins= [4,7,9]
        nameRmaxs= [7,9,13]
        for ii in range(len(Rmins)):
            plate= 'all'
            if Rmins[ii] is None:
                thisleft_legend= r'$R \leq 7\,\mathrm{kpc\ plates}$'
            elif Rmins[ii] == 7.:
                thisleft_legend= r'$7\,\mathrm{kpc} < R \leq 9\,\mathrm{kpc\ plates}$'
            elif Rmaxs[ii] is None:
                thisleft_legend= r'$R \geq 9\,\mathrm{kpc\ plates}$'
            thisright_legend= None
            bovy_plot.bovy_print()
            compare_func(model1,params1,sf,colordist,fehdist,
                         data,plate,color='k',
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         bins=bins,ls='-',left_legend=thisleft_legend,
                         right_legend=thisright_legend,
                         Rmin=Rmins[ii],Rmax=Rmaxs[ii])
            if not params2 is None:
                compare_func(model2,params2,sf,colordist,fehdist,
                             data,plate,color='k',bins=bins,
                             rmin=14.5,rmax=rmax,
                             grmin=grmin,grmax=grmax,
                             fehmin=fehmin,fehmax=fehmax,feh=feh,
                             xrange=xrange,
                             overplot=True,ls='--',
                             Rmin=Rmins[ii],Rmax=Rmaxs[ii])
            if not params3 is None:
                compare_func(model3,params3,sf,colordist,fehdist,
                             data,plate,color='k',bins=bins,
                             rmin=14.5,rmax=rmax,
                             grmin=grmin,grmax=grmax,
                             fehmin=fehmin,fehmax=fehmax,feh=feh,
                             xrange=xrange,
                             overplot=True,ls=':',
                             Rmin=Rmins[ii],Rmax=Rmaxs[ii])
            if options.type == 'r':
                bovy_plot.bovy_end_print(args[0]+'model_data_g_%iR%i' % (nameRmins[ii],nameRmaxs[ii])+'.'+options.ext)
            else:
                bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_%iR%i' % (nameRmins[ii],nameRmaxs[ii])+'.'+options.ext)
    #all, faint, bright
    bins= [31,31,31]
    plates= ['all','bright','faint']
    for ii in range(len(plates)):
        plate= plates[ii]
        if plate == 'all':
#            thisleft_legend= left_legend
#            thisright_legend= right_legend
            thisleft_legend= None
            thisright_legend= None
        else:
            thisleft_legend= None
            thisright_legend= None
        bovy_plot.bovy_print()
        compare_func(model1,params1,sf,colordist,fehdist,
                     data,plate,color='k',
                     rmin=14.5,rmax=rmax,
                     grmin=grmin,grmax=grmax,
                     fehmin=fehmin,fehmax=fehmax,feh=feh,
                     xrange=xrange,
                     bins=bins[ii],ls='-',left_legend=thisleft_legend,
                     right_legend=thisright_legend)
        if not params2 is None:
            compare_func(model2,params2,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins[ii],
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins[ii],
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+plate+'.'+options.ext)
        else:
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_'+plate+'.'+options.ext)
        if options.all: return None
    bins= 16
    for ii in range(len(ls)):
        nodata= False
        #Bright
        plate= compareDataModel.similarPlatesDirection(ls[ii],bs[ii],20.,
                                                       sf,data,
                                                       faint=False)
        bovy_plot.bovy_print()
        try:
            compare_func(model1,params1,sf,colordist,fehdist,
                         data,plate,color='k',
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         bins=bins,ls='-')
        except IndexError:
            #no data
            nodata= True
        if not params2 is None and not nodata:
            compare_func(model2,params2,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None and not nodata:
            compare_func(model3,params3,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if not nodata:
            if options.type == 'r':
                bovy_plot.bovy_end_print(args[0]+'model_data_g_'+'l%i_b%i_bright.' % (ls[ii],bs[ii])+options.ext)
            else:
                bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_l%i_b%i_bright.' % (ls[ii],bs[ii])+options.ext)
        #Faint
        plate= compareDataModel.similarPlatesDirection(ls[ii],bs[ii],20.,
                                                       sf,data,
                                                       bright=False)
        bovy_plot.bovy_print()
        try:
            compare_func(model1,params1,sf,colordist,fehdist,
                         data,plate,color='k',
                         rmin=14.5,rmax=rmax,
                         grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         bins=bins,ls='-')
        except IndexError:
            #No data
            continue
        if not params2 is None:
            compare_func(model2,params2,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,colordist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,grmin=grmin,
                         grmax=grmax,
                         fehmin=fehmin,fehmax=fehmax,feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+'l%i_b%i_faint.' % (ls[ii],bs[ii])+options.ext)
        else:
            bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_l%i_b%i_faint.' % (ls[ii],bs[ii])+options.ext)
    return None
Example #3
0
def compareGRichRdist(options,args):
    if options.png: ext= 'png'
    else: ext= 'ps'
    #Set up density models and their parameters
    model1= _TwoDblExpDensity
    model2= _TwoDblExpDensity
    model3= _TwoDblExpDensity
    params2= None
    params3= None
    #model2= _HWRDensity
    left_legend= None
    if options.metal.lower() == 'rich':
        params1= numpy.array([-1.36358793,
                               -0.40929899,
                               1.29196694,
                               1.85495651,
                               0.0123595])
        params2= numpy.array([-1.36358793,
                               -0.40929899,
                               numpy.log(2.),
                               1.85495651,
                               0.0123595])
        params3= numpy.array([-1.36358793,
                               -0.40929899,
                               numpy.log(3.),
                               1.85495651,
                               0.0123595])
        left_legend= r'$[\mathrm{Fe/H}] > -0.3$'
    elif options.metal.lower() == 'poor':
        params1= numpy.array([-0.37728915,
                               -0.06891146,
                               0.69623296,
                               1.0986486,
                               0.04188442])
        params2= numpy.array([-0.37728915,
                               -0.06891146,
                               numpy.log(3.),
                               1.0986486,
                               0.04188442])
        params3= numpy.array([-0.37728915,
                               -0.06891146,
                               numpy.log(4.),
                               1.0986486,
                               0.04188442])
    elif options.metal.lower() == 'poorpoor':
        model1= _TwoDblExpDensity
        model2= _TwoDblExpDensity
        model3= _TwoDblExpDensity
        params1= numpy.array([-0.15566038,
                               -0.14511052,
                               0.72449094,
                               0.73929871,
                               0.06788415])
        params2= numpy.array([-0.15566038,
                               -0.14511052,
                               numpy.log(3.),
                               0.73929871,
                               0.06788415])
        params3= numpy.array([-0.15566038,
                               -0.14511052,
                               numpy.log(4.),
                               0.73929871,
                               0.06788415])
        left_legend= r'$[\mathrm{Fe/H}] < -0.70$'
    elif options.metal.lower() == 'poorrich':
        model1= _TwoDblExpDensity
        model2= _TwoDblExpDensity
        model3= _TwoDblExpDensity
        params1= numpy.array([-0.5387634,
                               -0.13596311,
                               0.67857382,
                               1.37668202,
                               0.03020303])
        params2= numpy.array([-0.5387634,
                               -0.13596311,
                               numpy.log(3.),
                               1.37668202,
                               0.03020303])
        params3= numpy.array([-0.5387634,
                               -0.13596311,
                               numpy.log(4.),
                               1.37668202,
                               0.03020303])
        left_legend= r'$[\mathrm{Fe/H}] \geq -0.70$'
    elif options.metal.lower() == 'richpoor':
        model1= _TwoDblExpDensity
        model2= _TwoDblExpDensity
        model3= _TwoDblExpDensity
        params1= numpy.array([-1.02044843,
                               -0.05517342,
                               3.35487325,
                               3.69485597,
                               0.01818825])
        params2= numpy.array([-1.02044843,
                               -0.05517342,
                               numpy.log(2.),
                               3.69485597,
                               0.01818825])
        params3= numpy.array([-1.02044843,
                               -0.05517342,
                               numpy.log(3.),
                               3.69485597,
                               0.01818825])
        left_legend= r'$-0.6 < [\mathrm{Fe/H}] < -0.3$'
    elif options.metal.lower() == 'richrich':
        model1= _TwoDblExpDensity
        params1= numpy.array([-1.36358793,
                               -0.40929899,
                               1.29196694,
                               1.85495651,
                               0.0123595])
        params2= numpy.array([-1.36358793,
                               -0.40929899,
                               numpy.log(2.),
                               1.85495651,
                               0.0123595])
        params3= numpy.array([-1.36358793,
                               -0.40929899,
                               numpy.log(3.),
                               1.85495651,
                               0.0123595])
        left_legend= r'$[\mathrm{Fe/H}] \geq -0.25$'
        params3= None
    elif options.metal.lower() == 'richpoorest':
        model1= _TwoDblExpDensity
        params1= numpy.array([-0.37302496,
                               0.35869237,
                               4.60494691,
                               0.13423782,
                               0.02584325])
        params2= numpy.array([-0.37302496,
                               0.35869237,
                               numpy.log(2.),
                               0.13423782,
                               0.02584325])
        params3= numpy.array([-0.37302496,
                               0.35869237,
                               numpy.log(3.),
                               0.13423782,
                               0.02584325])
        left_legend= r'$-1.5 < [\mathrm{Fe/H}] < -0.6$'
    elif options.metal.lower() == 'apoorpoor':
        model1= _TwoDblExpDensity
        params1= numpy.array([-1.42966594,
                               -0.43592629,
                               1.46092453,
                               2.31726435,
                               0.01014193])
        params2= None
        left_legend= r'$0.00 < [\alpha/\mathrm{Fe}] < 0.15$'
    elif options.metal.lower() == 'apoorrich':
        model1= _TwoDblExpDensity
        params1= numpy.array([-1.05609215,
                               -0.04159115,
                               0.85264104,
                               1.61003202,
                               0.01804995])
        params2= None
        left_legend= r'$0.15 \leq [\alpha/\mathrm{Fe}] < 0.25$'
    elif options.metal.lower() == 'arichpoor':
        model1= _TwoDblExpDensity
        params1= numpy.array([-0.46676741,
                               -0.22070634,
                               0.80226706,
                               1.24844397,
                               0.03106556])
        left_legend= r'$0.25 \leq [\alpha/\mathrm{Fe}] < 0.35$'
        params2= None
    elif options.metal.lower() == 'arichrich':
        model1= _TwoDblExpDensity
        params1= numpy.array([-0.26808571,
                               -0.19104086,
                               0.63738051,
                               0.71367505,
                               0.02827808])
        params2= None
        left_legend= r'$0.35 \leq [\alpha/\mathrm{Fe}] < 0.45$'
    #Legend
    right_legend= None
    if options.all:
        if options.type == 'z':
            right_legend= r'$h_z = %i\ \mathrm{pc}$' % (1000.*numpy.exp(params1[0]))
        else:
            right_legend= r'$h_R = %.1f\ \mathrm{kpc}$' % numpy.exp(params1[2])
    #Load sf
    sf= segueSelect.segueSelect(sample=options.sample,sn=True,
                                type_bright='tanhrcut',
                                type_faint='tanhrcut')
    if options.metal.lower() == 'rich':
        feh= -0.15
        fehrange= _APOORFEHRANGE
    elif options.metal.lower() == 'poor':
        feh= -0.65
        fehrange= _ARICHFEHRANGE
    elif options.metal.lower() == 'richdiag' \
             or options.metal.lower() == 'richlowerdiag':
        feh= -0.15
        fehrange= _APOORFEHRANGE
    elif options.metal.lower() == 'poorpoor':
        feh= -0.7
        fehrange= [_ARICHFEHRANGE[0],-0.7]
    elif options.metal.lower() == 'poorrich':
        feh= -0.7
        fehrange= [-0.7,_ARICHFEHRANGE[1]]
    elif options.metal.lower() == 'richpoor':
        feh= -0.35
        fehrange= [-0.6,_APOORFEHRANGE[0]]
    elif options.metal.lower() == 'richrich':
        feh= -0.2
        fehrange= _APOORFEHRANGE
    elif options.metal.lower() == 'richpoorest':
        feh= -0.7
        fehrange= [-1.5,-0.6]
    elif options.metal.lower() == 'apoorpoor' or options.metal.lower() == 'apoorrich':
        feh= -0.15
        fehrange= _APOORFEHRANGE
    elif options.metal.lower() == 'arichpoor' or options.metal.lower() == 'arichrich':
        feh= -0.65
        fehrange= _ARICHFEHRANGE
    else:
        feh= -0.5 
        fehrange= [-1.5,0.5]
    #Load data
    XYZ,vxvyvz,cov_vxvyvz,data= readData(metal=options.metal,select=options.select,
                                         sample=options.sample)
    #Cut out bright stars on faint plates and vice versa
    indx= []
    nfaintbright, nbrightfaint= 0, 0
    for ii in range(len(data.feh)):
        if sf.platebright[str(data[ii].plate)] and data[ii].dered_r >= 17.8:
            indx.append(False)
            nbrightfaint+= 1
        elif not sf.platebright[str(data[ii].plate)] and data[ii].dered_r < 17.8:
            indx.append(False)
            nfaintbright+= 1
        else:
            indx.append(True)
    print nbrightfaint, nfaintbright
    indx= numpy.array(indx,dtype='bool')
    data= data[indx]
    XYZ= XYZ[indx,:]
    vxvyvz= vxvyvz[indx,:]
    cov_vxvyvz= cov_vxvyvz[indx,:]
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
        rmax= 19.5 #SF cuts off here
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
        rmax= 19.
    #Load model distributions
    #FeH
    fehdist= DistSpline(*numpy.histogram(data.feh,bins=11,range=fehrange),
                         xrange=fehrange)
    #Color
    cdist= DistSpline(*numpy.histogram(data.dered_g-data.dered_r,
                                       bins=9,range=colorrange),
                       xrange=colorrange)
    #Ranges
    if options.type == 'z':
        xrange= [-0.1,5.]
    elif options.type == 'R':
        xrange= [4.8,14.2]
    elif options.type == 'r':
        xrange= [14.2,20.1]
    #We do bright/faint for 4 directions and all, all bright, all faint
    ls= [180,180,45,45]
    bs= [0,90,-23,23]
    bins= 21
    #Set up comparison
    if options.type == 'r':
        compare_func= compareDataModel.comparerdistPlate
    elif options.type == 'z':
        compare_func= compareDataModel.comparezdistPlate
    elif options.type == 'R':
        compare_func= compareDataModel.compareRdistPlate
    #all, faint, bright
    if options.metal.lower() == 'poor':
        bins= [31,31,31]
    elif options.metal.lower() == 'rich':
        bins= [51,31,31]
    else:
        bins= [31,31,31]
    plates= ['all','bright','faint']
    for ii in range(len(plates)):
        plate= plates[ii]
        if plate == 'all':
            thisleft_legend= left_legend
            thisright_legend= right_legend
        else:
            thisleft_legend= None
            thisright_legend= None
        bovy_plot.bovy_print()
        compare_func(model1,params1,sf,cdist,fehdist,
                     data,plate,color='k',
                     rmin=14.5,rmax=rmax,
                     grmin=colorrange[0],
                     grmax=colorrange[1],
                     fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                     xrange=xrange,
                     bins=bins[ii],ls='-',left_legend=thisleft_legend,
                     right_legend=thisright_legend)
        if not params2 is None:
            compare_func(model2,params2,sf,cdist,fehdist,
                         data,plate,color='k',bins=bins[ii],
                         rmin=14.5,rmax=rmax,
                         grmin=colorrange[0],
                         grmax=colorrange[1],
                         fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,cdist,fehdist,
                         data,plate,color='k',bins=bins[ii],
                         rmin=14.5,rmax=rmax,
                         grmin=colorrange[0],
                         grmax=colorrange[1],
                         fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(os.path.join(args[0],'model_data_g_'+options.metal+'_'+plate+'.'+ext))
        else:
            bovy_plot.bovy_end_print(os.path.join(args[0],'model_data_g_'+options.metal+'_'+options.type+'dist_'+plate+'.'+ext))
        if options.all: return None
    bins= 16
    for ii in range(len(ls)):
        #Bright
        plate= compareDataModel.similarPlatesDirection(ls[ii],bs[ii],20.,
                                                       sf,data,
                                                       faint=False)
        bovy_plot.bovy_print()
        compare_func(model1,params1,sf,cdist,fehdist,
                     data,plate,color='k',
                     rmin=14.5,rmax=rmax,
                     grmin=colorrange[0],
                     grmax=colorrange[1],
                     fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                     xrange=xrange,
                     bins=bins,ls='-')
        if not params2 is None:
            compare_func(model2,params2,sf,cdist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,
                         grmin=colorrange[0],
                         grmax=colorrange[1],
                         fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,cdist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,
                         grmin=colorrange[0],
                         grmax=colorrange[1],
                         fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(os.path.join(args[0],'model_data_g_'+options.metal+'_l%i_b%i_bright.' % (ls[ii],bs[ii]))+ext)
        else:
            bovy_plot.bovy_end_print(os.path.join(args[0],'model_data_g_'+options.metal+'_'+options.type+'dist_l%i_b%i_bright.' % (ls[ii],bs[ii]))+ext)
        #Faint
        plate= compareDataModel.similarPlatesDirection(ls[ii],bs[ii],20.,
                                                       sf,data,
                                                       bright=False)
        bovy_plot.bovy_print()
        compare_func(model1,params1,sf,cdist,fehdist,
                     data,plate,color='k',
                     rmin=14.5,rmax=rmax,
                     grmin=colorrange[0],
                     grmax=colorrange[1],
                     fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                     xrange=xrange,
                     bins=bins,ls='-')
        if not params2 is None:
            compare_func(model2,params2,sf,cdist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,grmin=colorrange[0],
                         grmax=colorrange[1],
                         fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                         xrange=xrange,
                         overplot=True,ls='--')
        if not params3 is None:
            compare_func(model3,params3,sf,cdist,fehdist,
                         data,plate,color='k',bins=bins,
                         rmin=14.5,rmax=rmax,grmin=colorrange[0],
                         grmax=colorrange[1],
                         fehmin=fehrange[0],fehmax=fehrange[1],feh=feh,
                         xrange=xrange,
                         overplot=True,ls=':')
        if options.type == 'r':
            bovy_plot.bovy_end_print(os.path.join(args[0],'model_data_g_'+options.metal+'_l%i_b%i_faint.' % (ls[ii],bs[ii]))+ext)
        else:
            bovy_plot.bovy_end_print(os.path.join(args[0],'model_data_g_'+options.metal+'_'+options.type+'dist_l%i_b%i_faint.' % (ls[ii],bs[ii]))+ext)
    return None