Example #1
0
def plot_rcdistancecomparison(plotfilename):
    # Get the sample
    rcdata = define_rcsample.get_rcsample()
    # Now plot the differece
    bovy_plot.bovy_print()
    levels = special.erf(numpy.arange(1, 3) / numpy.sqrt(2.))
    bovy_plot.scatterplot(
        rcdata['RC_DIST'],
        (rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
        conditional=True,
        levels=levels,
        linestyle='none',
        color='k',
        marker=',',
        xrange=[0., 7.49],
        yrange=[-0.075, 0.075],
        xlabel=r'$M_{K_s}\!-\!\mathrm{based\ distance\,(kpc)}$',
        ylabel=
        r'$\mathrm{Fractional\ difference\ of}\ M_H\ \mathrm{vs.}\ M_{K_s}$',
        onedhistx=True,
        bins=31)
    bovy_plot.bovy_plot([0., 10.], [0., 0.],
                        '--',
                        lw=2.,
                        color='0.75',
                        overplot=True)
    # Plot lowess
    lowess = sm.nonparametric.lowess
    z = lowess((rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
               rcdata['RC_DIST'],
               frac=.3)
    bovy_plot.bovy_plot(z[:, 0], z[:, 1], 'w--', lw=2., overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def plot_dustwapogee(plotname):
    # Load the dust map
    green15map= dust.load_green15(5.,nest=True,nside_out=_NSIDE)
    green15map[green15map == healpy.UNSEEN]= -1.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,min=0.,max=.8,
                             format=r'$%g$',
                             title='',
                             cmap='gist_yarg',
                             unit='$A_H\,(\mathrm{mag})$')
    # Load the RC data to get the fields
    data= define_rcsample.get_rcsample()
    loc_ids= numpy.array(list(set(data['LOCATION_ID'])))
    # Load the selection function, just to get the field centers
    apo= apogee.select.apogeeSelect(_justprocessobslog=True)
    theta= numpy.empty(len(loc_ids))
    phi= numpy.empty(len(loc_ids))
    for ii,loc_id in enumerate(loc_ids):
        tl, tb= apo.glonGlat(loc_id)
        theta[ii]= (90.-tb)/180.*numpy.pi
        phi[ii]= tl/180.*numpy.pi
    hib= numpy.fabs((numpy.pi/2.-theta)) > (8./180.*numpy.pi)
    healpy.visufunc.projplot(theta[hib],phi[hib],'o',ms=5.,mfc='none',mew=0.8,
                             mec='k')
    lowb= True-hib
    healpy.visufunc.projplot(theta[lowb],phi[lowb],'o',ms=5.,mfc='none',
                             mec='w',mew=0.8)
    bovy_plot.bovy_end_print(plotname)
def load_data(sample):
    global ldata
    global data_highbIndx
    global data_outDiskIndx
    global data_betwDiskIndx
    global data_inDiskIndx
    global data_bulgeIndx
    global data_brightIndx
    global data_mediumIndx
    global data_faintIndx
    if sample.lower() == 'all':
        ldata = define_rcsample.get_rcsample()
    elif sample.lower() == 'alllowalpha':
        ldata = define_rcsample.get_rcsample()
        ldata = ldata[ldata[define_rcsample._AFETAG] < 0.1]
    elif sample.lower() == 'lowlow':
        ldata = define_rcsample.get_lowlowsample()
    elif sample.lower() == 'highfeh':
        ldata = define_rcsample.get_highfehsample()
    elif sample.lower() == 'highalpha':
        ldata = define_rcsample.get_highalphasample()
    elif sample.lower() == 'solar':
        ldata = define_rcsample.get_solarsample()
    # Get the indices of the various subsamples defined above
    data_highbIndx = numpy.zeros(len(ldata), dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[highbIndx]:
            data_highbIndx[ii] = True
    data_outDiskIndx = numpy.zeros(len(ldata), dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[outDiskIndx]:
            data_outDiskIndx[ii] = True
    data_betwDiskIndx = numpy.zeros(len(ldata), dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[betwDiskIndx]:
            data_betwDiskIndx[ii] = True
    data_inDiskIndx = numpy.zeros(len(ldata), dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[inDiskIndx]:
            data_inDiskIndx[ii] = True
    return None
def load_data(sample):
    global ldata
    global data_highbIndx
    global data_outDiskIndx
    global data_betwDiskIndx
    global data_inDiskIndx    
    global data_bulgeIndx    
    global data_brightIndx
    global data_mediumIndx
    global data_faintIndx
    if sample.lower() == 'all':
        ldata= define_rcsample.get_rcsample()
    elif sample.lower() == 'alllowalpha':
        ldata= define_rcsample.get_rcsample()
        ldata= ldata[ldata[define_rcsample._AFETAG] < 0.1]
    elif sample.lower() == 'lowlow':
        ldata= define_rcsample.get_lowlowsample()
    elif sample.lower() == 'highfeh':
        ldata= define_rcsample.get_highfehsample()
    elif sample.lower() == 'highalpha':
        ldata= define_rcsample.get_highalphasample()
    elif sample.lower() == 'solar':
        ldata= define_rcsample.get_solarsample()
    # Get the indices of the various subsamples defined above
    data_highbIndx= numpy.zeros(len(ldata),dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[highbIndx]:
            data_highbIndx[ii]= True
    data_outDiskIndx= numpy.zeros(len(ldata),dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[outDiskIndx]:
            data_outDiskIndx[ii]= True
    data_betwDiskIndx= numpy.zeros(len(ldata),dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[betwDiskIndx]:
            data_betwDiskIndx[ii]= True
    data_inDiskIndx= numpy.zeros(len(ldata),dtype='bool')
    for ii in range(len(ldata)):
        if ldata[ii]['LOCATION_ID'] in numpy.array(locations)[inDiskIndx]:
            data_inDiskIndx[ii]= True
    return None
Example #5
0
def calc_effsel(args, options, sample=None):
    # Work-horse function to compute the effective selection function,
    # sample is a data sample of stars to consider for the (JK,Z) sampling
    # Setup selection function
    selectFile = '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile, 'rb') as savefile:
            apo = pickle.load(savefile)
    else:
        # Setup selection function
        apo = apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile, apo)
    # Get the full data sample for the locations (need all locations where
    # stars could be observed, so the whole sample, not just the subsample
    # being analyzed)
    data = get_rcsample()
    locations = list(set(list(data['LOCATION_ID'])))
    # Load the dust map and setup the effective selection function
    if options.dmap.lower() == 'green15':
        dmap3d = mwdust.Green15(filter='2MASS H')
    elif options.dmap.lower() == 'marshall06':
        dmap3d = mwdust.Marshall06(filter='2MASS H')
    elif options.dmap.lower() == 'drimmel03':
        dmap3d = mwdust.Drimmel03(filter='2MASS H')
    elif options.dmap.lower() == 'sale14':
        dmap3d = mwdust.Sale14(filter='2MASS H')
    elif options.dmap.lower() == 'zero':
        dmap3d = mwdust.Zero(filter='2MASS H')
    # Sample the M_H distribution
    if options.samplemh:
        if sample is None: sample = data
        MH = sample['H0'] - sample['RC_DM']
        MH = numpy.random.permutation(MH)[:1000]  # do 1,000 max
    else:
        MH = -1.49
    apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=dmap3d, MH=MH)
    # Distances at which to calculate the effective selection function
    distmods = numpy.linspace(options.dm_min, options.dm_max, options.ndm)
    ds = 10.**(distmods / 5 - 2.)
    # Now compute all selection functions
    out= multi.parallel_map((lambda x: _calc_effsel_onelocation(\
                locations[x],apof,apo,ds)),
                            range(len(locations)),
                            numcores=numpy.amin([len(locations),
                                                 multiprocessing.cpu_count(),options.multi]))
    # Save out
    out = numpy.array(out)
    save_pickles(args[0], locations, out, distmods, ds)
    return None
Example #6
0
def calc_effsel(args,options,sample=None):
    # Work-horse function to compute the effective selection function, 
    # sample is a data sample of stars to consider for the (JK,Z) sampling
    # Setup selection function
    selectFile= '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile,'rb') as savefile:
            apo= pickle.load(savefile)
    else:
        # Setup selection function
        apo= apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile,apo)
    # Get the full data sample for the locations (need all locations where 
    # stars could be observed, so the whole sample, not just the subsample
    # being analyzed)
    data= get_rcsample()
    locations= list(set(list(data['LOCATION_ID'])))
    # Load the dust map and setup the effective selection function
    if options.dmap.lower() == 'green15':
        dmap3d= mwdust.Green15(filter='2MASS H')
    elif options.dmap.lower() == 'marshall06':
        dmap3d= mwdust.Marshall06(filter='2MASS H')
    elif options.dmap.lower() == 'drimmel03':
        dmap3d= mwdust.Drimmel03(filter='2MASS H')
    elif options.dmap.lower() == 'sale14':
        dmap3d= mwdust.Sale14(filter='2MASS H')
    elif options.dmap.lower() == 'zero':
        dmap3d= mwdust.Zero(filter='2MASS H')
    # Sample the M_H distribution
    if options.samplemh:
        if sample is None: sample= data
        MH= sample['H0']-sample['RC_DM']
        MH= numpy.random.permutation(MH)[:1000] # do 1,000 max
    else:
        MH= -1.49
    apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=dmap3d,MH=MH)
    # Distances at which to calculate the effective selection function
    distmods= numpy.linspace(options.dm_min,options.dm_max,options.ndm)
    ds= 10.**(distmods/5-2.)
    # Now compute all selection functions
    out= multi.parallel_map((lambda x: _calc_effsel_onelocation(\
                locations[x],apof,apo,ds)),
                            range(len(locations)),
                            numcores=numpy.amin([len(locations),
                                                 multiprocessing.cpu_count(),options.multi]))
    # Save out
    out= numpy.array(out)
    save_pickles(args[0],locations,out,distmods,ds)
    return None
def plot_dustwapogee(plotname):
    # Load the dust map
    green15map = dust.load_green15(5., nest=True, nside_out=_NSIDE)
    green15map[green15map == healpy.UNSEEN] = -1.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,
                             min=0.,
                             max=.8,
                             format=r'$%g$',
                             title='',
                             cmap='gist_yarg',
                             unit='$A_H\,(\mathrm{mag})$')
    # Load the RC data to get the fields
    data = define_rcsample.get_rcsample()
    loc_ids = numpy.array(list(set(data['LOCATION_ID'])))
    # Load the selection function, just to get the field centers
    apo = apogee.select.apogeeSelect(_justprocessobslog=True)
    theta = numpy.empty(len(loc_ids))
    phi = numpy.empty(len(loc_ids))
    for ii, loc_id in enumerate(loc_ids):
        tl, tb = apo.glonGlat(loc_id)
        theta[ii] = (90. - tb) / 180. * numpy.pi
        phi[ii] = tl / 180. * numpy.pi
    hib = numpy.fabs((numpy.pi / 2. - theta)) > (8. / 180. * numpy.pi)
    healpy.visufunc.projplot(theta[hib],
                             phi[hib],
                             'o',
                             ms=5.,
                             mfc='none',
                             mew=0.8,
                             mec='k')
    lowb = True - hib
    healpy.visufunc.projplot(theta[lowb],
                             phi[lowb],
                             'o',
                             ms=5.,
                             mfc='none',
                             mec='w',
                             mew=0.8)
    bovy_plot.bovy_end_print(plotname)
def plot_rcdistancecomparison(plotfilename):
    # Get the sample
    rcdata= define_rcsample.get_rcsample()
    # Now plot the differece
    bovy_plot.bovy_print()
    levels= special.erf(numpy.arange(1,3)/numpy.sqrt(2.))
    bovy_plot.scatterplot(rcdata['RC_DIST'],
                          (rcdata['RC_DIST_H']-rcdata['RC_DIST'])/rcdata['RC_DIST'],
                          conditional=True,
                          levels=levels,
                          linestyle='none',color='k',marker=',',
                          xrange=[0.,7.49],yrange=[-0.075,0.075],
                          xlabel=r'$M_{K_s}\!-\!\mathrm{based\ distance\,(kpc)}$',
                          ylabel=r'$\mathrm{Fractional\ difference\ of}\ M_H\ \mathrm{vs.}\ M_{K_s}$',
                          onedhistx=True,bins=31)
    bovy_plot.bovy_plot([0.,10.],[0.,0.],'--',lw=2.,color='0.75',overplot=True)
    # Plot lowess
    lowess= sm.nonparametric.lowess
    z= lowess((rcdata['RC_DIST_H']-rcdata['RC_DIST'])/rcdata['RC_DIST'],
              rcdata['RC_DIST'],frac=.3)             
    bovy_plot.bovy_plot(z[:,0],z[:,1],'w--',lw=2.,overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Example #9
0
def plot_afefeh(plotfilename):
    # Load the data
    data = define_rcsample.get_rcsample()
    # Plot the data
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(data[define_rcsample._FEHTAG],
                          data[define_rcsample._AFETAG],
                          'k.',
                          ms=.8,
                          levels=special.erf(
                              numpy.arange(1, 2) / numpy.sqrt(2.)),
                          xrange=[-1., 0.4],
                          yrange=[-0.15, 0.35],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=define_rcsample._AFELABEL)
    # Overplot sub-samples
    # low alpha, low feh
    lowfeh = define_rcsample._lowlow_lowfeh(0.)
    highfeh = define_rcsample._lowlow_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._lowlow_lowafe(lowfeh),
        define_rcsample._lowlow_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._lowlow_lowafe(highfeh),
        define_rcsample._lowlow_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._lowlow_lowafe(lowfeh),
        define_rcsample._lowlow_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._lowlow_highafe(lowfeh),
        define_rcsample._lowlow_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # high alpha
    lowfeh = define_rcsample._highalpha_lowfeh(0.)
    highfeh = define_rcsample._highalpha_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._highalpha_lowafe(lowfeh),
        define_rcsample._highalpha_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._highalpha_lowafe(highfeh),
        define_rcsample._highalpha_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highalpha_lowafe(lowfeh),
        define_rcsample._highalpha_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highalpha_highafe(lowfeh),
        define_rcsample._highalpha_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # solar
    lowfeh = define_rcsample._solar_lowfeh(0.)
    highfeh = define_rcsample._solar_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._solar_lowafe(lowfeh),
        define_rcsample._solar_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._solar_lowafe(highfeh),
        define_rcsample._solar_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._solar_lowafe(lowfeh),
        define_rcsample._solar_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._solar_highafe(lowfeh),
        define_rcsample._solar_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # high [Fe/H]
    lowfeh = define_rcsample._highfeh_lowfeh(0.)
    highfeh = define_rcsample._highfeh_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._highfeh_lowafe(lowfeh),
        define_rcsample._highfeh_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._highfeh_lowafe(highfeh),
        define_rcsample._highfeh_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highfeh_lowafe(lowfeh),
        define_rcsample._highfeh_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highfeh_highafe(lowfeh),
        define_rcsample._highfeh_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # Label them
    bovy_plot.bovy_text(-0.4,
                        0.265,
                        r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
                        size=15.,
                        backgroundcolor='w')
    bovy_plot.bovy_text(-0.975,
                        0.05,
                        r'$\mathrm{low\ [Fe/H]}$',
                        size=15.,
                        backgroundcolor='w')
    bovy_plot.bovy_text(0.,
                        -0.125,
                        r'$\mathrm{high\ [Fe/H]}$',
                        size=15.,
                        backgroundcolor='w')
    bovy_plot.bovy_text(-0.225,
                        -0.125,
                        r'$\mathrm{solar}$',
                        size=15.,
                        backgroundcolor='w')
    # Loci
    if False:
        haloc = define_rcsample.highalphalocus()
        bovy_plot.bovy_plot(haloc[:, 0],
                            haloc[:, 1],
                            'k-',
                            lw=2.,
                            overplot=True)
        haloc = define_rcsample.lowalphalocus()
        bovy_plot.bovy_plot(haloc[:, 0],
                            haloc[:, 1],
                            'k-',
                            lw=2.,
                            overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Example #10
0
    parser.add_option("--H0",dest='H0',default=-1.49,type='float',
                      help="RC absolute magnitude")
    parser.add_option("--nls",dest='nls',default=101,type='int',
                      help="Number of longitudes to bin each field in")
    parser.add_option("--nmock",dest='nmock',default=20000,type='int',
                      help="Number of mock samples to generate")
    # Dust map to use
    parser.add_option("--extmap",dest='extmap',default='green15',
                      help="Dust map to use ('Green15', 'Marshall03', 'Drimmel03', 'Sale14', or 'zero'")
    # Multiprocessing?
    parser.add_option("-m","--multi",dest='multi',default=1,type='int',
                      help="number of cpus to use")
    return parser

if __name__ == '__main__':
    parser= get_options()
    options, args= parser.parse_args()
    data= define_rcsample.get_rcsample()
    locations= list(set(list(data['LOCATION_ID'])))
    #locations= [4240,4242]
    out= generate(locations,
                  type=options.type,
                  sample=options.sample,
                  extmap=options.extmap,
                  nls=options.nls,
                  nmock=options.nmock,
                  H0=options.H0,
                  ncpu=options.multi)
    fitsio.write(args[0],out[0],clobber=True)
    
Example #11
0
def plot_afe_spectra(savename,plotname):
    # Load the data
    data= define_rcsample.get_rcsample()
    data= data[data['SNR'] > 200.]
    fehindx= (data['FE_H'] <= -0.35)*(data['FE_H'] > -0.45)
    fehdata= data[fehindx]
    # First compute the residuals and do the EM-PCA smoothing
    if not os.path.exists(savename):
        nspec= len(fehdata)
        spec= numpy.zeros((nspec,7214))
        specerr= numpy.zeros((nspec,7214))
        for ii in range(nspec):
            sys.stdout.write('\r'+"Loading spectrum %i / %i ...\r" % (ii+1,nspec))
            sys.stdout.flush()
            spec[ii]= apread.aspcapStar(fehdata['LOCATION_ID'][ii],
                                        fehdata['APOGEE_ID'][ii],
                                        ext=1,header=False,aspcapWavegrid=True)
            specerr[ii]= apread.aspcapStar(fehdata['LOCATION_ID'][ii],
                                           fehdata['APOGEE_ID'][ii],
                                           ext=2,header=False,
                                           aspcapWavegrid=True)
        teffs= fehdata['FPARAM'][:,paramIndx('teff')]
        loggs= fehdata['FPARAM'][:,paramIndx('logg')]
        metals= fehdata[define_rcsample._FEHTAG]
        cf, s, r= apcannon.quadfit(spec,specerr,
                                   teffs-4800.,loggs-2.85,metals+0.3,
                                   return_residuals=True)
        pr= numpy.zeros_like(r)
        # Deal w/ bad data
        _MAXERR= 0.02
        npca= 8
        pca_input= r
        pca_weights= (1./specerr**2.)
        pca_weights[pca_weights < 1./_MAXERR**2.]= 0. 
        nanIndx= numpy.isnan(pca_input) + numpy.isnan(pca_weights)
        pca_weights[nanIndx]= 0. 
        pca_input[nanIndx]= 0.
        # Run EM-PCA
        m= empca.empca(pca_input,pca_weights,nvec=npca,niter=25)#,silent=False)
        for jj in range(nspec):
            for kk in range(npca):
                pr[jj]+= m.coeff[jj,kk]*m.eigvec[kk]
        save_pickles(savename,pr,r,cf)
    else:
        with open(savename,'rb') as savefile:
            pr= pickle.load(savefile)
    # Now plot the various elements
    colormap= cm.seismic
    colorFunc= lambda afe: afe/0.25
    widths= [3.5,2.]
    yranges= [[-0.05,0.02],[-0.03,0.01]]
    for ee, elem in enumerate(['S','Ca1']):
        for ii in range(5):
            tindx= (fehdata[define_rcsample._AFETAG] > ii*0.05-0.025)\
                *(fehdata[define_rcsample._AFETAG] <= (ii+1)*0.05-0.025)
            args= (apstack.median(pr[tindx][:12]),elem,)
            kwargs= {'markLines':ii==4,
                     'yrange':yranges[ee],
                     'ylabel':'',
                     'cleanZero':False,
                     'zorder':int(numpy.floor(numpy.random.uniform()*5)),
                     'color':colormap(colorFunc(ii*0.05)),
                     'overplot':ii>0,
                     'fig_width':widths[ee]}
            if ii>0: kwargs.pop('fig_width')
            splot.windows(*args,**kwargs)
        bovy_plot.bovy_end_print(plotname.replace('ELEM',
                                                  elem.lower().capitalize()))
    # Also do Mg
    for ii in range(5):
        tindx= (fehdata[define_rcsample._AFETAG] > ii*0.05-0.025)\
            *(fehdata[define_rcsample._AFETAG] <= (ii+1)*0.05-0.025)
        args= (apstack.median(pr[tindx][:12]),)
        kwargs={'startindxs':[3012,3120,3990],
                'endindxs':[3083,3158,4012],
                'yrange':[-0.05,0.02],
                'ylabel':'',
                'cleanZero':False,
                '_markwav':[15745.017,15753.189,15770.055,15958.836],
                'zorder':int(numpy.floor(numpy.random.uniform()*5)),
                'color':colormap(colorFunc(ii*0.05)),
                'overplot':ii>0,
                'fig_width':4.5,
                'markLines':True}
        if ii>0: kwargs.pop('fig_width')
        if ii != 4: 
            kwargs.pop('_markwav')
            kwargs.pop('markLines')
        kwargs['_startendskip']= 0
        kwargs['_noxticks']= True
        kwargs['_labelwav']= True
        splot.waveregions(*args,**kwargs)                          
        bovy_plot.bovy_text(r'$\mathrm{Mg}$',
                            top_left=True,fontsize=10,backgroundcolor='w')
    bovy_plot.bovy_end_print(plotname.replace('ELEM','Mg'))
    # Also do Si
    for ii in range(5):
        tindx= (fehdata[define_rcsample._AFETAG] > ii*0.05-0.025)\
            *(fehdata[define_rcsample._AFETAG] <= (ii+1)*0.05-0.025)
        args= (apstack.median(pr[tindx][:12]),)
        kwargs={'startindxs':[4469, 4624,5171, 7205, 7843],
                'endindxs':[4488, 4644,5182, 7243, 7871],
                'yrange':[-0.05,0.02],
                'ylabel':'',
                'cleanZero':False,
                '_markwav':apwindow.lines('Si'),
                'zorder':int(numpy.floor(numpy.random.uniform()*5)),
                'color':colormap(colorFunc(ii*0.05)),
                'overplot':ii>0,
                'fig_width':6.,
                'markLines':True}
        if ii>0: kwargs.pop('fig_width')
        if ii != 4: 
            kwargs.pop('_markwav')
            kwargs.pop('markLines')
        kwargs['_startendskip']= 0
        kwargs['_noxticks']= True
        kwargs['_labelwav']= True
        splot.waveregions(*args,**kwargs)                          
        bovy_plot.bovy_text(r'$\mathrm{Si}$',
                            top_left=True,fontsize=10,backgroundcolor='w')
    bovy_plot.bovy_end_print(plotname.replace('ELEM','Si2'))
    # Also do Oxygen
    for ii in range(5):
        tindx= (fehdata[define_rcsample._AFETAG] > ii*0.05-0.025)\
            *(fehdata[define_rcsample._AFETAG] <= (ii+1)*0.05-0.025)
        args= (apstack.median(pr[tindx][:12]),)
        kwargs={'startlams':[15558,16242,16536,16720],
                'endlams':[15566,16250,16544,16728],
                'yrange':[-0.05,0.02],
                'ylabel':'',
                'cleanZero':False,
                '_markwav':[15562,16246,16539,16723.5],
                'zorder':int(numpy.floor(numpy.random.uniform()*5)),
                'color':colormap(colorFunc(ii*0.05)),
                'overplot':ii>0,
                'fig_width':5.,
                'markLines':True}
        if ii>0: kwargs.pop('fig_width')
        if ii != 4: 
            kwargs.pop('_markwav')
            kwargs.pop('markLines')
        kwargs['_startendskip']= 0
        kwargs['_noxticks']= True
        kwargs['_labelwav']= True
        splot.waveregions(*args,**kwargs)                          
        bovy_plot.bovy_text(r'$\mathrm{O}$',
                            top_left=True,fontsize=10,backgroundcolor='w')
    bovy_plot.bovy_end_print(plotname.replace('ELEM','O'))
    # Also do Ti
    for ii in range(5):
        tindx= (fehdata[define_rcsample._AFETAG] > ii*0.05-0.025)\
            *(fehdata[define_rcsample._AFETAG] <= (ii+1)*0.05-0.025)
        args= (apstack.median(pr[tindx][:12]),)
        kwargs={'startindxs':[1116,2100,2899],
                'endindxs':[1146,2124,2922],
                'yrange':[-0.05,0.02],
                'ylabel':'',
                'cleanZero':False,
                '_markwav':apwindow.lines('Ti'),
                'zorder':int(numpy.floor(numpy.random.uniform()*5)),
                'color':colormap(colorFunc(ii*0.05)),
                'overplot':ii>0,
                'fig_width':3.5,
                'markLines':True}
        if ii>0: kwargs.pop('fig_width')
        if ii != 4: 
            kwargs.pop('_markwav')
            kwargs.pop('markLines')
        kwargs['_startendskip']= 0
        kwargs['_noxticks']= True
        kwargs['_labelwav']= True
        splot.waveregions(*args,**kwargs)                          
        bovy_plot.bovy_text(r'$\mathrm{Ti}$',
                            top_left=True,fontsize=10,backgroundcolor='w')
    bovy_plot.bovy_end_print(plotname.replace('ELEM','Ti'))
    return None
Example #12
0
def plot_afefeh(plotfilename):
    # Load the data
    data= define_rcsample.get_rcsample()
    # Plot the data
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(data[define_rcsample._FEHTAG],
                          data[define_rcsample._AFETAG],
                          'k.',ms=.8,
                          levels=special.erf(numpy.arange(1,2)/numpy.sqrt(2.)),
                          xrange=[-1.,0.4],
                          yrange=[-0.15,0.35],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=define_rcsample._AFELABEL)
    # Overplot sub-samples
    # low alpha, low feh
    lowfeh= define_rcsample._lowlow_lowfeh(0.)
    highfeh= define_rcsample._lowlow_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._lowlow_lowafe(lowfeh),
                                 define_rcsample._lowlow_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._lowlow_lowafe(highfeh),
                                   define_rcsample._lowlow_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._lowlow_lowafe(lowfeh),
                                  define_rcsample._lowlow_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._lowlow_highafe(lowfeh),
                                  define_rcsample._lowlow_highafe(highfeh)],
                'k--',lw=2.)
    # high alpha
    lowfeh= define_rcsample._highalpha_lowfeh(0.)
    highfeh= define_rcsample._highalpha_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._highalpha_lowafe(lowfeh),
                                 define_rcsample._highalpha_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._highalpha_lowafe(highfeh),
                                   define_rcsample._highalpha_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highalpha_lowafe(lowfeh),
                                  define_rcsample._highalpha_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highalpha_highafe(lowfeh),
                                  define_rcsample._highalpha_highafe(highfeh)],
                'k--',lw=2.)
    # solar
    lowfeh= define_rcsample._solar_lowfeh(0.)
    highfeh= define_rcsample._solar_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._solar_lowafe(lowfeh),
                                 define_rcsample._solar_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._solar_lowafe(highfeh),
                                   define_rcsample._solar_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._solar_lowafe(lowfeh),
                                  define_rcsample._solar_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._solar_highafe(lowfeh),
                                  define_rcsample._solar_highafe(highfeh)],
                'k--',lw=2.)
    # high [Fe/H]
    lowfeh= define_rcsample._highfeh_lowfeh(0.)
    highfeh= define_rcsample._highfeh_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._highfeh_lowafe(lowfeh),
                                 define_rcsample._highfeh_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._highfeh_lowafe(highfeh),
                                   define_rcsample._highfeh_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highfeh_lowafe(lowfeh),
                                  define_rcsample._highfeh_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highfeh_highafe(lowfeh),
                                  define_rcsample._highfeh_highafe(highfeh)],
                'k--',lw=2.)
    # Label them
    bovy_plot.bovy_text(-0.4,0.265,r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
                         size=15.,backgroundcolor='w')
    bovy_plot.bovy_text(-0.975,0.05,r'$\mathrm{low\ [Fe/H]}$',
                         size=15.,backgroundcolor='w')
    bovy_plot.bovy_text(0.,-0.125,r'$\mathrm{high\ [Fe/H]}$',
                         size=15.,backgroundcolor='w')
    bovy_plot.bovy_text(-0.225,-0.125,r'$\mathrm{solar}$',
                         size=15.,backgroundcolor='w')
    # Loci
    if False:
        haloc= define_rcsample.highalphalocus()
        bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'k-',lw=2.,overplot=True)
        haloc= define_rcsample.lowalphalocus()
        bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'k-',lw=2.,overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def plot_ah_location(location, plotname):
    # Setup selection function
    selectFile = '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile, 'rb') as savefile:
            apo = pickle.load(savefile)
    else:
        # Setup selection function
        apo = apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile, apo)
    glon, glat = apo.glonGlat(location)
    glon = glon[0]
    glat = glat[0]
    ahFile = '../savs/ah-%i.sav' % location
    if not os.path.exists(ahFile):
        # Distances at which to calculate the extinction
        distmods = numpy.linspace(7., 15.5, 301)
        ds = 10.**(distmods / 5 - 2.)
        # Setup Green et al. (2015) dust map
        gd = mwdust.Green15(filter='2MASS H')
        pa, ah = gd.dust_vals_disk(glon, glat, ds, apo.radius(location))
        meanah_default = numpy.sum(numpy.tile(pa, (len(ds), 1)).T * ah,
                                   axis=0) / numpy.sum(pa)
        stdah_default= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                *ah**2.,axis=0)\
                                      /numpy.sum(pa)-meanah_default**2.)
        # Marshall et al. (2006)
        marshall = mwdust.Marshall06(filter='2MASS H')
        try:
            pa, ah = marshall.dust_vals_disk(glon, glat, ds,
                                             apo.radius(location))
        except IndexError:
            meanah_marshall = -numpy.ones_like(ds)
            stdah_marshall = -numpy.ones_like(ds)
        else:
            meanah_marshall = numpy.sum(numpy.tile(pa, (len(ds), 1)).T * ah,
                                        axis=0) / numpy.sum(pa)
            stdah_marshall= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                     *ah**2.,axis=0)\
                                       /numpy.sum(pa)-meanah_marshall**2.)
        if True:
            # Drimmel et al. (2003)
            drimmel = mwdust.Drimmel03(filter='2MASS H')
            pa, ah = drimmel.dust_vals_disk(glon, glat, ds,
                                            apo.radius(location))
            meanah_drimmel = numpy.sum(numpy.tile(pa, (len(ds), 1)).T * ah,
                                       axis=0) / numpy.sum(pa)
            stdah_drimmel= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                    *ah**2.,axis=0)\
                                          /numpy.sum(pa)-meanah_drimmel**2.)
        else:
            meanah_drimmel = -numpy.ones_like(ds)
            stdah_drimmel = -numpy.ones_like(ds)
        if True:
            # Sale et al. (2014)
            sale = mwdust.Sale14(filter='2MASS H')
            try:
                pa, ah = sale.dust_vals_disk(glon, glat, ds,
                                             apo.radius(location))
                meanah_sale = numpy.sum(numpy.tile(pa, (len(ds), 1)).T * ah,
                                        axis=0) / numpy.sum(pa)
            except (TypeError, ValueError):
                meanah_sale = -numpy.ones_like(ds)
                stdah_sale = -numpy.ones_like(ds)
            else:
                stdah_sale= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                     *ah**2.,axis=0)\
                                           /numpy.sum(pa)-meanah_sale**2.)
        else:
            meanah_sale = -numpy.ones_like(ds)
            stdah_sale = -numpy.ones_like(ds)
        save_pickles(ahFile, distmods, meanah_default, stdah_default,
                     meanah_marshall, stdah_marshall, meanah_drimmel,
                     stdah_drimmel, meanah_sale, stdah_sale)
    else:
        with open(ahFile, 'rb') as savefile:
            distmods = pickle.load(savefile)
            meanah_default = pickle.load(savefile)
            stdah_default = pickle.load(savefile)
            meanah_marshall = pickle.load(savefile)
            stdah_marshall = pickle.load(savefile)
            meanah_drimmel = pickle.load(savefile)
            stdah_drimmel = pickle.load(savefile)
            meanah_sale = pickle.load(savefile)
            stdah_sale = pickle.load(savefile)
    # Now plot
    bovy_plot.bovy_print(fig_height=3.)
    if _PLOTDIST:
        distmods = 10.**(distmods / 5 - 2.)
        xrange = [0., 12.]
        xlabel = r'$D\,(\mathrm{kpc})$'
    else:
        xrange = [7., 15.8],
        xlabel = r'$\mathrm{distance\ modulus}\ \mu$'
    ylabel = r'$A_H$'
    yrange = [
        0., 1.2 * numpy.amax(
            numpy.vstack(
                (meanah_default + stdah_default,
                 meanah_marshall + stdah_marshall,
                 meanah_drimmel + stdah_drimmel, meanah_sale + stdah_sale)))
    ]
    line_default = bovy_plot.bovy_plot(distmods,
                                       meanah_default,
                                       'b-',
                                       lw=_LW,
                                       zorder=12,
                                       xrange=xrange,
                                       xlabel=xlabel,
                                       yrange=yrange,
                                       ylabel=ylabel)
    pyplot.fill_between(distmods,
                        meanah_default - stdah_default,
                        meanah_default + stdah_default,
                        hatch='/',
                        facecolor=(0, 0, 0, 0),
                        color='b',
                        lw=0.25,
                        zorder=4)
    line_marshall = bovy_plot.bovy_plot(distmods,
                                        meanah_marshall,
                                        'r-',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=8)
    pyplot.fill_between(distmods,
                        meanah_marshall - stdah_marshall,
                        meanah_marshall + stdah_marshall,
                        hatch='\\',
                        facecolor=(0, 0, 0, 0),
                        color='r',
                        lw=0.25,
                        zorder=2)
    line_drimmel = bovy_plot.bovy_plot(distmods,
                                       meanah_drimmel,
                                       '-',
                                       lw=_LW,
                                       color='gold',
                                       overplot=True,
                                       zorder=7)
    pyplot.fill_between(distmods,
                        meanah_drimmel - stdah_drimmel,
                        meanah_drimmel + stdah_drimmel,
                        hatch='///',
                        facecolor=(0, 0, 0, 0),
                        color='gold',
                        lw=0.25,
                        zorder=1)
    line_sale = bovy_plot.bovy_plot(distmods,
                                    meanah_sale,
                                    '-',
                                    lw=_LW,
                                    color='c',
                                    overplot=True,
                                    zorder=9)
    pyplot.fill_between(distmods,
                        meanah_sale - stdah_sale,
                        meanah_sale + stdah_sale,
                        hatch='//',
                        facecolor=(0, 0, 0, 0),
                        color='c',
                        lw=0.25,
                        zorder=3)
    if True:
        data = get_rcsample()
        data = data[data['LOCATION_ID'] == location]
        bovy_plot.bovy_plot(data['RC_DIST'],
                            data['AK_TARG'] * 1.55,
                            'ko',
                            zorder=20,
                            overplot=True,
                            ms=2.)
    if location == 4318:
        pyplot.legend(
            (line_default[0], line_sale[0]),
            (r'$\mathrm{Green\ et\ al.\ (2015)}$',
             r'$\mathrm{Sale\ et\ al.\ (2014)}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    elif location == 4242:
        pyplot.legend(
            (line_marshall[0], line_drimmel[0]),
            (r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
             r'$\mathrm{Drimmel\ et\ al.\ (2003)}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    # Label
    lcen, bcen = apo.glonGlat(location)
    if numpy.fabs(bcen) < 0.1: bcen = 0.
    bovy_plot.bovy_text(r'$(l,b) = (%.1f,%.1f)$' % (lcen, bcen),
                        top_right=True,
                        size=16.)
    bovy_plot.bovy_end_print(plotname,
                             dpi=300,
                             bbox_extra_artists=pyplot.gca().get_children(),
                             bbox_inches='tight')
    return None
def plot_ah_location(location,plotname):
    # Setup selection function
    selectFile= '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile,'rb') as savefile:
            apo= pickle.load(savefile)
    else:
        # Setup selection function
        apo= apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile,apo)
    glon, glat= apo.glonGlat(location)
    glon= glon[0]
    glat= glat[0]
    ahFile= '../savs/ah-%i.sav' % location
    if not os.path.exists(ahFile):
        # Distances at which to calculate the extinction
        distmods= numpy.linspace(7.,15.5,301)
        ds= 10.**(distmods/5-2.)
        # Setup Green et al. (2015) dust map
        gd= mwdust.Green15(filter='2MASS H')
        pa, ah= gd.dust_vals_disk(glon,glat,ds,apo.radius(location))
        meanah_default= numpy.sum(numpy.tile(pa,(len(ds),1)).T*ah,axis=0)/numpy.sum(pa)
        stdah_default= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                *ah**2.,axis=0)\
                                      /numpy.sum(pa)-meanah_default**2.)
        # Marshall et al. (2006)
        marshall= mwdust.Marshall06(filter='2MASS H')
        try:
            pa, ah= marshall.dust_vals_disk(glon,glat,ds,apo.radius(location))
        except IndexError:
            meanah_marshall= -numpy.ones_like(ds)
            stdah_marshall= -numpy.ones_like(ds)
        else:
            meanah_marshall= numpy.sum(numpy.tile(pa,(len(ds),1)).T*ah,
                                       axis=0)/numpy.sum(pa)
            stdah_marshall= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                     *ah**2.,axis=0)\
                                       /numpy.sum(pa)-meanah_marshall**2.)
        if True:
            # Drimmel et al. (2003)
            drimmel= mwdust.Drimmel03(filter='2MASS H')
            pa, ah= drimmel.dust_vals_disk(glon,glat,ds,apo.radius(location))
            meanah_drimmel= numpy.sum(numpy.tile(pa,(len(ds),1)).T*ah,axis=0)/numpy.sum(pa)
            stdah_drimmel= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                    *ah**2.,axis=0)\
                                          /numpy.sum(pa)-meanah_drimmel**2.)
        else:
            meanah_drimmel= -numpy.ones_like(ds)
            stdah_drimmel= -numpy.ones_like(ds)
        if True:
            # Sale et al. (2014)
            sale= mwdust.Sale14(filter='2MASS H')
            try:
                pa, ah= sale.dust_vals_disk(glon,glat,ds,apo.radius(location))
                meanah_sale= numpy.sum(numpy.tile(pa,(len(ds),1)).T*ah,
                                       axis=0)/numpy.sum(pa)
            except (TypeError,ValueError):
                meanah_sale= -numpy.ones_like(ds)
                stdah_sale= -numpy.ones_like(ds)               
            else:
                stdah_sale= numpy.sqrt(numpy.sum(numpy.tile(pa,(len(ds),1)).T\
                                                     *ah**2.,axis=0)\
                                           /numpy.sum(pa)-meanah_sale**2.)
        else:
                meanah_sale= -numpy.ones_like(ds)
                stdah_sale= -numpy.ones_like(ds)
        save_pickles(ahFile,distmods,meanah_default,stdah_default,
                     meanah_marshall,stdah_marshall,
                     meanah_drimmel,stdah_drimmel,
                     meanah_sale,stdah_sale)
    else:
        with open(ahFile,'rb') as savefile:
            distmods= pickle.load(savefile)
            meanah_default= pickle.load(savefile)
            stdah_default= pickle.load(savefile)
            meanah_marshall= pickle.load(savefile)
            stdah_marshall= pickle.load(savefile)
            meanah_drimmel= pickle.load(savefile)
            stdah_drimmel= pickle.load(savefile)
            meanah_sale= pickle.load(savefile)
            stdah_sale= pickle.load(savefile)
    # Now plot
    bovy_plot.bovy_print(fig_height=3.)
    if _PLOTDIST:
        distmods= 10.**(distmods/5-2.)
        xrange= [0.,12.]
        xlabel=r'$D\,(\mathrm{kpc})$'
    else:
        xrange=[7.,15.8],
        xlabel=r'$\mathrm{distance\ modulus}\ \mu$'
    ylabel=r'$A_H$'
    yrange= [0.,1.2*numpy.amax(numpy.vstack((meanah_default+stdah_default,
                                             meanah_marshall+stdah_marshall,
                                             meanah_drimmel+stdah_drimmel,
                                             meanah_sale+stdah_sale)))]
    line_default= bovy_plot.bovy_plot(distmods,meanah_default,
                                      'b-',lw=_LW,zorder=12,
                                      xrange=xrange,
                                      xlabel=xlabel,
                                      yrange=yrange,
                                      ylabel=ylabel)
    pyplot.fill_between(distmods,
                        meanah_default-stdah_default,
                        meanah_default+stdah_default,
                        hatch='/',facecolor=(0,0,0,0),
                        color='b',lw=0.25,zorder=4)
    line_marshall= bovy_plot.bovy_plot(distmods,meanah_marshall,'r-',lw=_LW,
                                       overplot=True,
                                       zorder=8)
    pyplot.fill_between(distmods,
                        meanah_marshall-stdah_marshall,
                        meanah_marshall+stdah_marshall,
                        hatch='\\',facecolor=(0,0,0,0),
                        color='r',lw=0.25,zorder=2)
    line_drimmel= bovy_plot.bovy_plot(distmods,meanah_drimmel,'-',lw=_LW,
                                      color='gold',
                                       overplot=True,
                                       zorder=7)
    pyplot.fill_between(distmods,
                        meanah_drimmel-stdah_drimmel,
                        meanah_drimmel+stdah_drimmel,
                        hatch='///',facecolor=(0,0,0,0),
                        color='gold',lw=0.25,zorder=1)
    line_sale= bovy_plot.bovy_plot(distmods,meanah_sale,'-',lw=_LW,
                                   color='c',
                                   overplot=True,
                                   zorder=9)
    pyplot.fill_between(distmods,
                        meanah_sale-stdah_sale,
                        meanah_sale+stdah_sale,
                        hatch='//',facecolor=(0,0,0,0),
                        color='c',lw=0.25,zorder=3)
    if True:
        data= get_rcsample()
        data= data[data['LOCATION_ID'] == location]
        bovy_plot.bovy_plot(data['RC_DIST'],data['AK_TARG']*1.55,
                            'ko',zorder=20,overplot=True,ms=2.)
    if location == 4318:
        pyplot.legend((line_default[0],line_sale[0]),
                      (r'$\mathrm{Green\ et\ al.\ (2015)}$',
                       r'$\mathrm{Sale\ et\ al.\ (2014)}$'),
                      loc='lower right',#bbox_to_anchor=(.91,.375),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False)                      
    elif location == 4242:
        pyplot.legend((line_marshall[0],line_drimmel[0]),
                      (r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
                       r'$\mathrm{Drimmel\ et\ al.\ (2003)}$'),
                      loc='lower right',#bbox_to_anchor=(.91,.375),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False)                      
    # Label
    lcen, bcen= apo.glonGlat(location)
    if numpy.fabs(bcen) < 0.1: bcen= 0.
    bovy_plot.bovy_text(r'$(l,b) = (%.1f,%.1f)$' % (lcen,bcen),
                        top_right=True,size=16.)
    bovy_plot.bovy_end_print(plotname,dpi=300,
                             bbox_extra_artists=pyplot.gca().get_children(),
                             bbox_inches='tight')
    return None
Example #15
0
        dest='extmap',
        default='green15',
        help=
        "Dust map to use ('Green15', 'Marshall03', 'Drimmel03', 'Sale14', or 'zero'"
    )
    # Multiprocessing?
    parser.add_option("-m",
                      "--multi",
                      dest='multi',
                      default=1,
                      type='int',
                      help="number of cpus to use")
    return parser


if __name__ == '__main__':
    parser = get_options()
    options, args = parser.parse_args()
    data = define_rcsample.get_rcsample()
    locations = list(set(list(data['LOCATION_ID'])))
    #locations= [4240,4242]
    out = generate(locations,
                   type=options.type,
                   sample=options.sample,
                   extmap=options.extmap,
                   nls=options.nls,
                   nmock=options.nmock,
                   H0=options.H0,
                   ncpu=options.multi)
    fitsio.write(args[0], out[0], clobber=True)
Example #16
0
def plot_effsel_location(location, plotname):
    # Setup selection function
    selectFile = '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile, 'rb') as savefile:
            apo = pickle.load(savefile)
    else:
        # Setup selection function
        apo = apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile, apo)
    effselFile = '../savs/effselfunc-%i.sav' % location
    if not os.path.exists(effselFile):
        # Distances at which to calculate the effective selection function
        distmods = numpy.linspace(7., 15.5, 301)
        ds = 10.**(distmods / 5 - 2.)
        # Setup default effective selection function
        do_samples = True
        gd = mwdust.Green15(filter='2MASS H', load_samples=do_samples)
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=gd)
        sf_default = apof(location, ds)
        # Also calculate for a sample of MH
        data = get_rcsample()
        MH = data['H0'] - data['RC_DM']
        MH = numpy.random.permutation(MH)[:1000]
        sf_jkz = apof(location, ds, MH=MH)
        # Go through the samples
        sf_samples = numpy.zeros((20, len(ds)))
        if do_samples:
            for ii in range(20):
                # Swap in a sample for bestfit in the Green et al. (2015) dmap
                gd.substitute_sample(ii)
                apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=gd)
                sf_samples[ii] = apof(location, ds)
        zerodust = mwdust.Zero(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=zerodust)
        sf_zero = apof(location, ds)
        drimmel = mwdust.Drimmel03(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=drimmel)
        sf_drimmel = apof(location, ds)
        marshall = mwdust.Marshall06(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=marshall)
        try:
            sf_marshall = apof(location, ds)
        except IndexError:
            sf_marshall = -numpy.ones_like(ds)
        sale = mwdust.Sale14(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=sale)
        try:
            sf_sale = apof(location, ds)
        except (TypeError, ValueError):
            sf_sale = -numpy.ones_like(ds)
        save_pickles(effselFile, distmods, sf_default, sf_jkz, sf_samples,
                     sf_zero, sf_drimmel, sf_marshall, sf_sale)
    else:
        with open(effselFile, 'rb') as savefile:
            distmods = pickle.load(savefile)
            sf_default = pickle.load(savefile)
            sf_jkz = pickle.load(savefile)
            sf_samples = pickle.load(savefile)
            sf_zero = pickle.load(savefile)
            sf_drimmel = pickle.load(savefile)
            sf_marshall = pickle.load(savefile)
            sf_sale = pickle.load(savefile)
    # Now plot
    bovy_plot.bovy_print(fig_height=3.)
    rc('text.latex',
       preamble=r'\usepackage{amsmath}' + '\n' + r'\usepackage{amssymb}' +
       '\n' + r'\usepackage{yfonts}')
    if _PLOTDIST:
        distmods = 10.**(distmods / 5 - 2.)
        xrange = [0., 12.]
        xlabel = r'$D\,(\mathrm{kpc})$'
        ylabel = r'$\textswab{S}(\mathrm{location},D)$'
    else:
        xrange = [7., 15.8],
        xlabel = r'$\mathrm{distance\ modulus}\ \mu$'
        ylabel = r'$\textswab{S}(\mathrm{location},\mu)$'
    line_default = bovy_plot.bovy_plot(distmods,
                                       sf_default,
                                       'b-',
                                       lw=_LW,
                                       zorder=12,
                                       xrange=xrange,
                                       xlabel=xlabel,
                                       yrange=[0., 1.2 * numpy.amax(sf_zero)],
                                       ylabel=ylabel)
    pyplot.fill_between(distmods,
                        sf_default-_EXAGGERATE_ERRORS\
                            *(sf_default-numpy.amin(sf_samples,axis=0)),
                        sf_default+_EXAGGERATE_ERRORS\
                            *(numpy.amax(sf_samples,axis=0)-sf_default),
                        color='0.65',zorder=0)
    line_jkz = bovy_plot.bovy_plot(distmods,
                                   sf_jkz,
                                   'g-.',
                                   lw=2. * _LW,
                                   overplot=True,
                                   zorder=13)
    line_zero = bovy_plot.bovy_plot(distmods,
                                    sf_zero,
                                    'k--',
                                    lw=_LW,
                                    overplot=True,
                                    zorder=7)
    line_drimmel = bovy_plot.bovy_plot(distmods,
                                       sf_drimmel,
                                       '-',
                                       color='gold',
                                       lw=_LW,
                                       overplot=True,
                                       zorder=8)
    line_marshall = bovy_plot.bovy_plot(distmods,
                                        sf_marshall,
                                        'r-',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=9)
    line_sale = bovy_plot.bovy_plot(distmods,
                                    sf_sale,
                                    'c-',
                                    lw=_LW,
                                    overplot=True,
                                    zorder=10)
    if location == 4378:
        pyplot.legend(
            (line_default[0], line_jkz[0], line_zero[0]),
            (r'$\mathrm{Green\ et\ al.\ (2015)}$',
             r'$\mathrm{Green\ et\ al.} + p(M_H)$',
             r'$\mathrm{zero\ extinction}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    elif location == 4312:
        pyplot.legend(
            (line_sale[0], line_marshall[0], line_drimmel[0]),
            (r'$\mathrm{Sale\ et\ al.\ (2014)}$',
             r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
             r'$\mathrm{Drimmel\ et\ al.\ (2003)}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    # Label
    lcen, bcen = apo.glonGlat(location)
    if numpy.fabs(bcen) < 0.1: bcen = 0.
    bovy_plot.bovy_text(r'$(l,b) = (%.1f,%.1f)$' % (lcen, bcen),
                        top_right=True,
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
def plot_effsel_location(location,plotname):
    # Setup selection function
    selectFile= '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile,'rb') as savefile:
            apo= pickle.load(savefile)
    else:
        # Setup selection function
        apo= apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile,apo)
    effselFile= '../savs/effselfunc-%i.sav' % location
    if not os.path.exists(effselFile):
        # Distances at which to calculate the effective selection function
        distmods= numpy.linspace(7.,15.5,301)
        ds= 10.**(distmods/5-2.)
        # Setup default effective selection function
        do_samples= True
        gd= mwdust.Green15(filter='2MASS H',load_samples=do_samples)
        apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=gd)
        sf_default= apof(location,ds)
        # Also calculate for a sample of MH
        data= get_rcsample()
        MH= data['H0']-data['RC_DM']
        MH= numpy.random.permutation(MH)[:1000]
        sf_jkz= apof(location,ds,MH=MH)
        # Go through the samples
        sf_samples= numpy.zeros((20,len(ds)))
        if do_samples:
            for ii in range(20):
                # Swap in a sample for bestfit in the Green et al. (2015) dmap
                gd.substitute_sample(ii)
                apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=gd)
                sf_samples[ii]= apof(location,ds)          
        zerodust= mwdust.Zero(filter='2MASS H')
        apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=zerodust)
        sf_zero= apof(location,ds)
        drimmel= mwdust.Drimmel03(filter='2MASS H')
        apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=drimmel)
        sf_drimmel= apof(location,ds)
        marshall= mwdust.Marshall06(filter='2MASS H')
        apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=marshall)
        try:
            sf_marshall= apof(location,ds)
        except IndexError:
            sf_marshall= -numpy.ones_like(ds)
        sale= mwdust.Sale14(filter='2MASS H')
        apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=sale)
        try:
            sf_sale= apof(location,ds)
        except (TypeError,ValueError):
            sf_sale= -numpy.ones_like(ds)
        save_pickles(effselFile,distmods,sf_default,sf_jkz,sf_samples,
                     sf_zero,sf_drimmel,sf_marshall,sf_sale)
    else:
        with open(effselFile,'rb') as savefile:
            distmods= pickle.load(savefile)
            sf_default= pickle.load(savefile)
            sf_jkz= pickle.load(savefile)
            sf_samples= pickle.load(savefile)
            sf_zero= pickle.load(savefile)
            sf_drimmel= pickle.load(savefile)
            sf_marshall= pickle.load(savefile)
            sf_sale= pickle.load(savefile)
    # Now plot
    bovy_plot.bovy_print(fig_height=3.)
    rc('text.latex', preamble=r'\usepackage{amsmath}'+'\n'
       +r'\usepackage{amssymb}'+'\n'+r'\usepackage{yfonts}')
    if _PLOTDIST:
        distmods= 10.**(distmods/5-2.)
        xrange= [0.,12.]
        xlabel=r'$D\,(\mathrm{kpc})$'
        ylabel=r'$\textswab{S}(\mathrm{location},D)$'
    else:
        xrange=[7.,15.8],
        xlabel=r'$\mathrm{distance\ modulus}\ \mu$'
        ylabel=r'$\textswab{S}(\mathrm{location},\mu)$'
    line_default= bovy_plot.bovy_plot(distmods,sf_default,
                                      'b-',lw=_LW,zorder=12,
                                      xrange=xrange,
                                      xlabel=xlabel,
                                      yrange=[0.,1.2*numpy.amax(sf_zero)],
                                      ylabel=ylabel)
    pyplot.fill_between(distmods,
                        sf_default-_EXAGGERATE_ERRORS\
                            *(sf_default-numpy.amin(sf_samples,axis=0)),
                        sf_default+_EXAGGERATE_ERRORS\
                            *(numpy.amax(sf_samples,axis=0)-sf_default),
                        color='0.65',zorder=0)
    line_jkz= bovy_plot.bovy_plot(distmods,sf_jkz,'g-.',lw=2.*_LW,
                                   overplot=True,zorder=13)
    line_zero= bovy_plot.bovy_plot(distmods,sf_zero,'k--',lw=_LW,
                                   overplot=True,zorder=7)
    line_drimmel= bovy_plot.bovy_plot(distmods,sf_drimmel,'-',color='gold',
                                      lw=_LW,overplot=True,zorder=8)
    line_marshall= bovy_plot.bovy_plot(distmods,sf_marshall,'r-',lw=_LW,
                                       overplot=True,
                        zorder=9)
    line_sale= bovy_plot.bovy_plot(distmods,sf_sale,'c-',lw=_LW,overplot=True,
                                   zorder=10)
    if location == 4378:
        pyplot.legend((line_default[0],line_jkz[0],line_zero[0]),
                      (r'$\mathrm{Green\ et\ al.\ (2015)}$',
                       r'$\mathrm{Green\ et\ al.} + p(M_H)$',
                       r'$\mathrm{zero\ extinction}$'),
                      loc='lower right',#bbox_to_anchor=(.91,.375),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False)
    elif location == 4312:
        pyplot.legend((line_sale[0],line_marshall[0],line_drimmel[0]),
                      (r'$\mathrm{Sale\ et\ al.\ (2014)}$',
                       r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
                       r'$\mathrm{Drimmel\ et\ al.\ (2003)}$'),
                      loc='lower right',#bbox_to_anchor=(.91,.375),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False)                      
    # Label
    lcen, bcen= apo.glonGlat(location)
    if numpy.fabs(bcen) < 0.1: bcen= 0.
    bovy_plot.bovy_text(r'$(l,b) = (%.1f,%.1f)$' % (lcen,bcen),
                        top_right=True,size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None