예제 #1
0
def raveRC():
    data= readRave()
    jk= data['Jmag2']-data['Kmag2']-0.17*numpy.exp(data['Av'])
    z= isodist.FEH2Z(data['[M/H]K'],zsolar=0.017)
    logg= data['loggK']
    indx= (jk < 0.8)*(jk >= 0.5)\
        *(z <= 0.06)\
        *(z <= rcmodel.jkzcut(jk,upper=True))\
        *(z >= rcmodel.jkzcut(jk))\
        *(logg >= rcmodel.loggteffcut(data['TeffK'],z,upper=False))\
        *(logg <= rcmodel.loggteffcut(data['TeffK'],z,upper=True))
    data= data[indx]
    #To allow for XY pixelization
    data= esutil.numpy_util.add_fields(data,[('RC_GALR', float),
                                             ('RC_GALPHI', float),
                                             ('RC_GALZ', float),
                                             ('VHELIO_AVG', float)])
    XYZ= bovy_coords.lbd_to_XYZ(data['GLON'],
                                data['GLAT'],
                                data['Dist'],
                                degree=True)
    R,phi,Z= bovy_coords.XYZ_to_galcencyl(XYZ[:,0],
                                          XYZ[:,1],
                                          XYZ[:,2],
                                          Xsun=8.,Zsun=0.025)
    data['RC_GALR']= R
    data['RC_GALPHI']= phi
    data['RC_GALZ']= Z   
    data['VHELIO_AVG']= data['HRV']
    return data
예제 #2
0
def write_matches(savefilename):
    apokasc= match_apokasc_saga()
    #Perform RC selection
    logg= apokasc['KASC_RG_LOGG_SCALE_2']
    teff= apokasc['TEFF']
    z= 0.017*10.**apokasc['METALS']
    jk= apokasc['J0']-apokasc['K0']
    indx= (logg >= 1.8)\
        *(logg <= 0.0018*(teff+382.5*apokasc['METALS']-4607)+2.5)\
        *(jk < 0.8)\
        *(jk >= 0.5)\
        *(z <= 0.06)\
        *(z <= rcmodel.jkzcut(jk,upper=True))\
        *(z >= rcmodel.jkzcut(jk))
    print "Found %i RC stars in APOKASC" % numpy.sum(indx)
    rcdists= numpy.zeros(len(apokasc))-1
    rcd= rcdist('../data/rcmodel_mode_jkz_ks_parsec_newlogg.sav')
    rcdists[indx]= rcd(jk[indx],z[indx],apokasc['K0'][indx])
    pindx= (rcdists > 0.)*(apokasc['DIST_SEISMO'] > 0.)
    apokasc= apokasc[pindx]
    rcdists= rcdists[pindx]
    print "Found %i RC stars in APOKASC with seismic distances" % numpy.sum(pindx)
    savefile= open(savefilename,'w')
    savefile.write('#ID,RCDIST(pc),SEISMODIST(SCALE,MO,pc),(SEISMODIST-RCDIST)/RCDIST\n')
    csvwriter = csv.writer(savefile, delimiter=',')
    for ii in range(len(apokasc)):
        csvwriter.writerow([apokasc['KEPLER ID'][ii],
                            rcdists[ii]*1000.,
                            apokasc['DIST_SEISMO'][ii]*1000.,
                            (apokasc['DIST_SEISMO'][ii]-rcdists[ii])/rcdists[ii]])
    savefile.close()
예제 #3
0
def plot_apogee_jkz(plotfilename,sample):
    if sample == 'disk':
        data= readData()
    elif sample == 'halo':
        data= readData(halo=True)
    elif sample == 'bulge':
        data= readData(bulge=True)
    ntotal= len(data)
    #logg cut
    data= data[(data['LOGG_AVG'] < 2.8)*(data['LOGG_AVG'] > 1.8)]
    npass= len(data)
    #Deredden
    aj= data['AK_WISE']*2.5
    ah= data['AK_WISE']*1.55
    j0= data['JMAG']-aj
    h0= data['HMAG']-ah
    k0= data['KMAG']-data['AK_WISE']
    #calculate Zs
    zsolar= 0.019
    z= isodist.FEH2Z(data['METALS_AVG'])/zsolar
    #Plot
    bovy_plot.bovy_print()
    if sample == 'bulge':
        bovy_plot.bovy_plot(j0-k0,z,'ko',
                            xrange=[0.5,0.75],
                            yrange=[0.,0.03/zsolar],
                            xlabel=r'$(J-K_s)_0$',
                            ylabel=r'$Z/Z_\odot$',ms=5.)
    else:
        bovy_plot.scatterplot(j0-k0,z,'k,',
                              xrange=[0.5,0.75],
                              yrange=[0.,0.03/zsolar],
                              xlabel=r'$(J-K_s)_0$',
                              ylabel=r'$Z/Z_\odot$',
                              bins=21)
    #Overplot cuts
    jks= numpy.linspace(0.5,0.75,1001)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks)/zsolar,
                        'k--',lw=2.,overplot=True)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks,upper=True)/zsolar,
                        'k--',lw=2.,overplot=True)
    #Data between the cuts
    indx= (j0-k0 < 0.75)*(j0-k0 > 0.5)\
                   *(z <= rcmodel.jkzcut(j0-k0,upper=True)/zsolar)\
                   *(z >= rcmodel.jkzcut(j0-k0)/zsolar)
#    j0= j0[indx]
#    h0= h0[indx]
#    k0= k0[indx]
#    z= z[indx]
#    bovy_plot.bovy_plot(j0-k0,z,'w.',
#                        overplot=True,
#                        mec='w',
#                        ms=.5)
    bovy_plot.bovy_text(r'$\mathrm{APOGEE\ ' + sample + '\ sample}$',
                        title=True)
    bovy_plot.bovy_text(r'$%i/%i/%i$' % (numpy.sum(indx),npass,ntotal),
                        bottom_right=True,size=14.)
    bovy_plot.bovy_end_print(plotfilename)
    return None                        
예제 #4
0
def indiv_calc(ii,zs,options,njks,jks,nmks,mks,logpz):
    print zs[ii]
    out= numpy.empty((2,njks,nmks))
    rc= rcmodel.rcmodel(Z=zs[ii],loggmin=1.8,loggmax='custom',
                        band=options.band,basti=options.basti,
                        imfmodel=options.imfmodel,
                        expsfh=options.expsfh,
                        parsec=options.parsec,
                        stage=options.stage)
    for jj in range(njks):
        if zs[ii] > rcmodel.jkzcut(jks[jj],upper=True) \
                or zs[ii] < rcmodel.jkzcut(jks[jj]):
            out[0,jj,:]= -numpy.finfo(numpy.dtype(numpy.float64)).max
            out[1,jj,:]= -numpy.finfo(numpy.dtype(numpy.float64)).max
            continue
        for kk in range(nmks):
            out[0,jj,kk]= logpz[ii]+rc(jks[jj],mks[kk])+numpy.log(-mks[kk])
            out[1,jj,kk]= logpz[ii]+rc(jks[jj],mks[kk])
    return out
