Esempio n. 1
0
def resampleMags(raw,comps,options,args):
    #For each data point's line-of-sight and color and feh 
    #calculate the "thin" and "thick" distributions
    model_thick= _DblExpDensity
    model_thin= _DblExpDensity
    params_thick= numpy.array([numpy.log(options.hz_thick/1000.),
                               -numpy.log(options.hr_thick)])
    params_thin= numpy.array([numpy.log(options.hz_thin/1000.),
                              -numpy.log(options.hr_thin)])
    if options.allthin:
        params_thick= params_thin
    elif options.allthick:
        params_thin= params_thick 
   #Load sf
    sf= segueSelect(sample=options.sample,sn=True,
                    type_bright='tanhrcut',
                    type_faint='tanhrcut')
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    #Cut out bright stars on faint plates and vice versa
    cutbright= False
    if cutbright:
        indx= []
        for ii in range(len(raw.feh)):
            if sf.platebright[str(raw[ii].plate)] and raw[ii].dered_r >= 17.8:
                indx.append(False)
            elif not sf.platebright[str(raw[ii].plate)] and raw[ii].dered_r < 17.8:
                indx.append(False)
            else:
                indx.append(True)
        indx= numpy.array(indx,dtype='bool')
        raw= raw[indx]
        comps= comps[indx]
    #Loadthe data into the pixelAfeFeh structure
    raw= _append_field_recarray(raw,'comps',comps)
    binned= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05,fehmin=-1.6,
                        fehmax=0.5,afemin=-0.05,afemax=0.55)
    #Color
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
        rmax= 20.2
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
        rmax= 19.
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.5, 20.2
    ngr, nfeh, nrs= 2, 2, 201
    grs= numpy.linspace(grmin,grmax,ngr)
    rs= numpy.linspace(rmin,rmax,nrs)
    #Run through the bins
    ii, jj= 0, 0
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            rawIndx= binned.callIndx(binned.feh(ii),binned.afe(jj))
            if len(data) < 1:
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            #Set up feh and color
            feh= binned.feh(ii)
            fehrange= [binned.fehedges[ii],binned.fehedges[ii+1]]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            #Predict the r-distribution for all plates
            #Thick or thin?
            thick_amp= numpy.mean(data.comps)
            rdists_thin= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
            rdists_thick= numpy.zeros((len(sf.plates),nrs,ngr,nfeh))
            for pp in range(len(sf.plates)):
                sys.stdout.write('\r'+"Working on bin %i / %i: plate %i / %i" \
                                     % (ii*(len(binned.afeedges)-1)+jj+1,
                                        (len(binned.afeedges)-1)*(len(binned.fehedges)-1),pp+1,len(sf.plates))+'\r')
                sys.stdout.flush()
                rdists_thin[pp,:,:,:]= _predict_rdist_plate(rs,model_thin,
                                                            params_thin,
                                                            rmin,rmax,
                                                            platelb[pp,0],platelb[pp,1],
                                                            grmin,grmax,
                                                            fehrange[0],fehrange[1],feh,
                                                            colordist,
                                                            fehdist,sf,sf.plates[pp],
                                                            dontmarginalizecolorfeh=True,
                                                            ngr=ngr,nfeh=nfeh)
            
                rdists_thick[pp,:,:,:]= _predict_rdist_plate(rs,model_thick,
                                                             params_thick,
                                                             rmin,rmax,
                                                             platelb[pp,0],platelb[pp,1],
                                                             grmin,grmax,
                                                             fehrange[0],fehrange[1],feh,
                                                             colordist,
                                                             fehdist,sf,sf.plates[pp],
                                                             dontmarginalizecolorfeh=True,
                                                             ngr=ngr,nfeh=nfeh)
            rdists= thick_amp*rdists_thick+(1.-thick_amp)*rdists_thin
            rdists[numpy.isnan(rdists)]= 0.
            numbers= numpy.sum(rdists,axis=3)
            numbers= numpy.sum(numbers,axis=2)
            numbers= numpy.sum(numbers,axis=1)
            numbers= numpy.cumsum(numbers)
            numbers/= numbers[-1]
            rdists= numpy.cumsum(rdists,axis=1)
            for ww in range(len(sf.plates)):
                for ll in range(ngr):
                    for kk in range(nfeh):
                        if rdists[ww,-1,ll,kk] != 0.:
                            rdists[ww,:,ll,kk]/= rdists[ww,-1,ll,kk]
            #Now sample
            nout= 0
            while nout < len(data):
                #First sample a plate
                ran= numpy.random.uniform()
                kk= 0
                while numbers[kk] < ran: kk+= 1
                #plate==kk; now sample from the rdist of this plate
                ran= numpy.random.uniform()
                ll= 0
                #Find cc and ff for this data point
                cc= int(numpy.floor((data[nout].dered_g-data[nout].dered_r-colorrange[0])/(colorrange[1]-colorrange[0])*ngr))
                ff= int(numpy.floor((data[nout].feh-fehrange[0])/(fehrange[1]-fehrange[0])*nfeh))
                while rdists[kk,ll,cc,ff] < ran and ll < nrs-1: ll+= 1
                #r=ll
                oldgr= data.dered_g[nout]-data.dered_r[nout]
                oldr= data.dered_r[nout]
                data.dered_r[nout]= rs[ll]
                data.dered_g[nout]= oldgr+data.dered_r[nout]
                #Also change plate and l and b
                data.plate[nout]= sf.plates[kk]
                data.ra[nout]= sf.platestr.ra[kk]
                data.dec[nout]= sf.platestr.dec[kk]
                data.l[nout]= platelb[kk,0]
                data.b[nout]= platelb[kk,1]
                nout+= 1
            raw.dered_r[rawIndx]= data.dered_r
            raw.dered_g[rawIndx]= data.dered_g
            raw.plate[rawIndx]= data.plate
            raw.ra[rawIndx]= data.ra
            raw.dec[rawIndx]= data.dec
            raw.l[rawIndx]= data.l
            raw.b[rawIndx]= data.b
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    #Dump raw
    fitsio.write(args[0],raw,clobber=True)
