コード例 #1
0
ファイル: predictBellHalo.py プロジェクト: jobovy/segue-maps
def predictBellHalo():
    params= None
    data= read_gdwarfs(ebv=True,sn=True)
    plates= numpy.array(list(set(list(data.plate))),dtype='int') #Only load plates that we use
    sf= segueSelect(plates=plates,sample='G',type_bright='tanhrcut',
                    type_faint='tanhrcut',sn=True)
    cdist= _const_colordist
    fehdist= haloMDF
    n,d,x= compareDataModel.comparernumberPlate(bellfunc,params,sf,cdist,fehdist,data,'all',fehmin=-1.8,fehmax=-0.8,feh=-2.,noplot=True)
    #Normalization of bell
    bell= 10**8./(integrate.dblquad(lambda r,f: numpy.sin(f)*r**2*bellfunc(r*numpy.sin(f),r*numpy.cos(f),None),
                                    0.,numpy.pi,lambda x:1., lambda x: 40.)[0]*2.*numpy.pi)
    return numpy.sum(n)*7.*(numpy.pi/180.)**2.*(20.2-14.5)/1000*bell*0.2*numpy.log(10.) #these are some factors left out of compareDataModel
コード例 #2
0
ファイル: calcMass.py プロジェクト: jobovy/segue-maps
def calcMass(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        elif options.select.lower() == 'fakebimodal':
            raw= read_gdwarfs(_FAKEBIMODALGDWARFFILE,
                              logg=True,ebv=True,sn=True)
            options.select= 'all'
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        mass= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        mass= []
        ii, jj= 0, 0
    #parameters
    if os.path.exists(args[1]):#Load initial
        savefile= open(args[1],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    else:
        print "Error: must provide parameters of best fits"
        print "Returning ..."
        return None
    #Sample?
    if options.mcsample:
        if ii < len(binned.fehedges)-1 and jj < len(binned.afeedges)-1:
            print "First do all of the best-fit mass estimates ..."
            print "Returning ..."
            return None
        if os.path.exists(args[2]): #Load savefile
            savefile= open(args[2],'rb')
            masssamples= pickle.load(savefile)
            ii= pickle.load(savefile)
            jj= pickle.load(savefile)
            savefile.close()
        else:
            masssamples= []
            ii, jj= 0, 0
        if os.path.exists(args[3]): #Load savefile
            savefile= open(args[3],'rb')
            denssamples= pickle.load(savefile)
            savefile.close()
        else:
            print "If mcsample you need to provide the file with the density samples ..."
            print "Returning ..."
            return None
    #Set up model etc.
    if options.model.lower() == 'hwr':
        densfunc= _HWRDensity
    elif options.model.lower() == 'twodblexp':
        densfunc= _TwoDblExpDensity
    like_func= _HWRLikeMinus
    pdf_func= _HWRLike
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
    #Load selection function
    plates= numpy.array(list(set(list(raw.plate))),dtype='int') #Only load plates that we use
    print "Using %i plates, %i stars ..." %(len(plates),len(raw))
    sf= segueSelect(plates=plates,type_faint='tanhrcut',
                    sample=options.sample,type_bright='tanhrcut',
                    sn=True,select=options.select)
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    indx= [not 'faint' in name for name in sf.platestr.programname]
    platebright= numpy.array(indx,dtype='bool')
    indx= ['faint' in name for name in sf.platestr.programname]
    platefaint= numpy.array(indx,dtype='bool')
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.5, 20.2
    #Run through the bins
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                if options.mcsample: masssamples.append(None)
                else: mass.append(None)
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            print binned.feh(ii), binned.afe(jj), len(data)
            fehindx= binned.fehindx(binned.feh(ii))
            afeindx= binned.afeindx(binned.afe(jj))
            #set up feh and color
            feh= binned.feh(ii)
            fehrange= [binned.fehedges[ii],binned.fehedges[ii+1]]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            
            #Age marginalization
            afe= binned.afe(jj)
            if options.simpleage:
                agemin, agemax= 0.5, 10.
            else:
                if afe > 0.25: agemin, agemax= 7.,10.
                else: agemin,agemax= 1.,8.
            if options.mcsample:
                #Loop over samples
                thissamples= denssamples[afeindx+fehindx*binned.npixafe()]
                if options.nsamples < len(thissamples):
                    print "Taking random ..."
                    #Random permutation
                    thissamples= numpy.random.permutation(thissamples)[0:options.nsamples]
                thismasssamples= []
                print "WARNING: DISK MASS IN CALCMASS ONLY FOR G COLORS"
                for kk in range(len(thissamples)):
                    thisparams= thissamples[kk]
                    thismasssamples.append(predictDiskMass(densfunc,
                                                           thisparams,sf,
                                                           colordist,fehdist,
                                                           fehrange[0],
                                                           fehrange[1],feh,
                                                           data,0.45,
                                                           0.58,
                                                           agemin,agemax,
                                                           normalize=options.normalize,
                                                           imfmodel=options.imfmodel))
                #Print some stuff
                print numpy.mean(numpy.array(thismasssamples)), numpy.std(numpy.array(thismasssamples))
                masssamples.append(thismasssamples)
            else:
                thisparams= fits[afeindx+fehindx*binned.npixafe()]
                print "WARNING: DISK MASS IN CALCMASS ONLY FOR G COLORS"
                mass.append(predictDiskMass(densfunc,
                                            thisparams,sf,
                                            colordist,fehdist,
                                            fehrange[0],
                                            fehrange[1],feh,
                                            data,0.45,
                                            0.58,
                                            agemin,agemax,
                                            normalize=options.normalize,
                                            imfmodel=options.imfmodel))
                print mass[-1]
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
            if options.mcsample: save_pickles(args[2],masssamples,ii,jj)
            else: save_pickles(args[0],mass,ii,jj)
            if jj == 0: #this means we've reset the counter 
                break
    if options.mcsample: save_pickles(args[2],masssamples,ii,jj)
    else: save_pickles(args[0],mass,ii,jj)
    return None
コード例 #3
0
ファイル: fakeBimodalData.py プロジェクト: jobovy/segue-maps
def resampleMags(raw,comps,options,args):
    #For each data point's line-of-sight and color and feh 
    #calculate the "thin" and "thick" distributions
    model_thick= _DblExpDensity
    model_thin= _DblExpDensity
    params_thick= numpy.array([numpy.log(options.hz_thick/1000.),
                               -numpy.log(options.hr_thick)])
    params_thin= numpy.array([numpy.log(options.hz_thin/1000.),
                              -numpy.log(options.hr_thin)])
    if options.allthin:
        params_thick= params_thin
    elif options.allthick:
        params_thin= params_thick 
   #Load sf
    sf= segueSelect(sample=options.sample,sn=True,
                    type_bright='tanhrcut',
                    type_faint='tanhrcut')
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    #Cut out bright stars on faint plates and vice versa
    cutbright= False
    if cutbright:
        indx= []
        for ii in range(len(raw.feh)):
            if sf.platebright[str(raw[ii].plate)] and raw[ii].dered_r >= 17.8:
                indx.append(False)
            elif not sf.platebright[str(raw[ii].plate)] and raw[ii].dered_r < 17.8:
                indx.append(False)
            else:
                indx.append(True)
        indx= numpy.array(indx,dtype='bool')
        raw= raw[indx]
        comps= comps[indx]
    #Loadthe data into the pixelAfeFeh structure
    raw= _append_field_recarray(raw,'comps',comps)
    binned= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05,fehmin=-1.6,
                        fehmax=0.5,afemin=-0.05,afemax=0.55)
    #Color
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
        rmax= 20.2
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
        rmax= 19.
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.5, 20.2
    ngr, nfeh, nrs= 2, 2, 201
    grs= numpy.linspace(grmin,grmax,ngr)
    rs= numpy.linspace(rmin,rmax,nrs)
    #Run through the bins
    ii, jj= 0, 0
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            rawIndx= binned.callIndx(binned.feh(ii),binned.afe(jj))
            if len(data) < 1:
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            #Set up feh and color
            feh= binned.feh(ii)
            fehrange= [binned.fehedges[ii],binned.fehedges[ii+1]]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            #Predict the r-distribution for all plates
            #Thick or thin?
            thick_amp= numpy.mean(data.comps)
            rdists_thin= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
            rdists_thick= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
            for pp in range(len(sf.plates)):
                sys.stdout.write('\r'+"Working on bin %i / %i: plate %i / %i" \
                                     % (ii*(len(binned.afeedges)-1)+jj+1,
                                        (len(binned.afeedges)-1)*(len(binned.fehedges)-1),pp+1,len(sf.plates))+'\r')
                sys.stdout.flush()
                rdists_thin[pp,:,:,:]= _predict_rdist_plate(rs,model_thin,
                                                            params_thin,
                                                            rmin,rmax,
                                                            platelb[pp,0],platelb[pp,1],
                                                            grmin,grmax,
                                                            fehrange[0],fehrange[1],feh,
                                                            colordist,
                                                            fehdist,sf,sf.plates[pp],
                                                            dontmarginalizecolorfeh=True,
                                                            ngr=ngr,nfeh=nfeh)
            
                rdists_thick[pp,:,:,:]= _predict_rdist_plate(rs,model_thick,
                                                             params_thick,
                                                             rmin,rmax,
                                                             platelb[pp,0],platelb[pp,1],
                                                             grmin,grmax,
                                                             fehrange[0],fehrange[1],feh,
                                                             colordist,
                                                             fehdist,sf,sf.plates[pp],
                                                             dontmarginalizecolorfeh=True,
                                                             ngr=ngr,nfeh=nfeh)
            rdists= thick_amp*rdists_thick+(1.-thick_amp)*rdists_thin
            rdists[numpy.isnan(rdists)]= 0.
            numbers= numpy.sum(rdists,axis=3)
            numbers= numpy.sum(numbers,axis=2)
            numbers= numpy.sum(numbers,axis=1)
            numbers= numpy.cumsum(numbers)
            numbers/= numbers[-1]
            rdists= numpy.cumsum(rdists,axis=1)
            for ww in range(len(sf.plates)):
                for ll in range(ngr):
                    for kk in range(nfeh):
                        if rdists[ww,-1,ll,kk] != 0.:
                            rdists[ww,:,ll,kk]/= rdists[ww,-1,ll,kk]
            #Now sample
            nout= 0
            while nout < len(data):
                #First sample a plate
                ran= numpy.random.uniform()
                kk= 0
                while numbers[kk] < ran: kk+= 1
                #plate==kk; now sample from the rdist of this plate
                ran= numpy.random.uniform()
                ll= 0
                #Find cc and ff for this data point
                cc= int(numpy.floor((data[nout].dered_g-data[nout].dered_r-colorrange[0])/(colorrange[1]-colorrange[0])*ngr))
                ff= int(numpy.floor((data[nout].feh-fehrange[0])/(fehrange[1]-fehrange[0])*nfeh))
                while rdists[kk,ll,cc,ff] < ran and ll < nrs-1: ll+= 1
                #r=ll
                oldgr= data.dered_g[nout]-data.dered_r[nout]
                oldr= data.dered_r[nout]
                data.dered_r[nout]= rs[ll]
                data.dered_g[nout]= oldgr+data.dered_r[nout]
                #Also change plate and l and b
                data.plate[nout]= sf.plates[kk]
                data.ra[nout]= sf.platestr.ra[kk]
                data.dec[nout]= sf.platestr.dec[kk]
                data.l[nout]= platelb[kk,0]
                data.b[nout]= platelb[kk,1]
                nout+= 1
            raw.dered_r[rawIndx]= data.dered_r
            raw.dered_g[rawIndx]= data.dered_g
            raw.plate[rawIndx]= data.plate
            raw.ra[rawIndx]= data.ra
            raw.dec[rawIndx]= data.dec
            raw.l[rawIndx]= data.l
            raw.b[rawIndx]= data.b
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    #Dump raw
    fitsio.write(args[0],raw,clobber=True)
コード例 #4
0
ファイル: fakeDFData.py プロジェクト: jobovy/segue-maps
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
コード例 #5
0
ファイル: fakeDensData.py プロジェクト: jobovy/segue-maps
def fakeDensData(parser):
    numpy.random.seed(1)
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    #Set up density model
    if options.model.lower() == 'hwr':
        densfunc= _HWRDensity
        if options.metal.lower() == 'rich':
            params= numpy.array([-1.34316986e+00,1.75402412e+00,5.14667706e-04])
        else:
            params= numpy.array([-0.3508148171668,0.65752,0.00206572947631])
    elif options.model.lower() == 'flare':
        densfunc= _FlareDensity
        if options.metal.lower() == 'rich':
            params= numpy.log(numpy.array([0.3,2.5,2.5]))
        else:
            params= numpy.log(numpy.array([0.3,2.5,2.5]))
    elif options.model.lower() == 'tiedflare':
        densfunc= _TiedFlareDensity
        if options.metal.lower() == 'rich':
            params= numpy.log(numpy.array([0.3,2.5]))
        else:
            params= numpy.log(numpy.array([0.3,2.5]))
    elif options.model.lower() == 'twovertical':
        densfunc= _TwoVerticalDensity
        if options.metal.lower() == 'rich':
            params= numpy.log(numpy.array([0.3,0.8,2.5,1.05]))
        else:
            params= numpy.log(numpy.array([0.3,0.8,2.5,1.05]))
    #Data
    XYZ,vxvyvz,cov_vxvyvz,rawdata= readData(metal=options.metal,
                                            sample=options.sample)
    if options.metal.lower() == 'rich':
        feh= -0.15
        fehrange= [-0.4,0.5]
    elif options.metal.lower() == 'poor':
        feh= -0.65
        fehrange= [-1.5,-0.5]
    else:
        feh= -0.5 
    #Load model distributions
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
    #FeH
    fehdist= DistSpline(*numpy.histogram(rawdata.feh,bins=11,range=fehrange),
                         xrange=fehrange)
    #Color
    colordist= DistSpline(*numpy.histogram(rawdata.dered_g-rawdata.dered_r,
                                           bins=9,range=colorrange),
                           xrange=colorrange)
    #Load selection function
    sf= segueSelect.segueSelect(type_bright=options.sel_bright,
                                type_faint=options.sel_faint,
                                sample=options.sample)
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    if options.sample.lower() == 'g':
        rmin, rmax= 14.5, 20.2
        grmin, grmax= 0.48, 0.55
    elif options.sample.lower() == 'k':
        rmin, rmax= 14.5, 19.
        grmin, grmax= 0.55, 0.75
    #Calculate the r-distribution for each plate
    nrs= 1001
    ngr, nfeh= 21, 21
    grs= numpy.linspace(grmin,grmax,ngr)
    fehs= numpy.linspace(fehrange[0],fehrange[1],nfeh)
    #Calcuate FeH and gr distriutions
    fehdists= numpy.zeros(nfeh)
    for ii in range(nfeh): fehdists[ii]= fehdist(fehs[ii])
    fehdists= numpy.cumsum(fehdists)
    fehdists/= fehdists[-1]
    colordists= numpy.zeros(ngr)
    for ii in range(ngr): colordists[ii]= colordist(grs[ii])
    colordists= numpy.cumsum(colordists)
    colordists/= colordists[-1]
    rs= numpy.linspace(rmin,rmax,nrs)
    rdists= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
    for ii in range(len(sf.plates)):
        p= sf.plates[ii]
        sys.stdout.write('\r'+"Working on plate %i (%i/%i)" % (p,ii+1,len(sf.plates)))
        sys.stdout.flush()
        rdists[ii,:,:,:]= _predict_rdist_plate(rs,densfunc,params,rmin,rmax,
                                               platelb[ii,0],platelb[ii,1],
                                               grmin,grmax,
                                               fehrange[0],fehrange[1],feh,
                                               colordist,
                                               fehdist,sf,sf.plates[ii],
                                               dontmarginalizecolorfeh=True,
                                               ngr=ngr,nfeh=nfeh)
    sys.stdout.write('\r'+segueSelect._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)
    numbers/= numbers[-1]
    rdists= numpy.cumsum(rdists,axis=1)
    for ii in range(len(sf.plates)):
        for jj in range(ngr):
            for kk in range(nfeh):
                rdists[ii,:,jj,kk]/= rdists[ii,-1,jj,kk]
    #Now sample until we're done
    out= []
    while len(out) < options.nsamples:
        #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
        while rdists[kk,jj,cc,ff] < ran: jj+= 1
        #r=jj
        out.append([rs[jj],grs[cc],fehs[ff],platelb[kk,0],platelb[kk,1],
                    sf.plates[kk]])
    #Save as pickle
    savefile= open(args[0],'wb')
    pickle.dump(out,savefile)
    savefile.close()
コード例 #6
0
def scatterData(options,args):
    if options.png: ext= 'png'
    else: ext= 'ps'
    #Load sf
    sf= segueSelect.segueSelect(sample=options.sample,sn=True,
                                type_bright='sharprcut',
                                type_faint='sharprcut')
    if options.fake:
        fakefile= open(options.fakefile,'rb')
        fakedata= pickle.load(fakefile)
        fakefile.close()
        #Calculate distance
        ds, ls, bs, rs, grs, fehs= [], [], [], [], [], []
        for ii in range(len(fakedata)):
            ds.append(_ivezic_dist(fakedata[ii][1],fakedata[ii][0],fakedata[ii][2]))
            ls.append(fakedata[ii][3]+(2*numpy.random.uniform()-1.)\
                          *1.49)
            bs.append(fakedata[ii][4]+(2*numpy.random.uniform()-1.)\
                          *1.49)
            rs.append(fakedata[ii][0])
            grs.append(fakedata[ii][1])
            fehs.append(fakedata[ii][2])
        ds= numpy.array(ds)
        ls= numpy.array(ls)
        bs= numpy.array(bs)
        rs= numpy.array(rs)
        grs= numpy.array(grs)
        fehs= numpy.array(fehs)
        XYZ= bovy_coords.lbd_to_XYZ(ls,bs,ds,degree=True)                      
    else:
        #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= []
        for ii in range(len(data.feh)):
            if sf.platebright[str(data[ii].plate)] and data[ii].dered_r >= 17.8:
                indx.append(False)
            elif not sf.platebright[str(data[ii].plate)] and data[ii].dered_r < 17.8:
                indx.append(False)
            else:
                indx.append(True)
        indx= numpy.array(indx,dtype='bool')
        data= data[indx]
        XYZ= XYZ[indx,:]
        vxvyvz= vxvyvz[indx,:]
        cov_vxvyvz= cov_vxvyvz[indx,:]
    R= ((8.-XYZ[:,0])**2.+XYZ[:,1]**2.)**0.5
    bovy_plot.bovy_print()
    if options.type.lower() == 'dataxy':
        bovy_plot.bovy_plot(XYZ[:,0],XYZ[:,1],'k,',
                            xlabel=r'$X\ [\mathrm{kpc}]$',
                            ylabel=r'$Y\ [\mathrm{kpc}]$',
                            xrange=[5,-5],yrange=[5,-5],
                            onedhists=True)
    elif options.type.lower() == 'datarz':
        bovy_plot.bovy_plot(R,XYZ[:,2],'k,',
                            xlabel=r'$R\ [\mathrm{kpc}]$',
                            ylabel=r'$Z\ [\mathrm{kpc}]$',
                            xrange=[5,14],
                            yrange=[-4,4],
                            onedhists=True)
    if options.fake:
        bovy_plot.bovy_end_print(os.path.join(args[0],options.type+'_'
                                              +'fake_'+
                                              options.sample+'_'+
                                              options.metal+'.'+ext))
    else:
        bovy_plot.bovy_end_print(os.path.join(args[0],options.type+'_'
                                              +options.sample+'_'+
                                              options.metal+'.'+ext))
コード例 #7
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