예제 #5
0
def plot_vs_jkz(parser):
    options,args= parser.parse_args()
    if options.basti:
        zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04])
    elif options.parsec:
        zs= numpy.arange(0.0005,0.06005,0.0005)
    else:
        zs= numpy.arange(0.0005,0.03005,0.0005)
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        plotthis= pickle.load(savefile)
        jks= pickle.load(savefile)
        zs= pickle.load(savefile)
        savefile.close()
    else:
        njks= 101
        jks= numpy.linspace(0.5,0.8,njks)
        plotthis= numpy.zeros((njks,len(zs)))
        funcargs= (zs,options,njks,jks)
        multOut= multi.parallel_map((lambda x: indiv_calc(x,
                                                          *funcargs)),
                                    range(len(zs)),
                                    numcores=numpy.amin([64,len(zs),
                                                         multiprocessing.cpu_count()]))
        for ii in range(len(zs)):
            plotthis[:,ii]= multOut[ii]
        #Save
        save_pickles(args[0],plotthis,jks,zs)
    #Plot
    if options.type == 'sig':
        if options.band.lower() == 'age':
            if options.relative:
                raise NotImplementedError("relative age not implemented yet")
            else:
                vmin, vmax= 0.,.5
                zlabel= r'$\mathrm{FWHM} / 2\sqrt{2\,\ln 2}$'
        else:
            if options.relative:
                vmin, vmax= 0.8,1.2
                zlabel= r'$\mathrm{FWHM}/\mathrm{FWHM}_{\mathrm{fiducial}}$'
            else:
                vmin, vmax= 0., 0.4
                zlabel= r'$\mathrm{FWHM} / 2\sqrt{2\,\ln 2}$'
    elif options.type == 'mode':
        if options.band.lower() == 'age':
            if options.relative:
                raise NotImplementedError("relative age not implemented yet")
            else:
                vmin, vmax= 0.,1.
                zlabel= r'$\Delta\displaystyle\arg\!\max_{\substack{\log_{10}\mathrm{Age}}}{p(\log_{10}\mathrm{Age}|[J-K_s]_0)}$'
        else:
            if options.relative:
                vmin, vmax= -0.05,0.05
                zlabel= r'$\Delta\displaystyle\arg\!\max_{\substack{K_s}}{p(M_{K_s}|[J-K_s]_0)}$'
            else:
                vmin, vmax= -1.8, -1.5
                if options.band.lower() == 'h':
                    zlabel= r'$\displaystyle\arg\!\max_{\substack{H}}{p(M_{H}|[J-K_s]_0)}$'
                else:
                    zlabel= r'$\displaystyle\arg\!\max_{\substack{K_s}}{p(M_{K_s}|[J-K_s]_0)}$'
    if options.basti:#Remap the Zs
        zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04])
        regularzs= numpy.arange(0.0005,0.04005,0.0005)
        njks= len(jks)
        regularplotthis= numpy.zeros((njks,len(regularzs)))
        for jj in range(len(regularzs)):
            #Find z
            thisindx= numpy.argmin(numpy.fabs(regularzs[jj]-zs))
            for ii in range(njks):
                regularplotthis[ii,jj]= plotthis[ii,thisindx]
        zs= regularzs
        plotthis= regularplotthis
    if options.relative and os.path.exists(options.infilename):
        savefile= open(options.infilename,'rb')
        plotthisrel= pickle.load(savefile)
        savefile.close()
        if options.basti:
            plotthisrel= plotthisrel[:,:80]
        elif not options.parsec:
            plotthisrel= plotthisrel[:,:60]
        if options.type == 'mode':
            plotthis-= plotthisrel
        elif options.type == 'sig':
            plotthis/= plotthisrel
    bovy_plot.bovy_print()
    if options.type == 'sig':
        plotthis[numpy.isnan(plotthis)]= vmax
    if options.relative:
        #Only plot between the cuts
        for ii in range(plotthis.shape[0]):
            indx= zs >= rcmodel.jkzcut(jks[ii],upper=True)
            indx+= zs <= rcmodel.jkzcut(jks[ii],upper=False)
            plotthis[ii,indx]= numpy.nan
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          xrange=[jks[0],jks[-1]],
                          yrange=[zs[0],zs[-1]],
                          vmin=vmin,vmax=vmax,
                          xlabel=r'$(J-K_s)_0$',
                          ylabel=r'$Z$',
                          interpolation='nearest',
                          colorbar=True,
                          shrink=0.78,
                          zlabel=zlabel)
    #Overplot cuts
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks),
                        'w--',lw=2.,overplot=True)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks,upper=True),
                        'w--',lw=2.,overplot=True)
    if options.basti:
        pyplot.annotate(r'$\mathrm{BaSTI}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif not options.parsec:
        pyplot.annotate(r'$\mathrm{Padova}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif options.imfmodel == 'kroupa2003':
        pyplot.annotate(r'$\mathrm{Kroupa\ (2003)\ IMF}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif 'expsfh' in args[0]:
        pyplot.annotate(r'$\mathrm{p(\mathrm{Age}) \propto e^{\mathrm{Age}/(8\,\mathrm{Gyr})}}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif not options.eta is None:
        pyplot.annotate(r'$\eta_{\mathrm{Reimers}} = %.1f$' % options.eta,
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif False:
        pyplot.annotate(r'$\mathrm{Padova}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
예제 #6
0
def compare_seismic_distances(plotfilename):
    apokasc= match_apokasc_saga()
    #Perform RC selection
    logg= apokasc['KASC_RG_LOGG_SCALE_2']
    teff= apokasc['TEFF']
    z= 0.017*10.**apokasc['METALS']
    jk= apokasc['J0']-apokasc['K0']
    indx= (logg >= 1.8)\
        *(logg <= 0.0018*(teff+382.5*apokasc['METALS']-4607)+2.5)\
        *(jk < 0.8)\
        *(jk >= 0.5)\
        *(z <= 0.06)\
        *(z <= rcmodel.jkzcut(jk,upper=True))\
        *(z >= rcmodel.jkzcut(jk))#\
        #*(apokasc['SEISMO EVOL'] == 'CLUMP')
    print "Found %i RC stars in APOKASC" % numpy.sum(indx)
    rcdists= numpy.zeros(len(apokasc))-1
    rcd= rcdist('../data/rcmodel_mode_jkz_ks_parsec_newlogg.sav')
    rcdists[indx]= rcd(jk[indx],z[indx],apokasc['K0'][indx])
    pindx= (rcdists > 0.)*(apokasc['DIST_SEISMO'] > 0.)
    print "Found %i RC stars in APOKASC with seismic distances" % numpy.sum(pindx)
    #Setup plot
    bovy_plot.bovy_print(fig_height=7.)
    dx= 0.6
    left, bottom, width, height= 0.1, 0.9-dx, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,20.],[0.,20.],'k-',lw=2.,color='0.4',
                        overplot=True,zorder=0)
    bovy_plot.bovy_plot(rcdists[pindx],apokasc['DIST_SEISMO'][pindx],
                        'k.',overplot=True,zorder=10)
    if False:
        pyplot.errorbar(rcdists[pindx],
                        apokasc['DIST_SEISMO'][pindx],
                        xerr=0.05*rcdists[pindx],
                        yerr=apokasc['E_DIST_SEISMO'][pindx],
                        marker=',',color='k',
                        linestyle='none')
    thisax= pyplot.gca()
    thisax.set_ylim(0.,5.)
    pyplot.xlim(0.,5.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    bovy_plot._add_ticks()
    pyplot.ylabel(r'$\mathrm{seismic\ distance}\,(\mathrm{kpc})$')
    #Second plot
    left, bottom, width, height= 0.1, 0.1, 0.8, 0.8-dx
    thisax= pyplot.axes([left,bottom,width,height])
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,20.],[0.,0.],'k-',lw=2.,color='0.4',
                        overplot=True,zorder=0)
    bovy_plot.bovy_plot(rcdists[pindx],
                        (apokasc['DIST_SEISMO'][pindx]-rcdists[pindx])/rcdists[pindx],
                        'k.',overplot=True,zorder=10)
    thisax= pyplot.gca()
    thisax.set_ylim(-0.2,0.2)
    pyplot.xlim(0.,5.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    bovy_plot._add_ticks()
    pyplot.ylabel(r'$\mathrm{relative\ differene}$')
    pyplot.xlabel(r'$\mathrm{RC\ distance}\,(\mathrm{kpc})$')
    medoffset= numpy.median((apokasc['DIST_SEISMO'][pindx]-rcdists[pindx])/rcdists[pindx])
    medsig= 1.4826*numpy.median(numpy.fabs((apokasc['DIST_SEISMO'][pindx]-rcdists[pindx])/rcdists[pindx]-medoffset))
    bovy_plot.bovy_text(2.75,-0.125,r'$\mathrm{diff} = %.3f\pm%.3f$' % \
                            (medoffset,medsig),size=14.)
    bovy_plot.bovy_end_print(plotfilename)
예제 #7
0
def _calc_one(z, options, nages, lages, dlages):
    print z
    if options.allapogee or options.redapogee:
        rc = rcmodel.rcmodel(
            Z=z,
            loggmax=3.5,
            band=options.band,
            basti=options.basti,
            imfmodel=options.imfmodel,
            parsec=options.parsec,
            eta=options.eta,
        )
    else:
        rc = rcmodel.rcmodel(
            Z=z,
            loggmin=1.8,
            loggmax="custom",
            band=options.band,
            basti=options.basti,
            imfmodel=options.imfmodel,
            parsec=options.parsec,
            eta=options.eta,
        )
    out = numpy.zeros(nages)
    for jj in range(nages):
        jk = rc._jks
        aindx = (rc._lages <= lages[jj] + dlages) * (rc._lages > lages[jj] - dlages)
        if options.allapogee:
            aindx *= jk > 0.5
        elif options.redapogee:
            aindx *= jk > 0.8
        else:
            rcd = rcmodel.rcdist("../../rcdist-apogee/data/rcmodel_mode_jkz_ks_parsec_newlogg.sav")
            predH = numpy.array([rcd(j, z) for j in jk])
            predH = numpy.reshape(predH, len(jk))
            aindx *= (
                (jk < 0.8)
                * (jk > 0.5)
                * (z <= rcmodel.jkzcut(jk, upper=True))
                * (z >= rcmodel.jkzcut(jk))
                * (z <= 0.06)
                * (rc._sample[:, 1] > (predH - 0.4))
                * (rc._sample[:, 1] < (predH + 0.4))
                * (rc._sample[:, 1] > -3.0)
                * (rc._loggs[:, 0] <= 3.5)
            )
        if options.type == "omega":
            try:
                out[jj] = numpy.mean(rc._massweights[aindx])
            except ValueError:
                out[jj] = numpy.nan
        elif options.type == "numfrac":
            try:
                out[jj] = numpy.mean(rc._weights[aindx])
            except ValueError:
                out[jj] = numpy.nan
        elif options.type == "mass":
            try:
                out[jj] = numpy.sum(rc._masses[aindx] * rc._weights[aindx]) / numpy.sum(rc._weights[aindx])
            except ValueError:
                out[jj] = numpy.nan
    return out
예제 #8
0
def plot_Z_jk_apokasc(parser):
    options, args = parser.parse_args()
    # Setup Zs
    if os.path.exists(args[0]):
        savefile = open(args[0], "rb")
        outhist = pickle.load(savefile)
        hists = pickle.load(savefile)
        edgess = pickle.load(savefile)
        data = pickle.load(savefile)
        savefile.close()
    else:
        if _PREDICT:
            zs = numpy.arange(0.0005, 0.06005, 0.0005)
            if _DEBUG:
                zs = numpy.arange(0.0005, 0.06005, 0.005)
            # Load the RC models for each feh individually
            rcms = []
            hists = []
            edgess = []
            for z in zs:
                print z
                trc = rcmodel.rcmodel(
                    Z=z,
                    loggmin=1.8,
                    loggmax=2.8,
                    band=options.band,
                    basti=options.basti,
                    imfmodel=options.imfmodel,
                    parsec=options.parsec,
                )
                rcms.append(trc)
                sample = numpy.vstack([trc._sample[:, 0], z * numpy.ones(trc._sample.shape[0])]).T
                weights = trc._weights
                hist, edges = numpy.histogramdd(
                    sample, weights=weights, bins=12, range=[[0.5, 0.8], [0.0, 0.06]]  # 12*(10-_DEBUG*9),
                )
                hists.append(hist)
                edgess.append(edges)
        # Load APOKASC data
        data = apread.apokasc()
        indx = (data["KASC_RG_LOGG_SCALE_2"] > 2.25) * (data["KASC_RG_LOGG_SCALE_2"] < 2.65)
        print "Using %i APOKASC objects ..." % (numpy.sum(indx))
        data = data[indx]
        if _PREDICT:
            # Stack predictions
            outhist = numpy.zeros_like(hists[0])
            for ii in range(len(hists)):
                outhist += hists[ii]
            save_pickles(args[0], outhist, hists, edgess, data)
    if _PREDICT:
        # Normalize each color
        pass
        #        for ii in range(len(outhist[:,0])):
    #            outhist[ii,:]/= numpy.nanmax(outhist[ii,:])/numpy.nanmax(outhist)
    # for ii in range(len(outhist[0,:])):
    #    outhist[:,ii]/= numpy.nanmax(outhist[:,ii])/numpy.nanmax(outhist)
    # Plot everything
    bovy_plot.bovy_print()
    if _PREDICT:
        bovy_plot.bovy_dens2d(
            outhist.T,
            origin="lower",
            cmap="gist_yarg",
            xrange=[edgess[0][0][0], edgess[0][0][-1]],
            yrange=[edgess[0][1][0], edgess[0][1][-1]],
            aspect=(edgess[0][0][-1] - edgess[0][0][0]) / float(edgess[0][1][-1] - edgess[0][1][0]),
            xlabel=r"$(J-K_s)_0\ [\mathrm{mag}]$",
            ylabel=r"$Z$",
            shrink=0.78,
            interpolation="nearest",
        )
        # Overplot APOKASC data
        # Load APOKASC data
        data = apread.apokasc()
        indx = (data["KASC_RG_LOGG_SCALE_2"] > 1.8) * (data["KASC_RG_LOGG_SCALE_2"] < 2.8)
        print "Using %i APOKASC objects ..." % (numpy.sum(indx))
        data = data[indx]
    bovy_plot.bovy_plot(
        data["J0"] - data["K0"],
        options.zsolar * 10.0 ** data["METALS"],
        c=data["KASC_RG_LOGG_SCALE_2"] - 2.45,
        s=20.0,
        edgecolors="none",
        scatter=True,
        colorbar=True,
        overplot=True,
    )
    #                        mec='none',ms=3.)
    # Overplot cuts
    jks = numpy.linspace(0.5, 0.8, 201)
    bovy_plot.bovy_plot(jks, rcmodel.jkzcut(jks), "k--", lw=2.0, overplot=True)
    bovy_plot.bovy_plot(jks, rcmodel.jkzcut(jks, upper=True), "k--", lw=2.0, overplot=True)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
예제 #9
0
def make_rcsample(parser):
    options,args= parser.parse_args()
    savefilename= options.savefilename
    if savefilename is None:
        #Create savefilename if not given
        savefilename= os.path.join(appath._APOGEE_DATA,
                                   'rcsample_'+appath._APOGEE_REDUX+'.fits')
        print "Saving to %s ..." % savefilename
    #Read the base-sample
    data= apread.allStar(adddist=_ADDHAYDENDIST,rmdups=options.rmdups)
    #Remove a bunch of fields that we do not want to keep
    data= esutil.numpy_util.remove_fields(data,
                                          ['TARGET_ID',
                                           'FILE',
                                           'AK_WISE',
                                           'SFD_EBV',
                                           'SYNTHVHELIO_AVG',
                                           'SYNTHVSCATTER',
                                           'SYNTHVERR',
                                           'SYNTHVERR_MED',
                                           'RV_TEFF',
                                           'RV_LOGG',
                                           'RV_FEH',
                                           'RV_CCFWHM',
                                           'RV_AUTOFWHM',
                                           'SYNTHSCATTER',
                                           'CHI2_THRESHOLD',
                                           'APSTAR_VERSION',
                                           'ASPCAP_VERSION',
                                           'RESULTS_VERSION',
                                           'REDUCTION_ID',
                                           'SRC_H',
                                           'PM_SRC'])
    if int(appath._APOGEE_REDUX[1:]) < 500:
        data= esutil.numpy_util.remove_fields(data,
                                              ['ELEM'])
    #Select red-clump stars
    jk= data['J0']-data['K0']
    z= isodist.FEH2Z(data['METALS'],zsolar=0.017)
    if int(appath._APOGEE_REDUX[1:]) > 600:
        from apogee.tools import paramIndx
        if False:
            #Use my custom logg calibration that's correct for the RC
            logg= (1.-0.042)*data['FPARAM'][:,paramIndx('logg')]-0.213
            lowloggindx= data['FPARAM'][:,paramIndx('logg')] < 1.
            logg[lowloggindx]= data['FPARAM'][lowloggindx,paramIndx('logg')]-0.255
            hiloggindx= data['FPARAM'][:,paramIndx('logg')] > 3.8
            logg[hiloggindx]= data['FPARAM'][hiloggindx,paramIndx('logg')]-0.3726
        else:
            #Use my custom logg calibration that's correct on average
            logg= (1.+0.03)*data['FPARAM'][:,paramIndx('logg')]-0.37
            lowloggindx= data['FPARAM'][:,paramIndx('logg')] < 1.
            logg[lowloggindx]= data['FPARAM'][lowloggindx,paramIndx('logg')]-0.34
            hiloggindx= data['FPARAM'][:,paramIndx('logg')] > 3.8
            logg[hiloggindx]= data['FPARAM'][hiloggindx,paramIndx('logg')]-0.256
    else:
        logg= data['LOGG']
    indx= (jk < 0.8)*(jk >= 0.5)\
        *(z <= 0.06)\
        *(z <= rcmodel.jkzcut(jk,upper=True))\
        *(z >= rcmodel.jkzcut(jk))\
        *(logg >= rcmodel.loggteffcut(data['TEFF'],z,upper=False))\
        *(logg <= rcmodel.loggteffcut(data['TEFF'],z,upper=True))
    data= data[indx]
    #Add more aggressive flag cut
    data= esutil.numpy_util.add_fields(data,[('ADDL_LOGG_CUT',numpy.int32)])
    data['ADDL_LOGG_CUT']= ((data['TEFF']-4800.)/1000.+2.75) > data['LOGG']
    if options.loggcut:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    print "Making catalog of %i objects ..." % len(data)
    #Add distances
    data= esutil.numpy_util.add_fields(data,[('RC_DIST', float),
                                             ('RC_DM', float),
                                             ('RC_GALR', float),
                                             ('RC_GALPHI', float),
                                             ('RC_GALZ', float)])
    rcd= rcmodel.rcdist('../../rcdist-apogee/data/rcmodel_mode_jkz_ks_parsec_newlogg.sav')
    jk= data['J0']-data['K0']
    z= isodist.FEH2Z(data['METALS'],zsolar=0.017)
    data['RC_DIST']= rcd(jk,z,appmag=data['K0'])*options.distfac
    data['RC_DM']= 5.*numpy.log10(data['RC_DIST'])+10.
    XYZ= bovy_coords.lbd_to_XYZ(data['GLON'],
                                data['GLAT'],
                                data['RC_DIST'],
                                degree=True)
    R,phi,Z= bovy_coords.XYZ_to_galcencyl(XYZ[:,0],
                                          XYZ[:,1],
                                          XYZ[:,2],
                                          Xsun=8.,Zsun=0.025)
    data['RC_GALR']= R
    data['RC_GALPHI']= phi
    data['RC_GALZ']= Z
    #Save
    fitsio.write(savefilename,data,clobber=True)
    if not options.nostat:
        #Determine statistical sample and add flag
        apo= apogee.select.apogeeSelect()
        statIndx= apo.determine_statistical(data)
        mainIndx= apread.mainIndx(data)
        data= esutil.numpy_util.add_fields(data,[('STAT',numpy.int32),
                                                 ('INVSF',float)])
        data['STAT']= 0
        data['STAT'][statIndx*mainIndx]= 1
        for ii in range(len(data)):
            if (statIndx*mainIndx)[ii]:
                data['INVSF'][ii]= 1./apo(data['LOCATION_ID'][ii],
                                          data['H'][ii])
            else:
                data['INVSF'][ii]= -1.
    if options.nopm:
        fitsio.write(savefilename,data,clobber=True)       
        return None
    #Get proper motions
    from astroquery.vizier import Vizier
    import astroquery
    from astropy import units as u
    import astropy.coordinates as coord
    pmfile= savefilename.split('.')[0]+'_pms.fits'
    if os.path.exists(pmfile):
        pmdata= fitsio.read(pmfile,1)
    else:
        pmdata= numpy.recarray(len(data),
                               formats=['f8','f8','f8','f8','f8','f8','i4'],
                               names=['RA','DEC','PMRA','PMDEC',
                                      'PMRA_ERR','PMDEC_ERR','PMMATCH'])
        rad= u.Quantity(4./3600.,u.degree)
        v= Vizier(columns=['RAJ2000','DEJ2000','pmRA','pmDE','e_pmRA','e_pmDE'])
        for ii in range(len(data)):
            #if ii > 100: break
            sys.stdout.write('\r'+"Getting pm data for point %i / %i" % (ii+1,len(data)))
            sys.stdout.flush()
            pmdata.RA[ii]= data['RA'][ii]
            pmdata.DEC[ii]= data['DEC'][ii]
            co= coord.ICRS(ra=data['RA'][ii],
                           dec=data['DEC'][ii],
                           unit=(u.degree, u.degree))
            trying= True
            while trying:
                try:
                    tab= v.query_region(co,rad,catalog='I/322') #UCAC-4 catalog
                except astroquery.exceptions.TimeoutError:
                    pass
                else:
                    trying= False
            if len(tab) == 0:
                pmdata.PMMATCH[ii]= 0
                print "Didn't find a match for %i ..." % ii
                continue
            else:
                pmdata.PMMATCH[ii]= len(tab)
                if len(tab[0]['pmRA']) > 1:
                    print "Found more than 1 match for %i ..." % ii
            try:
                pmdata.PMRA[ii]= float(tab[0]['pmRA'])
            except TypeError:
                jj= 1
                while len(tab[0]['pmRA']) > 1 and jj < 4: 
                    trad= u.Quantity((4.-jj)/3600.,u.degree)
                    trying= True
                    while trying:
                        try:
                            tab= v.query_region(co,trad,catalog='I/322') #UCAC-4 catalog
                        except astroquery.exceptions.TimeoutError:
                            pass
                        else:
                            trying= False
                    jj+= 1
                if len(tab) == 0:
                    pmdata.PMMATCH[ii]= 0
                    print "Didn't find a unambiguous match for %i ..." % ii
                    continue               
                pmdata.PMRA[ii]= float(tab[0]['pmRA'])
            pmdata.PMDEC[ii]= float(tab[0]['pmDE'])
            pmdata.PMRA_ERR[ii]= float(tab[0]['e_pmRA'])
            pmdata.PMDEC_ERR[ii]= float(tab[0]['e_pmDE'])
            if numpy.isnan(float(tab[0]['pmRA'])): pmdata.PMMATCH[ii]= 0
        sys.stdout.write('\r'+_ERASESTR+'\r')
        sys.stdout.flush()
        fitsio.write(pmfile,pmdata,clobber=True)
        #To make sure we're using the same format below
        pmdata= fitsio.read(pmfile,1)
    #Match proper motions
    try: #These already exist currently, but may not always exist
        data= esutil.numpy_util.remove_fields(data,['PMRA','PMDEC'])
    except ValueError:
        pass
    data= esutil.numpy_util.add_fields(data,[('PMRA', numpy.float),
                                             ('PMDEC', numpy.float),
                                             ('PMRA_ERR', numpy.float),
                                             ('PMDEC_ERR', numpy.float),
                                             ('PMMATCH',numpy.int32)])
    data['PMMATCH']= 0
    h=esutil.htm.HTM()
    m1,m2,d12 = h.match(pmdata['RA'],pmdata['DEC'],
                        data['RA'],data['DEC'],
                        2./3600.,maxmatch=1)
    data['PMRA'][m2]= pmdata['PMRA'][m1]
    data['PMDEC'][m2]= pmdata['PMDEC'][m1]
    data['PMRA_ERR'][m2]= pmdata['PMRA_ERR'][m1]
    data['PMDEC_ERR'][m2]= pmdata['PMDEC_ERR'][m1]
    data['PMMATCH'][m2]= pmdata['PMMATCH'][m1].astype(numpy.int32)
    pmindx= data['PMMATCH'] == 1
    data['PMRA'][True-pmindx]= -9999.99
    data['PMDEC'][True-pmindx]= -9999.99
    data['PMRA_ERR'][True-pmindx]= -9999.99
    data['PMDEC_ERR'][True-pmindx]= -9999.99
    #Calculate Galactocentric velocities
    data= esutil.numpy_util.add_fields(data,[('GALVR', numpy.float),
                                             ('GALVT', numpy.float),
                                             ('GALVZ', numpy.float)])
    lb= bovy_coords.radec_to_lb(data['RA'],data['DEC'],degree=True)
    XYZ= bovy_coords.lbd_to_XYZ(lb[:,0],lb[:,1],data['RC_DIST'],degree=True)
    pmllpmbb= bovy_coords.pmrapmdec_to_pmllpmbb(data['PMRA'],data['PMDEC'],
                                                data['RA'],data['DEC'],
                                                degree=True)
    vxvyvz= bovy_coords.vrpmllpmbb_to_vxvyvz(data['VHELIO_AVG'],
                                             pmllpmbb[:,0],
                                             pmllpmbb[:,1],
                                             lb[:,0],lb[:,1],data['RC_DIST'],
                                             degree=True)
    vR, vT, vZ= bovy_coords.vxvyvz_to_galcencyl(vxvyvz[:,0],
                                                vxvyvz[:,1],
                                                vxvyvz[:,2],
                                                8.-XYZ[:,0],
                                                XYZ[:,1],
                                                XYZ[:,2]+0.025,
                                                vsun=[-11.1,30.24*8.,7.25])#Assumes proper motion of Sgr A* and R0=8 kpc, zo= 25 pc
    data['GALVR']= vR
    data['GALVT']= vT
    data['GALVZ']= vZ
    data['GALVR'][True-pmindx]= -9999.99
    data['GALVT'][True-pmindx]= -9999.99
    data['GALVZ'][True-pmindx]= -9999.99
    #Get proper motions
    pmfile= savefilename.split('.')[0]+'_pms_ppmxl.fits'
    if os.path.exists(pmfile):
        pmdata= fitsio.read(pmfile,1)
    else:
        pmdata= numpy.recarray(len(data),
                               formats=['f8','f8','f8','f8','f8','f8','i4'],
                               names=['RA','DEC','PMRA','PMDEC',
                                      'PMRA_ERR','PMDEC_ERR','PMMATCH'])
        rad= u.Quantity(4./3600.,u.degree)
        v= Vizier(columns=['RAJ2000','DEJ2000','pmRA','pmDE','e_pmRA','e_pmDE'])
        for ii in range(len(data)):
            #if ii > 100: break
            sys.stdout.write('\r'+"Getting pm data for point %i / %i" % (ii+1,len(data)))
            sys.stdout.flush()
            pmdata.RA[ii]= data['RA'][ii]
            pmdata.DEC[ii]= data['DEC'][ii]
            co= coord.ICRS(ra=data['RA'][ii],
                           dec=data['DEC'][ii],
                           unit=(u.degree, u.degree))
            trying= True
            while trying:
                try:
                    tab= v.query_region(co,rad,catalog='I/317') #PPMXL catalog
                except astroquery.exceptions.TimeoutError:
                    pass
                else:
                    trying= False
            if len(tab) == 0:
                pmdata.PMMATCH[ii]= 0
                print "Didn't find a match for %i ..." % ii
                continue
            else:
                pmdata.PMMATCH[ii]= len(tab)
                if len(tab[0]['pmRA']) > 1:
                    pass
                    #print "Found more than 1 match for %i ..." % ii
            try:
                pmdata.PMRA[ii]= float(tab[0]['pmRA'])
            except TypeError:
                #Find nearest
                cosdists= numpy.zeros(len(tab[0]['pmRA']))
                for jj in range(len(tab[0]['pmRA'])):
                    cosdists[jj]= cos_sphere_dist(tab[0]['RAJ2000'][jj],
                                                  tab[0]['DEJ2000'][jj],
                                                  data['RA'][ii],
                                                  data['DEC'][ii])
                closest= numpy.argmax(cosdists)
                pmdata.PMRA[ii]= float(tab[0]['pmRA'][closest])
                pmdata.PMDEC[ii]= float(tab[0]['pmDE'][closest])
                pmdata.PMRA_ERR[ii]= float(tab[0]['e_pmRA'][closest])
                pmdata.PMDEC_ERR[ii]= float(tab[0]['e_pmDE'][closest])
                if numpy.isnan(float(tab[0]['pmRA'][closest])): pmdata.PMMATCH[ii]= 0
            else:
                pmdata.PMDEC[ii]= float(tab[0]['pmDE'])
                pmdata.PMRA_ERR[ii]= float(tab[0]['e_pmRA'])
                pmdata.PMDEC_ERR[ii]= float(tab[0]['e_pmDE'])
                if numpy.isnan(float(tab[0]['pmRA'])): pmdata.PMMATCH[ii]= 0
        sys.stdout.write('\r'+_ERASESTR+'\r')
        sys.stdout.flush()
        fitsio.write(pmfile,pmdata,clobber=True)
        #To make sure we're using the same format below
        pmdata= fitsio.read(pmfile,1)
    #Match proper motions to ppmxl
    data= esutil.numpy_util.add_fields(data,[('PMRA_PPMXL', numpy.float),
                                             ('PMDEC_PPMXL', numpy.float),
                                             ('PMRA_ERR_PPMXL', numpy.float),
                                             ('PMDEC_ERR_PPMXL', numpy.float),
                                             ('PMMATCH_PPMXL',numpy.int32)])
    data['PMMATCH_PPMXL']= 0
    h=esutil.htm.HTM()
    m1,m2,d12 = h.match(pmdata['RA'],pmdata['DEC'],
                        data['RA'],data['DEC'],
                        2./3600.,maxmatch=1)
    data['PMRA_PPMXL'][m2]= pmdata['PMRA'][m1]
    data['PMDEC_PPMXL'][m2]= pmdata['PMDEC'][m1]
    data['PMRA_ERR_PPMXL'][m2]= pmdata['PMRA_ERR'][m1]
    data['PMDEC_ERR_PPMXL'][m2]= pmdata['PMDEC_ERR'][m1]
    data['PMMATCH_PPMXL'][m2]= pmdata['PMMATCH'][m1].astype(numpy.int32)
    pmindx= data['PMMATCH_PPMXL'] == 1
    data['PMRA_PPMXL'][True-pmindx]= -9999.99
    data['PMDEC_PPMXL'][True-pmindx]= -9999.99
    data['PMRA_ERR_PPMXL'][True-pmindx]= -9999.99
    data['PMDEC_ERR_PPMXL'][True-pmindx]= -9999.99
    #Calculate Galactocentric velocities
    data= esutil.numpy_util.add_fields(data,[('GALVR_PPMXL', numpy.float),
                                             ('GALVT_PPMXL', numpy.float),
                                             ('GALVZ_PPMXL', numpy.float)])
    lb= bovy_coords.radec_to_lb(data['RA'],data['DEC'],degree=True)
    XYZ= bovy_coords.lbd_to_XYZ(lb[:,0],lb[:,1],data['RC_DIST'],degree=True)
    pmllpmbb= bovy_coords.pmrapmdec_to_pmllpmbb(data['PMRA_PPMXL'],
                                                data['PMDEC_PPMXL'],
                                                data['RA'],data['DEC'],
                                                degree=True)
    vxvyvz= bovy_coords.vrpmllpmbb_to_vxvyvz(data['VHELIO_AVG'],
                                             pmllpmbb[:,0],
                                             pmllpmbb[:,1],
                                             lb[:,0],lb[:,1],data['RC_DIST'],
                                             degree=True)
    vR, vT, vZ= bovy_coords.vxvyvz_to_galcencyl(vxvyvz[:,0],
                                                vxvyvz[:,1],
                                                vxvyvz[:,2],
                                                8.-XYZ[:,0],
                                                XYZ[:,1],
                                                XYZ[:,2]+0.025,
                                                vsun=[-11.1,30.24*8.,7.25])#Assumes proper motion of Sgr A* and R0=8 kpc, zo= 25 pc
    data['GALVR_PPMXL']= vR
    data['GALVT_PPMXL']= vT
    data['GALVZ_PPMXL']= vZ
    data['GALVR_PPMXL'][True-pmindx]= -9999.99
    data['GALVT_PPMXL'][True-pmindx]= -9999.99
    data['GALVZ_PPMXL'][True-pmindx]= -9999.99
    #Save
    fitsio.write(savefilename,data,clobber=True)
    return None
예제 #10
0
def plot_gaiamag(plotfilename,plx=False):
    Zs= [0.0035,0.017,0.035]
    iso= isodist.PadovaIsochrone(type='sdss-2mass',parsec=True,
                                 Z=Zs)
    tages= [9.,9.3,9.5,9.7,9.85,10.,10.1]
    overplot= False
    bovy_plot.bovy_print()
    hs= [12.2,12.8,13.3,13.8]
    colors= ['r','y','g','b']
    for jj in range(len(hs)):
        h= hs[jj]
        for age in tages:
            for tZ in Zs:
                p= iso(age,tZ)
                jk= p['J']-p['Ks']
                indx= (jk < 0.8)*(jk > 0.5)\
                    *(tZ <= 0.06)\
                    *(tZ <= rcmodel.jkzcut(jk,upper=True))\
                    *(tZ >= rcmodel.jkzcut(jk))\
                    *(p['logg'] >= 1.8)\
                    *(p['logg'] <= 2.8)            
                tG= G(p['g'][indx],p['g'][indx]-p['z'][indx])-p['H'][indx]+h
                tdm= h+1.49
                tdist= 10.**(tdm/5.-2.) #kpc
                tplxerr= numpy.array([plxerr(tG[ii],
                                                   vifromgi(p['g'][indx][ii]-p['i'][indx][ii])) for ii in range(numpy.sum(indx))])
                if plx:
                    bovy_plot.bovy_plot(tG,
                                        tplxerr*tdist*100.,
                                        marker='o',color=colors[jj],mec='none',
                                        overplot=overplot,
                                        xlabel=r'$Gaia\ G$',
                                        ylabel=r'$\sigma_\pi/\pi\,(\%)$',
                                        xrange=[11.,21.],
                                        yrange=[0.,200.])
                else:
                    bovy_plot.bovy_plot(tG,
                                        4.74047*tdist*tplxerr*0.5,
                                        marker='o',color=colors[jj],mec='none',
                                        overplot=overplot,
                                        xlabel=r'$Gaia\ G$',
                                        ylabel=r'$\mathrm{transverse\ velocity\ uncertainty}\ (\mathrm{km\,s}^{-1})$',
                                        xrange=[11.,21.],
                                        yrange=[0.,8.])
                overplot= True
                #half a magnitude ah
                tvi= numpy.array([vifromgi(p['g'][indx][ii]-p['i'][indx][ii]) for ii in range(numpy.sum(indx))])
                ag= .5/0.18307*(0.8426-0.1187*tvi+0.0157*tvi**2.-0.0007*tvi**3.)
                tG= tG-0.5
                tplxerr= numpy.array([plxerr(tG[ii]+ag[ii],
                                                   vifromgi(p['g'][indx][ii]+.5/0.18307*1.20585-p['i'][indx][ii]-.5/0.18307*0.68319)) for ii in range(numpy.sum(indx))])
                tdm= h+1.49-0.5
                tdist= 10.**(tdm/5.-2.) #kpc
                #print numpy.median(ag)/.5, numpy.median(tvi), numpy.std(tvi)
                if plx:
                    bovy_plot.bovy_plot(tG+ag,
                                        tdist*tplxerr*100.,
                                        marker='o',color=colors[jj],mec='none',
                                        overplot=overplot)
                else:
                    bovy_plot.bovy_plot(tG+ag,
                                        4.74047*tdist*tplxerr*0.5,
                                        marker='o',color=colors[jj],mec='none',
                                        overplot=overplot)
                #Full magnitude of ah
                tvi= numpy.array([vifromgi(p['g'][indx][ii]-p['i'][indx][ii]) for ii in range(numpy.sum(indx))])
                ag= 1./0.18307*(0.8426-0.1187*tvi+0.0157*tvi**2.-0.0007*tvi**3.)
                tG= tG-0.5
                tplxerr= numpy.array([plxerr(tG[ii]+ag[ii],
                                                   vifromgi(p['g'][indx][ii]+1./0.18307*1.20585-p['i'][indx][ii]-1./0.18307*0.68319)) for ii in range(numpy.sum(indx))])
                tdm= h+1.49-1.
                tdist= 10.**(tdm/5.-2.) #kpc
                if plx:
                    bovy_plot.bovy_plot(tG+ag,
                                        tdist*tplxerr*100.,
                                        marker='o',color=colors[jj],mec='none',
                                        overplot=overplot)
                else:
                    bovy_plot.bovy_plot(tG+ag,
                                        4.74047*tdist*tplxerr*0.5,
                                        marker='o',color=colors[jj],mec='none',
                                        overplot=overplot)
                if True:
                    #1.5 magnitudes of ah
                    tvi= numpy.array([vifromgi(p['g'][indx][ii]-p['i'][indx][ii]) for ii in range(numpy.sum(indx))])
                    ag= 1.5/0.18307*(0.8426-0.1187*tvi+0.0157*tvi**2.-0.0007*tvi**3.)
                    tG= tG-.5
                    tplxerr= numpy.array([plxerr(tG[ii]+ag[ii],
                                                 vifromgi(p['g'][indx][ii]+1./0.18307*1.20585-p['i'][indx][ii]-1./0.18307*0.68319)) for ii in range(numpy.sum(indx))])
                    tdm= h+1.49-1.5
                    tdist= 10.**(tdm/5.-2.) #kpc
                    if plx:
                        bovy_plot.bovy_plot(tG+ag,
                                            tdist*tplxerr*100.,
                                            marker='o',color=colors[jj],mec='none',
                                            overplot=overplot)
                    else:
                        bovy_plot.bovy_plot(tG+ag,
                                            4.74047*tdist*tplxerr*0.5,
                                            marker='o',color=colors[jj],mec='none',
                                            overplot=overplot)
    bovy_plot.bovy_plot([20.,20.],[0.,300.],'k:',overplot=True)
    #Work on legend
    dot2= bovy_plot.bovy_plot([-10.],[-10.],'o',color=colors[0],overplot=True,mec='none')
    dot3= bovy_plot.bovy_plot([-10.],[-10.],'o',color=colors[1],overplot=True,mec='none')
    dot4= bovy_plot.bovy_plot([-10.],[-10.],'o',color=colors[2],overplot=True,mec='none')
    dot5= bovy_plot.bovy_plot([-10.],[-10.],'o',color=colors[3],overplot=True,mec='none')
    pyplot.legend((dot2[0],dot3[0],dot4[0],dot5[0]),
                  (r'$H = 12.2$',
                   r'$H = 12.8 \ \ \ \ \mathrm{each\ incl.}$',
                   r'$H = 13.3 \ \ \ A_H= 0, 0.5,$',
                   r'$H = 13.8 \ \ \ \ \ \ \ \ \ \ \ \ \, 1, 1.5$'),
                  loc='upper left',#bbox_to_anchor=(.91,.375),
                  numpoints=1,
                  prop={'size':16},
                  frameon=False)
    if plx:
        bovy_plot.bovy_plot([5.,25.],[10.,10.],'k--',lw=2.,overplot=True)
        bovy_plot.bovy_text(11.25,2.,r'$\mathrm{spectro-photometric\ RC\ precision}$',
                            size=16.)
        from matplotlib.patches import FancyArrowPatch
        ax=pyplot.gca()
        ax.add_patch(FancyArrowPatch((20.5,10.),(20.5,-1.),
                                     arrowstyle='->',mutation_scale=15,
                                     fill=True,
                                     lw=1.25,color='k'))
    #Add twin x axis w/ distsance
    ax= pyplot.gca()
    def my_formatter(x, pos):
        """distance in kpc for zero reddening"""
        xs= 10.**((x-0.71)/5.-2.)
        xs2= 10.**((x-0.71-4.)/5.-2.)
        if xs2 > 1:
            return r'$%.0f/%.0f$' % (xs,xs2)
        else:
            return r'$%.0f/%.1f$' % (xs,xs2)
    ax2= pyplot.twiny()
    major_formatter = FuncFormatter(my_formatter)
    ax2.xaxis.set_major_formatter(major_formatter)
    xstep= ax.xaxis.get_majorticklocs()
    xstep= xstep[1]-xstep[0]
    ax2.xaxis.set_minor_locator(MultipleLocator(xstep/5.))
    ax2.xaxis.tick_top()
    ax2.xaxis.set_label_position('top')
    xmin, xmax= ax.xaxis.get_view_interval()
    ax2.xaxis.set_view_interval(xmin,xmax,ignore=True)
    ax2.set_xlabel('$\mathrm{distance\ for}\ A_H = 0/1\,(\mathrm{kpc})$')
    ystep= ax.yaxis.get_majorticklocs()
    ystep= ystep[1]-ystep[0]
    ax2.yaxis.set_minor_locator(MultipleLocator(ystep/5.))
    #Save
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #11
0
                                                         upper=True))
 print "Current contamination in logg range %i / % i = %i%%" % (numpy.sum(bloggindx*gloggindx),len(data),float(numpy.sum(bloggindx*gloggindx))*100./len(data))
 nlogg= data['KASC_RG_LOGG_SCALE_2']+numpy.random.normal(size=len(data))*0.2
 bloggindx= (nlogg >= 1.8)*(nlogg <= rcmodel.loggteffcut(data['TEFF'],
                                                         data['METALS'],
                                                         upper=True))
 print "Future contamination w/ good logg (unbiased, errors 0.2) in logg range %i / % i = %i%%" % (numpy.sum(bloggindx*gloggindx),len(data),float(numpy.sum(bloggindx*gloggindx))*100./len(data))
 print "Future contamination w/ good logg (unbiased, errors 0.2) for just RC in logg range %i / % i = %i%%" % (numpy.sum(bloggindx*gloggindx*rcindx),numpy.sum(rcindx),float(numpy.sum(bloggindx*gloggindx*rcindx))*100./numpy.sum(rcindx))
 #Select stars to be in the RC from the APOKASC data, then check against 
 #evolutionary state
 jk= data['J0']-data['K0']
 z= isodist.FEH2Z(data['METALS'],zsolar=0.017)#*(0.638*10.**data['ALPHAFE']+0.372)
 logg= data['KASC_RG_LOGG_SCALE_2']+numpy.random.normal(size=len(data))*0. #can adjust this to look at errors
 indx= (jk < 0.8)*(jk >= 0.5)\
     *(z <= 0.06)\
     *(z <= rcmodel.jkzcut(jk,upper=True))\
     *(z >= rcmodel.jkzcut(jk))\
     *(logg >= 1.8)\
     *(logg <= rcmodel.loggteffcut(data['TEFF'],z,upper=True))
 #indx*= ((data['TEFF']-4800.)/1000.+2.75) > logg
 #*(logg <= 2.8)            
 rckascdata= data[indx]
 rcseismoState= numpy.char.strip(rckascdata['SEISMO EVOL'])
 seismo= True-((rcseismoState == 'UNKNOWN'))
 norcseismo= (rcseismoState == 'RGB') \
     + (rcseismoState == 'DWARF/SUBGIANT')
 print "%i / %i = %i%% APOKASC non-CLUMP stars out of all RC stars would be included with good logg" % (numpy.sum(norcseismo),numpy.sum(seismo),float(numpy.sum(norcseismo))/numpy.sum(seismo)*100.)
 #Now, how many of the stars in our RC cut have evol and how many of RGB?
 indx= (jk < 0.8)*(jk >= 0.5)\
     *(logg >= 1.8)\
     *(logg <= rcmodel.loggteffcut(data['TEFF'],z,upper=True))