Esempio n. 2
0
def calcOrbits(parser):
    options,args= parser.parse_args()
    #Read data
    XYZ,vxvyvz,cov_vxvyvz,rawdata= readData(metal='allall',
                                            sample=options.sample,
                                            loggmin=4.2,
                                            snmin=15.,
                                            select=options.select)
    #Define potential
    if options.logp:
        pot= LogarithmicHaloPotential(normalize=1.)
    else:
        pot= MWPotential
    ts= numpy.linspace(0.,_MAXT,10000) #times to integrate
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        orbits= pickle.load(savefile)
        _ORBITSLOADED= True
        try:
            samples= pickle.load(savefile)
        except EORError:
            _SAMPLESLOADED= False
        else:
            _SAMPLESLOADED= True
        finally:
            savefile.close()
    else:
        _ORBITSLOADED= False
    if not _ORBITSLOADED:
        #First calculate orbits
        es, rmeans, rperis, raps, zmaxs = [], [], [], [], []
        densrmeans, vzrmeans= [], []
        for ii in range(len(rawdata)):
            sys.stdout.write('\r'+"Working on object %i/%i" % (ii,len(rawdata)))
            sys.stdout.flush()
            #Integrate the orbit
            data= rawdata[ii]
            o= Orbit([data.ra,data.dec,data.dist,data.pmra,data.pmdec,data.vr],
                     radec=True,vo=220.,ro=8.,zo=_ZSUN)
            o.integrate(ts,pot)
            es.append(o.e())
            rperis.append(o.rperi())
            raps.append(o.rap())
            zmaxs.append(o.zmax())
            rmeans.append(0.5*(o.rperi()+o.rap()))
            Rs= o.R(ts)
            vz2= o.vz(ts)**2.
            dens= evaluateDensities(Rs,0.*Rs,pot)
            densrmeans.append(numpy.sum(dens*Rs)/numpy.sum(dens))
            vzrmeans.append(numpy.sum(vz2*Rs)/numpy.sum(vz2))
#            print " ", rmeans[-1], densrmeans[-1], vzrmeans[-1]
        sys.stdout.write('\r'+_ERASESTR+'\r')
        sys.stdout.flush()
        es= numpy.array(es)
        rmeans= numpy.array(rmeans)
        rperis= numpy.array(rperis)
        raps= numpy.array(raps)
        zmaxs= numpy.array(zmaxs)
        orbits= _append_field_recarray(rawdata,'e',es)
        orbits= _append_field_recarray(orbits,'rmean',rmeans)
        orbits= _append_field_recarray(orbits,'rperi',rperis)
        orbits= _append_field_recarray(orbits,'rap',raps)
        orbits= _append_field_recarray(orbits,'zmax',zmaxs)
        orbits= _append_field_recarray(orbits,'densrmean',densrmeans)
        orbits= _append_field_recarray(orbits,'vzrmean',vzrmeans)
        #Pickle
        savefile= open(args[0],'wb')
        pickle.dump(orbits,savefile)
        savefile.close()
    return None
Esempio n. 3
0
def plotComps(options,args,comps):
    raw= readRealData(options,args)
    raw= _append_field_recarray(raw,'comps',comps)
    pix= pixelAfeFeh(raw,dfeh=0.1,dafe=0.05,fehmin=-1.6,
                     fehmax=0.5,afemin=-0.05,afemax=0.55)
    plotthis= numpy.zeros((pix.npixfeh(),pix.npixafe()))
    for ii in range(pix.npixfeh()):
        for jj in range(pix.npixafe()):
            data= pix(pix.feh(ii),pix.afe(jj))
            if len(data) < 100:
                plotthis[ii,jj]= numpy.nan
                continue
            plotthis[ii,jj]= numpy.mean(data.comps)
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg',
                          interpolation='nearest',
                          xrange=[-1.6,0.5],
                          yrange=[-0.05,0.55],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          zlabel=r'$\mathrm{fraction\ of\ stars\ in\ thick\ component}$',
#                          vmin=vmin,vmax=vmax,
                          colorbar=True,shrink=0.78,
                          contours=False)
    #Overplot contours of the underlying components
    #Restore deconvolution
    outfile= open(options.xdfile,'rb')
    xamp= pickle.load(outfile)
    xmean= pickle.load(outfile)
    xcovar= pickle.load(outfile)
    outfile.close()
    from matplotlib import pyplot
    from matplotlib.patches import Ellipse
    eigs1= numpy.linalg.eig(xcovar[0,:,:])
    eigs2= numpy.linalg.eig(xcovar[1,:,:])
    angle1= math.atan(-eigs1[1][0,1]/eigs1[1][1,1])/numpy.pi*180.
    angle2= math.atan(-eigs2[1][0,1]/eigs2[1][1,1])/numpy.pi*180.
    thisellipse= Ellipse(xmean[0,:],2.*numpy.sqrt(eigs1[0][0]),
                         2*numpy.sqrt(eigs1[0][1]),angle1)
    ells= [thisellipse]
    ells.append(Ellipse(xmean[0,:],4.*numpy.sqrt(eigs1[0][0]),
                        4*numpy.sqrt(eigs1[0][1]),angle1))
    ells.append(Ellipse(xmean[0,:],6.*numpy.sqrt(eigs1[0][0]),
                        6*numpy.sqrt(eigs1[0][1]),angle1))
    ells.append(Ellipse(xmean[1,:],2.*numpy.sqrt(eigs2[0][0]),
                        2*numpy.sqrt(eigs2[0][1]),angle2))
    ells.append(Ellipse(xmean[1,:],4.*numpy.sqrt(eigs2[0][0]),
                        4*numpy.sqrt(eigs2[0][1]),angle2))
    ells.append(Ellipse(xmean[1,:],6.*numpy.sqrt(eigs2[0][0]),
                        6*numpy.sqrt(eigs2[0][1]),angle2))
    ax= pyplot.gca()
    xlims= ax.get_xlim()
    ylims= ax.get_ylim()
    for e in ells:
        ax.add_artist(e)
        e.set_facecolor('none')
        e.set_edgecolor('0.85')
        e.set_linestyle('dashed')
    ax.set_xlim(xlims)
    ax.set_ylim(ylims)
    bovy_plot.bovy_end_print(options.compsplotfile)