Ejemplo n.º 1
0
def plot_data_add_labels(
        radeconly=False,
        rvonly=False,
        color=sns.color_palette()[2],
        p1=(1, 2, 1),
        p2=(1, 2, 2),
        noxlabel_dec=False,
        noxlabel_vlos=False,
        noylabel=False,
):
    """plot_data_add_labels."""
    if noxlabel_dec or noylabel:
        nullfmt = NullFormatter()
    if not radeconly and not rvonly:
        plt.subplot(*p1)
    if not rvonly:
        if not noxlabel_dec:
            plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$")
        else:
            plt.gca().xaxis.set_major_formatter(nullfmt)
        if not noylabel:
            plt.ylabel(r"$\mathrm{Dec}\,(\mathrm{degree})$")
        else:
            plt.gca().yaxis.set_major_formatter(nullfmt)
        plt.xlim(250.0, 210.0)
        plt.ylim(-15.0, 9.0)
        bovy_plot._add_ticks()
        plt.errorbar(
            pos_radec[:, 0],
            pos_radec[:, 1],
            yerr=pos_radec[:, 2],
            ls="none",
            marker="o",
            color=color,
        )
    if radeconly:
        return None
    if not rvonly:
        plt.subplot(*p2)
    if not noxlabel_vlos:
        plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$")
    else:
        plt.gca().xaxis.set_major_formatter(nullfmt)
    if not noylabel:
        plt.ylabel(r"$V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$")
    else:
        plt.gca().yaxis.set_major_formatter(nullfmt)
    plt.xlim(250.0, 221.0)
    plt.ylim(-80.0, 0.0)
    bovy_plot._add_ticks()
    plt.errorbar(
        rvel_ra[rvel_ra[:, 0] > 230.5, 0],
        rvel_ra[rvel_ra[:, 0] > 230.5, 1],
        yerr=rvel_ra[rvel_ra[:, 0] > 230.5, 2],
        ls="none",
        marker="o",
        color=color,
    )

    return None
Ejemplo n.º 2
0
def plot_vr(plotfilename):
    #Read the APOGEE-RC data and pixelate it
    #APOGEE-RC
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    data= data[indx]
    #Get velocity field
    xmin, xmax= 5.5, 13.5
    dx= 1.
    pix= pixelize_sample.pixelXY(data,
                                 xmin=xmin,xmax=xmax,
                                 ymin=-dx/2.,ymax=dx/2.,
                                 dx=dx,dy=dx)
#                                 dx=_RCDX,dy=_RCDX)
    vr= pix.plot(lambda x: dvlosgal(x),
                 returnz=True,justcalc=True)
    vrunc= pix.plot(lambda x: dvlosgal(x),
                    func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                    returnz=True,justcalc=True)
    sr= pix.plot(lambda x: dvlosgal(x),
                 func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x))),
                 returnz=True,justcalc=True)
    srunc= pix.plot(lambda x: dvlosgal(x),
                    func=disperror,
                    returnz=True,justcalc=True)
    #print numpy.median(vr.flatten()[numpy.array([True,True,False,True,True,True,True,True,True],dtype='bool')])
    print vr.flatten()
    print vrunc.flatten()
    print sr.flatten()
    print srunc.flatten()
    rs= numpy.arange(xmin+dx/2.,xmax-dx/2.+0.00001,dx)
    print rs
    bovy_plot.bovy_print()
    srAxes= pyplot.axes([0.1,0.5,0.8,0.4])
    vrAxes= pyplot.axes([0.1,0.1,0.8,0.4])
    pyplot.sca(srAxes)
    pyplot.errorbar(rs,sr.flatten(),yerr=srunc.flatten(),
                    marker='o',ls='none',ms=6.,color='k')
    pyplot.xlim(0.,15.)
    pyplot.ylim(9.5,49.)
    #srAxes.set_yscale('log')
    bovy_plot._add_ticks(yticks=False)
    bovy_plot._add_axislabels(r'$ $',
                              r'$\sigma_R\,(\mathrm{km\,s}^{-1})$')
    nullfmt   = NullFormatter()         # no labels
    srAxes.xaxis.set_major_formatter(nullfmt)
    pyplot.sca(vrAxes)
    pyplot.errorbar(rs,vr.flatten(),yerr=vrunc.flatten(),
                    marker='o',ls='none',ms=6.,color='k')
    pyplot.plot([0.,20.],numpy.median(vr.flatten())*numpy.ones(2),'k--')
    bovy_plot._add_ticks()
    pyplot.xlim(0.,15.)
    pyplot.ylim(-14.,14.)
    bovy_plot._add_axislabels(r'$R\,(\mathrm{kpc})$',
                              r'$\langle V_R\rangle\,(\mathrm{km\,s}^{-1})$')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Ejemplo n.º 3
0
def showExamplegr(filename='../data/SDSSJ203817.37+003029.8.fits',
                constraints=None,basefilename='SDSSJ203817.37+003029.8'):
    """
    NAME:
       showExamplegr
    PURPOSE:
       show an example of a power-law structure function GP covariance function
       fit to an SDSS quasar for g and r
    INPUT:
       filename - filename with the data
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
    OUTPUT:
       writes several plots
    HISTORY:
       2010-08-11 - Written - Bovy (NYU)
    """
    file= fu.table_fields(filename)
    mjd_g= nu.array(file.mjd_g)/365.25
    g= nu.array(file.g)
    err_g= nu.array(file.err_g)
    mjd_r= nu.array(file.mjd_r)/365.25
    r= nu.array(file.r)
    err_r= nu.array(file.err_r)

    mask= (mjd_g != 0)*(g < 20.6)*(g > 19.7)#Adjust for non-g
    g= g[mask]
    g-= nu.mean(g)
    err_g= err_g[mask]
    mjd_g= mjd_g[mask]
    mjd_g-= nu.amin(mjd_g)
    meanErr_g= nu.mean(err_g)

    r= r[mask]
    r-= nu.mean(r)
    err_r= err_r[mask]
    mjd_r= mjd_r[mask]
    mjd_r-= nu.amin(mjd_r)
    meanErr_r= nu.mean(err_r)
    
    meanErr_gr= nu.mean(nu.sqrt(err_r**2.+err_g**2.))

    nu.random.seed(4)
    nGP=5
    nx=201
    params_mean= ()
    from powerlawSFgr import covarFunc
    params= {'logGamma': array([-9.27821954]), 'logGammagr': array([-19.85172122]), 'gamma': array([ 0.45932629]), 'gammagr': array([ 0.29784021])}
    cf= covarFunc(**params)
    params_covar= (cf)
    ndata= len(g)
    if constraints is None:
        listx= [(t,'g') for t in mjd_g]
        listx.extend([(t,'r') for t in mjd_r])
        listy= [m for m in g]
        listy.extend([m for m in r])
        listy= nu.array(listy)
        noise= [m for m in err_g]
        noise.extend([m for m in err_r])
        noise= nu.array(noise)
        trainSet= trainingSet(listx=listx,listy=listy,noise=noise)
        constraints= trainSet
    else:
        constraints= nu.array([])

    useconstraints= constraints
    txs= nu.linspace(-0.1,6.5,nx)
    xs= [(txs[ii],'g') for ii in range(nx)]
    xs.extend([(txs[ii],'r') for ii in range(nx)])
    GPsamples= eval_gp(xs,mean,covar,(),params_covar,nGP=nGP,constraints=useconstraints,tiny_cholesky=.000001)
    thismean= calc_constrained_mean(xs,mean,params_mean,covar,params_covar,useconstraints)
    thiscovar= calc_constrained_covar(xs,covar,params_covar,useconstraints)
    plot.bovy_print()
    pyplot.plot(txs,GPsamples[0,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_g,g,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    pyplot.plot(txs,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_full.ps')


    plot.bovy_print()
    pyplot.figure()
    pyplot.plot(txs,GPsamples[0,nx-1:-1],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_r,r,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,nx-1:-1],'-',color=str(0.25+ii*.5/(nGP-1)))
    pyplot.plot(txs,thismean[nx-1:-1],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_r,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$r-\langle r\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_fullr.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 0
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    colors= colors-nu.mean(colors)
    pyplot.plot(txs,colors,'-',color='0.25')
    if isinstance(constraints,trainingSet):
        plot.bovy_plot(mjd_g,g-r,'k.',zorder=5,ms=10,overplot=True)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        colors= colors-nu.mean(colors)
        pyplot.plot(txs,colors,'-',color=str(0.25+ii*.5/(nGP-1)))
    plotthismean= nu.zeros(nx)
    for ii in range(nx):
        plotthismean[ii]= thismean[ii]-thismean[ii+nx]
    pyplot.plot(txs,plotthismean,'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.18,yerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-r- \langle g - r \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    if isinstance(constraints,trainingSet):
        pyplot.ylim(-0.25,.25)
    else:
        pass #pyplot.ylim(-10.,10.)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_color.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 2
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    pyplot.plot(colors,GPsamples[ii,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(g-r,g,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        pyplot.plot(colors,GPsamples[ii,0:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    colors= nu.array([thismean[jj]-thismean[jj+nx] for jj in range(nx)])
    pyplot.plot(colors,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(.13,-0.3,yerr=meanErr_g,xerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$g-r-\langle g-r\rangle\ [\mathrm{mag}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-.2,.2)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_ggr.ps')

    return

    plot.bovy_print()
    pyplot.plot(xs,GPsamples[0,:],'-',color='0.25')
    if not constraints == []:
        plot.bovy_plot(mjd_g,g,'k.',zorder=5,ms=10,overplot=True)
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(xs,GPsamples[ii,:],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints == []:
        pyplot.errorbar(6.15,-0.1,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$m-\langle m\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(3,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_zoom.ps')


    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        pyplot.loglog(sc.arange(1.,len(GPsamples[ii,:])/2)*(xs[1]-xs[0]),
                      2.*sc.var(GPsamples[ii,:])-2.*sc.correlate(GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),"same")[1:len(GPsamples[ii,:])/2][::-1]/len(GPsamples[ii,:]),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(xs[1]-xs[0]),xs[len(xs)/2]]
    pyplot.loglog(xline,nu.exp(-3.02045715)*nu.array(xline)**(0.5868293),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfunc.ps')
Ejemplo n.º 4
0
def elements(elem,*args,**kwargs):
    """
    NAME:
       elements
    PURPOSE:
       make a plot of measurements of the elemental abundances vs. atomic number
    INPUT:
       elem - dictionary with elemental abundances relative to H
       wrtFe= (True) if True, plot elements wrt Fe on the left Y
       inclwrtH= (True) if True, indicate what X/H is on the right Y
       bovy_plot.bovy_plot args and kwargs
    OUTPUT:
       plot to output
    HISTORY:
       2015-03-10 - Written - Bovy (IAS)
    """
    # Process the input dictionary
    xs= []
    names= []
    ys= []
    wrtFe= kwargs.pop('wrtFe',True)
    for el in elem:
        try:
            xs.append(atomic_number(el))
        except KeyError: # ignore things that aren't known elements
            continue
        names.append(r'$\mathrm{%s}$' % el.lower().capitalize())
        try:
            if not wrtFe: raise KeyError
            ys.append(elem[el]-elem['Fe'])
        except KeyError:
            ys.append(elem[el])
            wrtFe= False
    xs= numpy.array(xs,dtype='int')
    ys= numpy.array(ys)
    names= numpy.array(names)
    # sort
    sindx= numpy.argsort(xs)
    xs= xs[sindx]
    ys= ys[sindx]
    names= names[sindx]
    # add second y axis?
    inclwrtH= kwargs.pop('inclwrtH',True)
    if wrtFe:
        feh= elem['Fe']
        ylabel= kwargs.pop('ylabel',r'$[\mathrm{X/Fe}]$')
    else:
        ylabel= kwargs.pop('ylabel',r'$[\mathrm{X/H}]$')
    if not kwargs.get('overplot',False):
        bovy_plot.bovy_print(fig_width=7.,fig_height=4.)
    basezorder= kwargs.pop('zorder',0)
    yrange=kwargs.pop('yrange',[-0.5,0.5])
    ls= kwargs.pop('ls','-')
    lw= kwargs.pop('lw',0.25)
    bovy_plot.bovy_plot(xs,ys,*args,
                        ylabel=ylabel,
                        xrange=[4,numpy.amax(xs)+2],
                        yrange=yrange,zorder=2+basezorder,ls=ls,lw=lw,
                        **kwargs)
    pyplot.xticks(list(xs),names)
    pyplot.tick_params(axis='x',labelsize=11.)
    if wrtFe and inclwrtH:
        bovy_plot.bovy_plot([4,numpy.amax(xs)+2],[0.,0.],'-',lw=2.,
                            color='0.65',overplot=True,zorder=basezorder)
        ax= pyplot.gca()
        ax2= ax.twinx()
        ax2.set_ylim(yrange[0]+feh,yrange[1]+feh)
        ax2.set_ylabel(r'$[\mathrm{X/H}]$')
        pyplot.sca(ax2)
        bovy_plot._add_ticks(yticks=True,xticks=False)
    return None
Ejemplo n.º 5
0
def plotSystematics(plotfilename):
    #hard-code these paths 
    savefilename= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc230_an_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    savefilename_vo250= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc250_an_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    savefilename_vo210= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc210_an_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    savefilename_zh200= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc230_an_zh200_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    savefilename_dvcm3= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc230_an_dlnvcdlnr-3_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    savefilename_dvcp3= '../pdfs_margvrvt_gl_hsz/realDFFit_dfeh0.1_dafe0.05_dpdiskplhalofixbulgeflatwgasalt_gridall_fixvc230_an_dlnvcdlnr3_margvrvt_staeckel_singles_bestr_rvssurf.sav'
    #Read surface densities
    if os.path.exists(savefilename):
        surffile= open(savefilename,'rb')
        surfrs= pickle.load(surffile)
        surfs= pickle.load(surffile)
        surferrs= pickle.load(surffile)
        kzs= pickle.load(surffile)
        kzerrs= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    #Read surface densities
    if os.path.exists(savefilename_vo250):
        surffile= open(savefilename_vo250,'rb')
        surfrs_vo250= pickle.load(surffile)
        surfs_vo250= pickle.load(surffile)
        surferrs_vo250= pickle.load(surffile)
        kzs_vo250= pickle.load(surffile)
        kzerrs_vo250= pickle.load(surffile)
        altsurfrs_vo250= pickle.load(surffile)
        altsurfs_vo250= pickle.load(surffile)
        altsurferrs_vo250= pickle.load(surffile)
        altkzs_vo250= pickle.load(surffile)
        altkzerrs_vo250= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    #Read surface densities
    if os.path.exists(savefilename_vo210):
        surffile= open(savefilename_vo210,'rb')
        surfrs_vo210= pickle.load(surffile)
        surfs_vo210= pickle.load(surffile)
        surferrs_vo210= pickle.load(surffile)
        kzs_vo210= pickle.load(surffile)
        kzerrs_vo210= pickle.load(surffile)
        altsurfrs_vo210= pickle.load(surffile)
        altsurfs_vo210= pickle.load(surffile)
        altsurferrs_vo210= pickle.load(surffile)
        altkzs_vo210= pickle.load(surffile)
        altkzerrs_vo210= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    #Read surface densities
    if os.path.exists(savefilename_zh200):
        surffile= open(savefilename_zh200,'rb')
        surfrs_zh200= pickle.load(surffile)
        surfs_zh200= pickle.load(surffile)
        surferrs_zh200= pickle.load(surffile)
        kzs_zh200= pickle.load(surffile)
        kzerrs_zh200= pickle.load(surffile)
        altsurfrs_zh200= pickle.load(surffile)
        altsurfs_zh200= pickle.load(surffile)
        altsurferrs_zh200= pickle.load(surffile)
        altkzs_zh200= pickle.load(surffile)
        altkzerrs_zh200= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    #Read surface densities
    if os.path.exists(savefilename_dvcm3):
        surffile= open(savefilename_dvcm3,'rb')
        surfrs_dvcm3= pickle.load(surffile)
        surfs_dvcm3= pickle.load(surffile)
        surferrs_dvcm3= pickle.load(surffile)
        kzs_dvcm3= pickle.load(surffile)
        kzerrs_dvcm3= pickle.load(surffile)
        altsurfrs_dvcm3= pickle.load(surffile)
        altsurfs_dvcm3= pickle.load(surffile)
        altsurferrs_dvcm3= pickle.load(surffile)
        altkzs_dvcm3= pickle.load(surffile)
        altkzerrs_dvcm3= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    #Read surface densities
    if os.path.exists(savefilename_dvcp3):
        surffile= open(savefilename_dvcp3,'rb')
        surfrs_dvcp3= pickle.load(surffile)
        surfs_dvcp3= pickle.load(surffile)
        surferrs_dvcp3= pickle.load(surffile)
        kzs_dvcp3= pickle.load(surffile)
        kzerrs_dvcp3= pickle.load(surffile)
        altsurfrs_dvcp3= pickle.load(surffile)
        altsurfs_dvcp3= pickle.load(surffile)
        altsurferrs_dvcp3= pickle.load(surffile)
        altkzs_dvcp3= pickle.load(surffile)
        altkzerrs_dvcp3= pickle.load(surffile)
        surffile.close()
    else:
        raise IOError("savefilename with surface-densities has to exist")
    if True:#options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif False:#options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    indx= numpy.isnan(surfrs)
    indx[50]= True
    indx[57]= True
    indx= True - indx
    surfrs= surfrs[indx]
    surfs= surfs[indx]
    surferrs= surferrs[indx]
    kzs= kzs[indx]
    kzerrs= kzerrs[indx]
    #vo250
    surfrs_vo250= surfrs_vo250[indx]
    surfs_vo250= surfs_vo250[indx]
    surferrs_vo250= surferrs_vo250[indx]
    kzs_vo250= kzs_vo250[indx]
    kzerrs_vo250= kzerrs_vo250[indx]
    altsurfrs_vo250= altsurfrs_vo250[indx]
    altsurfs_vo250= altsurfs_vo250[indx]
    altsurferrs_vo250= altsurferrs_vo250[indx]
    altkzs_vo250= altkzs_vo250[indx]
    altkzerrs_vo250= altkzerrs_vo250[indx]
    #vo210
    surfrs_vo210= surfrs_vo210[indx]
    surfs_vo210= surfs_vo210[indx]
    surferrs_vo210= surferrs_vo210[indx]
    kzs_vo210= kzs_vo210[indx]
    kzerrs_vo210= kzerrs_vo210[indx]
    altsurfrs_vo210= altsurfrs_vo210[indx]
    altsurfs_vo210= altsurfs_vo210[indx]
    altsurferrs_vo210= altsurferrs_vo210[indx]
    altkzs_vo210= altkzs_vo210[indx]
    altkzerrs_vo210= altkzerrs_vo210[indx]
    #zh200
    surfrs_zh200= surfrs_zh200[indx]
    surfs_zh200= surfs_zh200[indx]
    surferrs_zh200= surferrs_zh200[indx]
    kzs_zh200= kzs_zh200[indx]
    kzerrs_zh200= kzerrs_zh200[indx]
    altsurfrs_zh200= altsurfrs_zh200[indx]
    altsurfs_zh200= altsurfs_zh200[indx]
    altsurferrs_zh200= altsurferrs_zh200[indx]
    altkzs_zh200= altkzs_zh200[indx]
    altkzerrs_zh200= altkzerrs_zh200[indx]
    #dvc-3
    surfrs_dvcm3= surfrs_dvcm3[indx]
    surfs_dvcm3= surfs_dvcm3[indx]
    surferrs_dvcm3= surferrs_dvcm3[indx]
    kzs_dvcm3= kzs_dvcm3[indx]
    kzerrs_dvcm3= kzerrs_dvcm3[indx]
    altsurfrs_dvcm3= altsurfrs_dvcm3[indx]
    altsurfs_dvcm3= altsurfs_dvcm3[indx]
    altsurferrs_dvcm3= altsurferrs_dvcm3[indx]
    altkzs_dvcm3= altkzs_dvcm3[indx]
    altkzerrs_dvcm3= altkzerrs_dvcm3[indx]
    #dvc+3
    surfrs_dvcp3= surfrs_dvcp3[indx]
    surfs_dvcp3= surfs_dvcp3[indx]
    surferrs_dvcp3= surferrs_dvcp3[indx]
    kzs_dvcp3= kzs_dvcp3[indx]
    kzerrs_dvcp3= kzerrs_dvcp3[indx]
    altsurfrs_dvcp3= altsurfrs_dvcp3[indx]
    altsurfs_dvcp3= altsurfs_dvcp3[indx]
    altsurferrs_dvcp3= altsurferrs_dvcp3[indx]
    altkzs_dvcp3= altkzs_dvcp3[indx]
    altkzerrs_dvcp3= altkzerrs_dvcp3[indx]
    fehs= fehs[indx]
    afes= afes[indx]
    #Plot
    bovy_plot.bovy_print(fig_height=8.,fig_width=7.)
    dx= 0.8/5.
    #vo250
    left, bottom, width, height= 0.1, 0.9-dx, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot(surfrs,numpy.log(altsurfs_vo250/surfs),'ko',
                        overplot=True,
                        zorder=10)
    pyplot.errorbar(surfrs,numpy.log(altsurfs_vo250/surfs),
                    yerr=surferrs/surfs,
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=5,
                    color='k')
    pyplot.plot([4.,10.],
                [numpy.log((250./230.)**2.),numpy.log((250./230.)**2.)],'--',
                color='0.5',lw=2.)
    pyplot.plot([4.,10.],
                [0.,0.],'-',
                color='0.5',lw=2.)
    bovy_plot.bovy_text(8.5,0.18,r'$V_c = 250\,\mathrm{km\,s}^{-1}$',
                        size=14.)
    #bovy_plot.bovy_plot(surfrs,numpy.log(altkzs_vo250/kzs),'kd',
    #                    overplot=True,color='0.35',
    #                    zorder=10)
    thisax= pyplot.gca()
    nullfmt   = NullFormatter()         # no labels
    thisax.xaxis.set_major_formatter(nullfmt)
    thisax.set_ylim(-0.29,0.29)
    thisax.set_xlim(4.,10.)
    bovy_plot._add_ticks()
    #vo210
    left, bottom, width, height= 0.1, 0.9-2.*dx, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot(surfrs,numpy.log(altsurfs_vo210/surfs),'ko',
                        overplot=True,
                        zorder=10)
    pyplot.errorbar(surfrs,numpy.log(altsurfs_vo210/surfs),
                    yerr=surferrs/surfs,
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=5,
                    color='k')
    pyplot.plot([4.,10.],
                [numpy.log((210./230.)**2.),numpy.log((210./230.)**2.)],'--',
                color='0.5',lw=2.)
    pyplot.plot([4.,10.],
                [0.,0.],'-',
                color='0.5',lw=2.)
    bovy_plot.bovy_text(8.5,0.18,r'$V_c = 210\,\mathrm{km\,s}^{-1}$',
                        size=14.)
    #bovy_plot.bovy_plot(surfrs,numpy.log(altkzs_vo210/kzs),'kd',
    #                    overplot=True,color='0.35',
    #                    zorder=10)
    thisax= pyplot.gca()
    nullfmt   = NullFormatter()         # no labels
    thisax.xaxis.set_major_formatter(nullfmt)
    thisax.set_ylim(-0.29,0.29)
    thisax.set_xlim(4.,10.)
    bovy_plot._add_ticks()
    #zh200
    left, bottom, width, height= 0.1, 0.9-3.*dx, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot(surfrs,numpy.log(altsurfs_zh200/surfs),'ko',
                        overplot=True,
                        zorder=10)
    pyplot.errorbar(surfrs,numpy.log(altsurfs_zh200/surfs),
                    yerr=surferrs/surfs,
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=5,
                    color='k')
    pyplot.plot([4.,10.],
                [0.,0.],'-',
                color='0.5',lw=2.)
    bovy_plot.bovy_text(8.5,0.18,r'$z_h = 200\,\mathrm{pc}$',
                        size=14.)
    #bovy_plot.bovy_plot(surfrs,numpy.log(altkzs_zh200/kzs),'kd',
    #                    overplot=True,color='0.35',
    #                    zorder=10)
    thisax= pyplot.gca()
    nullfmt   = NullFormatter()         # no labels
    thisax.xaxis.set_major_formatter(nullfmt)
    thisax.set_ylim(-0.29,0.29)
    thisax.set_xlim(4.,10.)
    pyplot.ylabel(r'$\ln \Sigma_{1.1}^{\mathrm{alt}} / \Sigma_{1.1}^{\mathrm{fid}}$')
    bovy_plot._add_ticks()
    #dvcm3
    left, bottom, width, height= 0.1, 0.9-4.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)    
    bovy_plot.bovy_plot(surfrs,numpy.log(altsurfs_dvcm3/surfs),'ko',
                        overplot=True,
                        zorder=10)
    pyplot.errorbar(surfrs,numpy.log(altsurfs_dvcm3/surfs),
                    yerr=surferrs/surfs,
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=5,
                    color='k')
    xs= numpy.linspace(4.,10.,1001)
    ys= numpy.log((69.*numpy.exp(-(xs-8.)/2.5)+67*(8./xs)**2.*(-0.1))/
                  (69.*numpy.exp(-(xs-8.)/2.5)))
    pyplot.plot(xs,ys,'--',color='0.5',lw=2.)
    pyplot.plot([4.,10.],
                [0.,0.],'-',
                color='0.5',lw=2.)
    bovy_plot.bovy_plot(surfrs,numpy.log(altkzs_dvcm3/kzs),'kd',
                        overplot=True,color='0.35',
                        xrange=[4.,10.],
                        yrange=[-0.41,0.41],zorder=10)
    bovy_plot.bovy_text(7.65,0.18,
                        r'$\mathrm{d} \ln V_c(R_0) / \mathrm{d} \ln R = -0.1$',
                        size=14.)
    thisax= pyplot.gca()
    thisax.set_ylim(-0.29,0.29)
    pyplot.xlim(4.,10.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    thisax.xaxis.set_major_formatter(nullfmt)
    #dvcp3
    left, bottom, width, height= 0.1, 0.9-5.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)    
    bovy_plot.bovy_plot(surfrs,numpy.log(altsurfs_dvcp3/surfs),'ko',
                        overplot=True,
                        zorder=10)
    pyplot.errorbar(surfrs,numpy.log(altsurfs_dvcp3/surfs),
                    yerr=surferrs/surfs,
                    elinewidth=1.,capsize=3,
                    linestyle='none',zorder=5,
                    color='k')
    xs= numpy.linspace(4.,10.,1001)
    ys= numpy.log((69.*numpy.exp(-(xs-8.)/2.5)+67*(8./xs)**2.*(+0.1))/
                  (69.*numpy.exp(-(xs-8.)/2.5)))
    pyplot.plot(xs,ys,'--',color='0.5',lw=2.)
    pyplot.plot([4.,10.],
                [0.,0.],'-',
                color='0.5',lw=2.)
    bovy_plot.bovy_plot(surfrs,numpy.log(altkzs_dvcp3/kzs),'kd',
                        overplot=True,color='0.35',
                        xrange=[4.,10.],
                        yrange=[-0.41,0.41],zorder=10)
    bovy_plot.bovy_text(7.65,0.18,
                        r'$\mathrm{d} \ln V_c(R_0) / \mathrm{d} \ln R = 0.1$',
                        size=14.)
    thisax= pyplot.gca()
    thisax.set_ylim(-0.29,0.29)
    pyplot.xlim(4.,10.)
    bovy_plot._add_ticks()
    pyplot.xlabel(r'$R\ (\mathrm{kpc})$')
    bovy_plot.bovy_end_print(plotfilename)
Ejemplo n.º 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)
Ejemplo n.º 7
0
def plot_nonaxi(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    # Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        validfeh=options.indivfeh,  # if indivfeh, we need validfeh
        cutmultiples=options.cutmultiples,
        jkmax=options.jkmax,
    )
    # data= data[0:20]
    # HACK
    indx = data["J0MAG"] - data["K0MAG"] < 0.5
    data["J0MAG"][indx] = 0.5 + data["K0MAG"][indx]
    indx = data["GLON"] <= 30.0
    data["GLON"][indx] = 30.05  # Hack because the non-axi models don't go below Ro/2
    # Cut outliers
    # data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    # Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, "rb")
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            # Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data["LOCATION"]))
            iso = []
            for ii in range(len(locs)):
                indx = data["LOCATION"] == locs[ii]
                locl = numpy.mean(data["GLON"][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, marginalizefeh=True, glon=locl)
                )
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, expsfh=options.expsfh)
        if options.dwarf:
            iso = [iso, isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, dwarf=True, expsfh=options.expsfh)]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, "wb")
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data["H0MAG"][ii] - dm
        if options.indivfeh:
            # Find closest Z
            thisZ = isodist.FEH2Z(data[ii]["FEH"])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        elif options.varfeh:
            # Find correct iso
            indx = locl == data[ii]["LOCATION"]
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF, _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data["H0MAG"][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    else:
        logpisodwarf = None
    """ #Does not matter anyway
    #clean logpiso
    dataindx= []
    for ii in range(len(data)):
        thislogpiso= logpiso[ii,:]-logsumexp(logpiso[ii,:])
        if numpy.all(thislogpiso == 0.): dataindx.append(False)
        else: dataindx.append(True)
    dataindx= numpy.array(dataindx,dtype='bool')
    data= data[dataindx]
    logpiso= logpiso[dataindx,:]
    logpisodwarf= logpisodwarf[dataindx,:]
    """
    # Calculate data means etc.
    # Calculate means
    locations = list(set(data["LOCATION"]))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = data["LOCATION"] == locations[ii]
        l_plate[ii] = numpy.mean(data["GLON"][indx])
        avg_plate[ii] = numpy.mean(data["VHELIO"][indx])
        sig_plate[ii] = numpy.std(data["VHELIO"][indx])
        siga_plate[ii] = numpy.std(data["VHELIO"][indx]) / numpy.sqrt(numpy.sum(indx))
    # Calculate plate means and variances from the model
    # Load initial parameters from file
    savefile = open(args[0], "rb")
    params = pickle.load(savefile)
    savefile.close()
    # First calculate fiducial model
    if not options.dwarf:
        logpisodwarf = None
    avg_plate_model_fid = calc_model(params, options, data, logpiso, logpisodwarf, df, nlocs, locations, iso)
    print l_plate, avg_plate_model_fid
    # Plot everything
    bovy_plot.bovy_print(fig_height=6.0, fig_width=7.0)
    dx = 0.8 / 5.0
    left, bottom, width, height = 0.1, 0.9 - dx, 0.8, dx
    axTop = pyplot.axes([left, bottom, width, height])
    allaxes = [axTop]
    fig = pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "ko", overplot=True)
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{fiducial}$", top_right=True, size=14.0)
    thisax = pyplot.gca()
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Second is bar
    print "Reading bar file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, 0.0)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 2.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{bar}$", top_right=True, size=14.0)
    # pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Third is spiral
    print "Reading spiral file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/spiral/spiral_rect_vr_51_101.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, 0.0)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 3.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{spiral}$", top_right=True, size=14.0)
    pyplot.ylabel(r"$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}} \ [\mathrm{km\ s}^{-1}]$")
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    # Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, 0.0)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 4.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{elliptical}$", top_right=True, size=14.0)
    # pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, -45.0 * _DEGTORAD)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 5.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{elliptical}$", top_right=True, size=14.0)
    # pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r"$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$")
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Ejemplo n.º 8
0
def showExampleDRW(filename='../data/SDSSJ203817.37+003029.8.fits',
                constraints=None,basefilename='SDSSJ203817.37+003029.8'):
    """
    NAME:
       showExampleDRW
    PURPOSE:
       show an example of a pDRW structure function GP covariance function
       fit to an SDSS quasar for g and r
    INPUT:
       filename - filename with the data
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
    OUTPUT:
       writes several plots
    HISTORY:
       2010-08-11 - Written - Bovy (NYU)
    """
    file= fu.table_fields(filename)
    mjd_g= nu.array(file.mjd_g)/365.25
    g= nu.array(file.g)
    err_g= nu.array(file.err_g)
    mjd_r= nu.array(file.mjd_r)/365.25
    r= nu.array(file.r)
    err_r= nu.array(file.err_r)

    mask= (mjd_g != 0)*(g < 20.6)*(g > 19.7)#Adjust for non-g
    g= g[mask]
    g-= nu.mean(g)
    err_g= err_g[mask]
    mjd_g= mjd_g[mask]
    mjd_g-= nu.amin(mjd_g)
    meanErr_g= nu.mean(err_g)

    r= r[mask]
    r-= nu.mean(r)
    err_r= err_r[mask]
    mjd_r= mjd_g#mjd_r[mask]
    #mjd_r-= nu.amin(mjd_r)
    meanErr_r= nu.mean(err_r)
    
    meanErr_gr= nu.mean(nu.sqrt(err_r**2.+err_g**2.))

    nu.random.seed(4)
    nGP=5
    nx=201
    params_mean= ()
    from drwcross import covarFunc
    #params= {'logS': array([1.63714183]), 'logtau': array([0.]), 'logB': array([ 2.32288434])}
    #params= {'logtau': array([-1.36399325]), 'logB': array([-519.45950737]), 'logS': array([-3.51531852])}
    params= {'logS': array([-1.08795813]), 'logtau': array([ 1.2790154]), 'logB': array([-1.01029709]), 'logC': array([-79.88349478]), 'gammagr': array([ 7.90536799]), 'logGammagr': array([ 2.8001978])}
    cf= covarFunc(**params)
    params_covar= (cf)
    ndata= len(g)
    if constraints is None:
        listx= [(t,'g') for t in mjd_g]
        listx.extend([(t,'r') for t in mjd_r])
        listy= [m for m in g]
        listy.extend([m for m in r])
        listy= nu.array(listy)
        noise= [m for m in err_g]
        noise.extend([m for m in err_r])
        noise= nu.array(noise)
        trainSet= trainingSet(listx=listx,listy=listy,noise=noise)
        constraints= trainSet
    else:
        constraints= nu.array([])

    useconstraints= constraints
    txs= nu.linspace(-0.1,6.5,nx)
    xs= [(txs[ii],'g') for ii in range(nx)]
    xs.extend([(txs[ii],'r') for ii in range(nx)])
    GPsamples= eval_gp(xs,mean,covar,(),params_covar,nGP=nGP,constraints=useconstraints,tiny_cholesky=.000001)
    thismean= calc_constrained_mean(xs,mean,params_mean,covar,params_covar,useconstraints)
    thiscovar= calc_constrained_covar(xs,covar,params_covar,useconstraints)
    plot.bovy_print()
    pyplot.plot(txs,GPsamples[0,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_g,g,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    pyplot.plot(txs,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_full.ps')


    plot.bovy_print()
    pyplot.figure()
    pyplot.plot(txs,GPsamples[0,nx-1:-1],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_r,r,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,nx-1:-1],'-',color=str(0.25+ii*.5/(nGP-1)))
    pyplot.plot(txs,thismean[nx-1:-1],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_r,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$r-\langle r\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_fullr.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 0
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    colors= colors-nu.mean(colors)
    pyplot.plot(txs,colors,'-',color='0.25')
    if isinstance(constraints,trainingSet):
        plot.bovy_plot(mjd_g,g-r,'k.',zorder=5,ms=10,overplot=True)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        colors= colors-nu.mean(colors)
        pyplot.plot(txs,colors,'-',color=str(0.25+ii*.5/(nGP-1)))
    plotthismean= nu.zeros(nx)
    for ii in range(nx):
        plotthismean[ii]= thismean[ii]-thismean[ii+nx]
    pyplot.plot(txs,plotthismean,'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.18,yerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-r- \langle g - r \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    if isinstance(constraints,trainingSet):
        pyplot.ylim(-0.25,.25)
    else:
        pass #pyplot.ylim(-10.,10.)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_color.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 2
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    pyplot.plot(colors,GPsamples[ii,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(g-r,g,'k.',zorder=5,ms=10)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        pyplot.plot(colors,GPsamples[ii,0:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    colors= nu.array([thismean[jj]-thismean[jj+nx] for jj in range(nx)])
    pyplot.plot(colors,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(.13,-0.3,yerr=meanErr_g,xerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$g-r-\langle g-r\rangle\ [\mathrm{mag}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-.2,.2)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_ggr.ps')

    return
Ejemplo n.º 9
0
def plot_nonaxi(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        cutmultiples=options.cutmultiples,
        jkmax=options.jkmax)
    #data= data[0:20]
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    indx = (data['GLON'] <= 30.)
    data['GLON'][
        indx] = 30.05  #Hack because the non-axi models don't go below Ro/2
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
        if options.dwarf:
            iso = [
                iso,
                isomodel.isomodel(imfmodel=options.imfmodel,
                                  Z=options.Z,
                                  dwarf=True,
                                  expsfh=options.expsfh)
            ]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, 'wb')
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data['H0MAG'][ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) +
                                    (data['J0MAG'] - data['K0MAG'])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF,
                                 _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data['H0MAG'][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) +
                                         (data['J0MAG'] - data['K0MAG'])[ii],
                                         mh)
    else:
        logpisodwarf = None
    """ #Does not matter anyway
    #clean logpiso
    dataindx= []
    for ii in range(len(data)):
        thislogpiso= logpiso[ii,:]-logsumexp(logpiso[ii,:])
        if numpy.all(thislogpiso == 0.): dataindx.append(False)
        else: dataindx.append(True)
    dataindx= numpy.array(dataindx,dtype='bool')
    data= data[dataindx]
    logpiso= logpiso[dataindx,:]
    logpisodwarf= logpisodwarf[dataindx,:]
    """
    #Calculate data means etc.
    #Calculate means
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
        avg_plate[ii] = numpy.mean(data['VHELIO'][indx])
        sig_plate[ii] = numpy.std(data['VHELIO'][indx])
        siga_plate[ii] = numpy.std(data['VHELIO'][indx]) / numpy.sqrt(
            numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile = open(args[0], 'rb')
    params = pickle.load(savefile)
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf = None
    avg_plate_model_fid = calc_model(params, options, data, logpiso,
                                     logpisodwarf, df, nlocs, locations, iso)
    print l_plate, avg_plate_model_fid
    #Plot everything
    bovy_plot.bovy_print(fig_height=6., fig_width=7.)
    dx = 0.8 / 5.
    left, bottom, width, height = 0.1, 0.9 - dx, 0.8, dx
    axTop = pyplot.axes([left, bottom, width, height])
    allaxes = [axTop]
    fig = pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0., 360.], [0., 0.], '-', color='0.5', overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$', top_right=True, size=14.)
    thisax = pyplot.gca()
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Second is bar
    print "Reading bar file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 2. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{bar}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Third is spiral
    print "Reading spiral file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/spiral/spiral_rect_vr_51_101.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 3. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{spiral}$', top_right=True, size=14.)
    pyplot.ylabel(
        r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}} \ [\mathrm{km\ s}^{-1}]$'
    )
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    #Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 4. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{elliptical}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, -45. * _DEGTORAD)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 5. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{elliptical}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Ejemplo n.º 10
0
def plot_internalcomparison(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    #data= data[0:20]
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        if options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:    
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Calculate data means etc.
    #Calculate means
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    if not options.index is None:
        params= params[options.index]
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf= None
    avg_plate_model_fid= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #Plot everything
    bovy_plot.bovy_print(fig_height=10.,fig_width=7.)
    dx= 0.8/9.
    left, bottom, width, height= 0.1, 0.9, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'ko',overplot=True)
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$',top_right=True,size=14.)
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Second is Dehnen
    fid_dfmodel= options.dfmodel
    options.dfmodel= 'dehnen'
    avg_plate_model= avg_plate_model_fid 
    #avg_plate_model= calc_model(params,options,data,
    #                            logpiso,logpisodwarf,
    #                            df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{Dehnen\ DF}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Third = hR= 2. kpc
    fid_hr= options.hr
    options.dfmodel= fid_dfmodel
    options.hr= 2.
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-2.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$h_R = 2\ \mathrm{kpc}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Fourth = hR= 4. kpc
    options.dfmodel= fid_dfmodel
    options.hr= 4.
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-3.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$h_R = 4\ \mathrm{kpc}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Fifth = hs= 5. kpc
    fid_hs= options.hs
    options.hr= fid_hr
    options.hs= 5.
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-4.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$h_\sigma = 5\ \mathrm{kpc}$',top_right=True,size=14.)
    pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}\ [\mathrm{km\ s}^{-1}]$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Sixth: multiple pops
    options.hs= fid_hs
    options.dfmodel= 'multiplepops'
    fid_params=copy.copy(params)
    params[2]= -1.8
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-5.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{Multiple\ populations,\ SFR} = \exp\left( -t/8\ \mathrm{Gyr}\right)$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Seventh: cut multiples
    options.dfmodel= fid_dfmodel
    params= fid_params
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=True,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                              +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    l_plate_fid= l_plate
    avg_plate_fid= avg_plate
    siga_plate_fid= siga_plate
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-6.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate_fid,
                        avg_plate_fid-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate_fid,avg_plate_fid-avg_plate_model_fid,
                    yerr=siga_plate_fid,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{Multiple\ visit\ dispersion} < 1\ \mathrm{km\ s}^{-1}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Eight b=2
    options.dfmodel= fid_dfmodel
    params= fid_params
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=10.,
                        meanb=4.,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                              +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-7.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate_fid,
                        avg_plate_fid-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate_fid,avg_plate_fid-avg_plate_model_fid,
                    yerr=siga_plate_fid,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$b = 4^\circ\ \mathrm{fields}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Nintht b=-2
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=10.,
                        meanb=-4.,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-8.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate_fid,
                        avg_plate_fid-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate_fid,avg_plate_fid-avg_plate_model_fid,
                    yerr=siga_plate_fid,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$b = -4^\circ\ \mathrm{fields}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Ejemplo n.º 11
0
 def plot_popmass(self):
     """
     NAME:
        plot_popmass
     PURPOSE:
        plot the stellar-population mass for each RC star
     INPUT:
         bovy_plot.bovy_plot **kwargs
     OUTPUT:
        bovy_plot.bovy_plot output
     HISTORY:
        2014-02-28 - Written in this form - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     fehs= numpy.linspace(-1.,0.5,101)
     lages= self._coarselages
     plotthis= numpy.empty((len(fehs),len(lages)))
     for ii in range(len(fehs)):
         for jj in range(len(lages)):
             plotthis[ii,jj]= self.popmass(fehs[ii],lages[jj])
     fig= pyplot.gcf()
     left, bottom, width, height= 0.1, 0.1, 0.8, 0.6
     axBottom= pyplot.axes([left,bottom,width,height])
     fig.sca(axBottom)
     xlimits= [fehs[0],fehs[-1]]
     dlages= (lages[1]-lages[0])
     ylimits= [lages[0]-dlages,lages[-1]+dlages]
     vmin, vmax= 0.,50000.
     vmin2, vmax2= 0.,25000.
     zlabel= r'$\mathrm{Stellar\ population\ mass\ per\ RC\ star}\,(M_\odot)$'
     xlabel= r'$[\mathrm{Fe/H}]\,(\mathrm{dex})$'
     out= bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                                xrange=xlimits,
                                yrange=ylimits,
                                vmin=vmin,vmax=vmax,
                                interpolation='nearest',
                                colorbar=True,
                                shrink=.9,
                                zlabel=zlabel,
                                overplot=True)
     extent= xlimits+ylimits
     pyplot.axis(extent)
     bovy_plot._add_axislabels(xlabel,
                               r'$\log_{10}\,\mathrm{Age} / 1\,\mathrm{Gyr}$')
     bovy_plot._add_ticks()
     left, bottom, width, height= 0.1, 0.68, 0.64, 0.2
     axTop= pyplot.axes([left,bottom,width,height])
     fig.sca(axTop)
     #Plot the average over SFH
     lages= numpy.linspace(-1.,1.,16)
     mtrend= numpy.zeros(len(self._zs))
     exppage= 10.**self._coarselages*numpy.exp((10.**(self._coarselages+2.))/800.) #e.g., Binney (2010)
     exexppage= 10.**self._coarselages*numpy.exp((10.**(self._coarselages+2.))/100.) #e.g., Binney (2010)
     page= 10.**self._coarselages
     plotthis= self._coarsemass[:-1,:]/self._omega[:-1,:]
     mtrend= 1./(numpy.sum(page*1./plotthis,axis=1)/numpy.sum(page))
     expmtrend= 1./(numpy.sum(exppage*1./plotthis,axis=1)/numpy.sum(exppage))
     exexpmtrend= 1./(numpy.sum(exexppage*1./plotthis,axis=1)/numpy.sum(exexppage))
     fehs= isodist.Z2FEH(self._zs[:-1],zsolar=zsolar())
     pyplot.plot(fehs,mtrend,'k-')
     pyplot.plot(fehs,expmtrend,'k--')
     pyplot.plot(fehs,exexpmtrend,'k-.')
     pyplot.ylim(vmin2,vmax2)
     pyplot.xlim(xlimits[0],xlimits[1])
     nullfmt   = NullFormatter()         # no labels
     thisax= pyplot.gca()
     thisax.xaxis.set_major_formatter(nullfmt)
     bovy_plot._add_ticks()
     return out
def bovy_metallicity_gradient(plotfilename,savefilename,largewave=False):
    # First read the RC catalog and cut it to stars near the plane
    data= apread.rcsample()
    if _HIZ:
        indx= (numpy.fabs(data['RC_GALZ']) > 0.6)*(data['METALS'] > -1000.)
    else:
        indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    data= data[indx]
    # Now go through bins in R
    Rmin, Rmax, dR= 5.5, 13., 0.1
    Rs= numpy.arange(Rmin+dR/2.,Rmax+dR/2.,dR)
    nR= len(Rs)
    # Read one spectrum to learn the size of the array
    spec, hdr= apread.aspcapStar(4424,'2M00025587+5849278',ext=1)
    if os.path.exists(savefilename):
        # Reload previously calculated median spectrum
        savefile= open(savefilename,'rb')
        median_spec= pickle.load(savefile)
        savefile.close()
    else:
        median_spec= numpy.zeros((len(spec),nR))
        # Now run through all the spectra and get the median
        tot= 0
        for ii in range(nR):
            indx= (data['RC_GALR'] >= Rs[ii]-dR/2.)\
                *(data['RC_GALR'] < Rs[ii]+dR/2.)
            tot+= numpy.sum(indx)
            print numpy.sum(indx), tot
            allspec= numpy.empty((len(spec),numpy.sum(indx)))
            for jj in range(numpy.sum(indx)):
                specdata= \
                    apread.aspcapStar(data['LOCATION_ID'][indx][jj],
                                      data['APOGEE_ID'][indx][jj],
                                      ext=1,header=False)
                specerr= \
                    apread.aspcapStar(data['LOCATION_ID'][indx][jj],
                                      data['APOGEE_ID'][indx][jj],
                                      ext=2,header=False)
                allspec[:,jj]= specdata
                allspec[specerr > 1.,jj]= numpy.nan
                allspec[specerr == 0.,jj]= numpy.nan
            for jj in range(len(spec)):
                if _PLOTMAD:
                    median_spec[jj,ii]= \
                        numpy.median(numpy.fabs(allspec[jj,True-numpy.isnan(allspec[jj,:])]-numpy.median(allspec[jj,True-numpy.isnan(allspec[jj,:])])))
                else:
                    median_spec[jj,ii]= \
                        numpy.median(allspec[jj,
                                             True-numpy.isnan(allspec[jj,:])])
        save_pickles(savefilename,median_spec)
    # Wavelengths
    wave= 10.**(numpy.arange(hdr['CRVAL1'],
                             hdr['CRVAL1']+len(spec)*hdr['CDELT1'],
                             hdr['CDELT1']))
    # Normalization, first calculate the spectrum near Ro
    absmax= 0.98
    absindx= (median_spec > absmax)*\
        numpy.tile(( (wave < 15929.)+(wave > 15929.5) ),(nR,1)).T
    median_spec[absindx]= absmax #focus on real absorption lines, except for V
    rospec= numpy.zeros(len(spec))
    roindx= numpy.argmin(numpy.fabs(Rs-8.))
    for jj in range(len(spec)):
        rospec[jj]= numpy.median(median_spec[jj,roindx-3:roindx+4])
    if not _PLOTMAD:
        # Normalization by spectrum at Ro
        roindx= numpy.argmin(numpy.fabs(Rs-8.))
        for jj in range(nR):
            # Normalize by the solar radius
            median_spec[:,jj]/= rospec
        median_spec-= 1. 
        vmin=-0.035
        vmax=0.035
        vmin=-0.04
        vmax=0.04
    # Now plot
    if False:
        startindx, endindx= 3652, 4100#3915
    if largewave:
        startindx, endindx= 7000,7600#7375, 7889
    else:
        startindx, endindx= 2500, 3100
    # Make N separate plots showing different wavelength regions
    bovy_plot.bovy_print(fig_width=8.4,fig_height=3.,
                         axes_labelsize=10,text_fontsize=9,legend_fontsize=9,
                         xtick_labelsize=8,ytick_labelsize=8)
    startindxs= [322,1790,2707,3852,4738,5820,7187] #DIB is at 818
    endindxs= [590,1940,2857,4021,5068,5955,7400]
    nregions= len(startindxs)
    # Calculate the width of the plot
    dx= numpy.array([endindxs[ii]-startindxs[ii] for ii in range(nregions)],
                    dtype='float')
    specdx= numpy.sum(dx) # for later
    dx/= numpy.sum(dx)
    totdx= 0.85
    skipdx= 0.015
    dx*= (totdx-(nregions-1)*skipdx)
    for ii in range(nregions):
        # Setup the axes
        if ii == 0:
            left, bottom, width, height= 0.1, 0.1, dx[ii],0.8
        else:
            left, bottom, width, height= 0.1+numpy.cumsum(dx)[ii-1]+skipdx*ii,\
                0.1, dx[ii], 0.8
        thisax= pyplot.axes([left,bottom,width,height])
        fig= pyplot.gcf()
        fig.sca(thisax)
        startindx, endindx= startindxs[ii], endindxs[ii]
        aspect= (hdr['CRVAL1']+(endindx-0.5)*hdr['CDELT1']-hdr['CRVAL1']-(startindx-0.5)*hdr['CDELT1'])\
            /(Rs[-1]+dR/2.-Rs[0]+dR/2.)
        aspect/= dx[ii]*5.
        yrange= [Rs[0]-dR/2.,Rs[-1]+dR/2.]
        xrange=[hdr['CRVAL1']+(startindx-0.5)*hdr['CDELT1']-numpy.log10(_LAMBDANORM),\
                    hdr['CRVAL1']+(endindx-0.5)*hdr['CDELT1']-numpy.log10(_LAMBDANORM)]
        extent= [xrange[0],xrange[1],yrange[0],yrange[1]]
        pyplot.imshow(-median_spec[startindx:endindx,:].T,
                       origin='lower',cmap='coolwarm',
                       vmin=vmin,vmax=vmax,
                       extent=extent,
                       interpolation='nearest',
                       #interpolation='bicubic',
                       aspect=aspect)
        pyplot.axis(extent)
        #pyplot.xticks(rotation=-45.)
        pyplot.xlim(xrange[0],xrange[1])
        pyplot.ylim(yrange[0],yrange[1])
        thisax.xaxis.set_major_locator(ticker.MultipleLocator(0.001))
        bovy_plot._add_ticks()
        if ii > 0:
            nullfmt   = NullFormatter()         # no labels
            thisax.yaxis.set_major_formatter(nullfmt)
        else:
            pyplot.ylabel(r'$R\,(\mathrm{kpc})$')
        # Remove spines between different wavelength regions
        if ii == 0:
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(right=False,which='both')
        elif ii == (nregions-1):
            thisax.spines['left'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False,which='both')
        else:
            thisax.spines['left'].set_visible(False)
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False,which='both')
            thisax.tick_params(right=False,which='both')
        # Plot cut-out markers
        d = .015 # how big to make the diagonal lines in axes coordinates
        kwargs = dict(transform=thisax.transAxes, color='k', clip_on=False)
        slope= 1./(dx[ii]+0.2*skipdx)/3.
        if ii == 0:
            thisax.plot((1-slope*d,1+slope*d),(-d,+d), **kwargs)
            thisax.plot((1-slope*d,1+slope*d),(1-d,1+d), **kwargs)
        elif ii == (nregions-1):
            thisax.plot((-slope*d,+slope*d),(-d,+d), **kwargs)
            thisax.plot((-slope*d,+slope*d),(1-d,1+d), **kwargs)
        else:
            thisax.plot((1-slope*d,1+slope*d),(-d,+d), **kwargs)
            thisax.plot((1-slope*d,1+slope*d),(1-d,1+d), **kwargs)
            thisax.plot((-slope*d,+slope*d),(-d,+d), **kwargs)
            thisax.plot((-slope*d,+slope*d),(1-d,1+d), **kwargs)
        # Draw solar line
        if ii == (nregions-1):
            xend= hdr['CRVAL1']+(endindx-0.5)*hdr['CDELT1']-numpy.log10(_LAMBDANORM)
            # Total wavelength span, incl. skipdx parts
            totaldx= hdr['CDELT1']*specdx*\
                (1.+(nregions-1)*skipdx/(totdx-(nregions-1)*skipdx))
            thisax.plot((xend-totaldx,xend),(8.,8.),
                        color='k',ls='--',lw=1.5,marker='None',clip_on=False)
        # Label the lines
        _label_all_lines(wave[startindx],wave[endindx])
    # Add the x-axis label
    thisax= pyplot.axes([0.1,0.175,0.85,0.65])
    pyplot.gcf().sca(thisax)
    thisax.spines['left'].set_visible(False)
    thisax.spines['right'].set_visible(False)
    thisax.spines['bottom'].set_visible(False)
    thisax.spines['top'].set_visible(False)
    thisax.tick_params(labelleft='off')
    thisax.tick_params(left=False,which='both')
    thisax.tick_params(right=False,which='both')
    thisax.tick_params(labelbottom='off')
    thisax.tick_params(bottom=False,which='both')
    thisax.tick_params(top=False,which='both')
    pyplot.xlabel(r'$\log \big(\lambda / 15,000 \AA\big)$')
    thisax.set_zorder(-1)
    bovy_plot.bovy_end_print(plotfilename,dpi=600)
    return None
Ejemplo n.º 13
0
def dualBandExample(filename='../data/SDSSJ203817.37+003029.8.fits',
                    constraints=None,
                    basefilename='SDSSJ203817.37+003029.8',
                    covarType='SF'):
    """
    NAME:
       dualBandExample
    PURPOSE:
       show an example of a power-law structure function GP covariance function
       fit to an SDSS quasar for g and r
    INPUT:
       filename - filename with the data
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
       covarType - 'SF' or 'DRW'
    OUTPUT:
       writes several plots
    HISTORY:
       2010-08-11 - Written - Bovy (NYU)
    """
    file = fu.table_fields(filename)
    mjd_g = nu.array(file.mjd_g) / 365.25
    g = nu.array(file.g)
    err_g = nu.array(file.err_g)
    mjd_r = nu.array(file.mjd_r) / 365.25
    r = nu.array(file.r)
    err_r = nu.array(file.err_r)

    mask = (mjd_g != 0) * (g < 20.6) * (g > 19.7)  #Adjust for non-g
    g = g[mask]
    g -= nu.mean(g)
    err_g = err_g[mask]
    mjd_g = mjd_g[mask]
    mjd_g -= nu.amin(mjd_g)
    meanErr_g = nu.mean(err_g)

    r = r[mask]
    r -= nu.mean(r)
    err_r = err_r[mask]
    mjd_r = mjd_r[mask]
    mjd_r -= nu.amin(mjd_r)
    meanErr_r = nu.mean(err_r)

    meanErr_gr = nu.mean(nu.sqrt(err_r**2. + err_g**2.))

    nu.random.seed(4)
    nGP = 5
    nx = 201
    params_mean = ()
    if covarType == 'SF':
        from powerlawSFgr import covarFunc
        params = {
            'logGamma': array([-7.33271548]),
            'logGammagr': array([-10.5]),
            'gamma': array([0.4821092]),
            'gammagr': array([0.5])
        }
        params = {
            'logGamma': array([-7.79009776]),
            'logGammagr': array([-28.0487848]),
            'gamma': array([0.45918053]),
            'gammagr': array([0.21333858])
        }
    else:
        from OUgr import covarFunc
        params = {
            'logl': array([1.94844503]),
            'loglgr': array([7.36282174]),
            'logagr2': array([1.0196474]),
            'loga2': array([-0.00588868])
        }
        params = {
            'logl': -1.37742591,
            'loga': -3.47341754,
            'loglgr': -2.3777,
            'logagr': -4.
        }
        params = {
            'logl': array([-1.38968195]),
            'loglgr': array([-2.46684501]),
            'logagr2': array([-6.62320832]),
            'loga2': array([-3.52099305])
        }
    paramsSF = params
    cf = covarFunc(**params)
    params_covar = (cf)
    ndata = len(g)
    if constraints is None:
        listx = [(t, 'g') for t in mjd_g]
        listx.extend([(t, 'r') for t in mjd_r])
        listy = [m for m in g]
        listy.extend([m for m in r])
        listy = nu.array(listy)
        noise = [m for m in err_g]
        noise.extend([m for m in err_r])
        noise = nu.array(noise)
        trainSet = trainingSet(listx=listx, listy=listy, noise=noise)
        constraints = trainSet
    else:
        constraints = nu.array([])

    useconstraints = constraints
    txs = nu.linspace(-0.1, 6.5, nx)
    xs = [(txs[ii], 'g') for ii in range(nx)]
    xs.extend([(txs[ii], 'r') for ii in range(nx)])
    GPsamples = eval_gp(xs,
                        mean,
                        covar, (),
                        params_covar,
                        nGP=nGP,
                        constraints=useconstraints,
                        tiny_cholesky=.00000001)
    thismean = calc_constrained_mean(xs, mean, params_mean, covar,
                                     params_covar, useconstraints)
    thiscovar = calc_constrained_covar(xs, covar, params_covar, useconstraints)
    #Calculate loglike
    if isinstance(constraints, trainingSet):
        (params, packing) = pack_params(cf)
        covarFuncName = inspect.getmodule(cf).__name__
        thisCovarClass = __import__(covarFuncName)
        loglike = marginalLikelihood(params, constraints, packing,
                                     thisCovarClass)

    plot.bovy_print()
    pyplot.plot(txs, GPsamples[0, :nx], '-', color='0.25')
    if isinstance(constraints, trainingSet):
        pyplot.plot(mjd_g, g, 'k.', zorder=5, ms=10)
    title = re.split(r'_', basefilename)[0]
    if covarType == 'SF':
        method = '\mathrm{power-law\ structure\ functions}'
    else:
        method = '\mathrm{damped\ random\ walk}'
    plot.bovy_text(r'$\mathrm{' + title + '\ / \ ' + method + r'}$',
                   title=True)
    if isinstance(constraints, trainingSet):
        plot.bovy_text(r'$\log P({\bf x}|\mathrm{parameters}) = %5.2f$' %
                       (-loglike),
                       top_left=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1, nGP):
        pyplot.plot(txs,
                    GPsamples[ii, :nx],
                    '-',
                    color=str(0.25 + ii * .5 / (nGP - 1)))
    #pyplot.plot(txs,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints, trainingSet):
        pyplot.errorbar(6.15, -0.25, yerr=meanErr_g, color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1, 6.5)
    pyplot.ylim(-0.6, 0.6)
    plot._add_ticks()
    plot.bovy_end_print(basefilename + '_fullg.ps')

    plot.bovy_print()
    pyplot.figure()
    pyplot.plot(txs, GPsamples[0, nx - 1:-1], '-', color='0.25')
    if isinstance(constraints, trainingSet):
        pyplot.plot(mjd_r, r, 'k.', zorder=5, ms=10)
    #plot.bovy_text(r'$\mathrm{'+title+'\ / \ '+method+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1, nGP):
        pyplot.plot(txs,
                    GPsamples[ii, nx - 1:-1],
                    '-',
                    color=str(0.25 + ii * .5 / (nGP - 1)))
    #pyplot.plot(txs,thismean[nx-1:-1],'k-',linewidth=2)
    if isinstance(constraints, trainingSet):
        pyplot.errorbar(6.15, -0.25, yerr=meanErr_r, color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$r-\langle r\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1, 6.5)
    pyplot.ylim(-0.6, 0.6)
    plot._add_ticks()
    plot.bovy_end_print(basefilename + '_fullr.ps')

    plot.bovy_print()
    pyplot.figure()
    ii = 0
    colors = nu.array(
        [GPsamples[ii, jj] - GPsamples[ii, jj + nx] for jj in range(nx)])
    if not isinstance(constraints, trainingSet):
        colors = colors - nu.mean(colors)
    pyplot.plot(txs, colors, '-', color='0.25')
    if isinstance(constraints, trainingSet):
        plot.bovy_plot(mjd_g, g - r, 'k.', zorder=5, ms=10, overplot=True)
    #plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1, nGP):
        colors = nu.array(
            [GPsamples[ii, jj] - GPsamples[ii, jj + nx] for jj in range(nx)])
        if not isinstance(constraints, trainingSet):
            colors = colors - nu.mean(colors)
        pyplot.plot(txs, colors, '-', color=str(0.25 + ii * .5 / (nGP - 1)))
    plotthismean = nu.zeros(nx)
    for ii in range(nx):
        plotthismean[ii] = thismean[ii] - thismean[ii + nx]
    #pyplot.plot(txs,plotthismean,'k-',linewidth=2)
    if isinstance(constraints, trainingSet):
        pyplot.errorbar(6.15, -0.18, yerr=meanErr_gr, color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-r- \langle g - r \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1, 6.5)
    if isinstance(constraints, trainingSet):
        pyplot.ylim(-0.25, .25)
    else:
        pass  #pyplot.ylim(-10.,10.)
    plot._add_ticks()
    plot.bovy_end_print(basefilename + '_color.ps')

    if covarType == 'DRW':
        return

    #Plot structure functions

    #g
    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        thisSample = GPsamples[ii, :nx]
        pyplot.loglog(sc.arange(1.,len(thisSample)/2)*(txs[1]-txs[0]),
                      2.*sc.var(thisSample)\
                          -2.*sc.correlate(thisSample-sc.mean(thisSample),thisSample-sc.mean(thisSample),"same")[1:len(thisSample)/2][::-1]/len(thisSample),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline = [(txs[1] - txs[0]), txs[len(txs) / 2]]
    pyplot.loglog(xline, (nu.exp(paramsSF['logGamma']) *
                          nu.array(xline))**(paramsSF['gamma']), 'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function\ in}\ g$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename + '_structfuncg.ps')

    #r
    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        thisSample = GPsamples[ii, nx - 1:-1]
        pyplot.loglog(sc.arange(1.,len(thisSample)/2)*(txs[1]-txs[0]),
                      2.*sc.var(thisSample)\
                          -2.*sc.correlate(thisSample-sc.mean(thisSample),thisSample-sc.mean(thisSample),"same")[1:len(thisSample)/2][::-1]/len(thisSample),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline = [(txs[1] - txs[0]), txs[len(txs) / 2]]
    pyplot.loglog(xline, (nu.exp(paramsSF['logGamma']) *
                          nu.array(xline))**(paramsSF['gamma']), 'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function\ in}\ r$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename + '_structfuncr.ps')

    #g-r
    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        thisSample = nu.array(
            [GPsamples[ii, jj] - GPsamples[ii, jj + nx] for jj in range(nx)])
        pyplot.loglog(sc.arange(1.,len(thisSample)/2)*(txs[1]-txs[0]),
                      2.*sc.var(thisSample)\
                          -2.*sc.correlate(thisSample-sc.mean(thisSample),thisSample-sc.mean(thisSample),"same")[1:len(thisSample)/2][::-1]/len(thisSample),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline = [(txs[1] - txs[0]), txs[len(txs) / 2]]
    pyplot.loglog(xline, (nu.exp(paramsSF['logGammagr']) *
                          nu.array(xline))**(paramsSF['gammagr']), 'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{color\ structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename + '_structfuncgr.ps')
def main(args: Optional[list] = None, opts: Optional[Namespace] = None):
    """Fit MWPotential2014 Script Function.

    Parameters
    ----------
    args : list, optional
        an optional single argument that holds the sys.argv list,
        except for the script name (e.g., argv[1:])
    opts : Namespace, optional
        pre-constructed results of parsed args
        if not None, used ONLY if args is None

    """
    if opts is not None and args is None:
        pass
    else:
        if opts is not None:
            warnings.warn("Not using `opts` because `args` are given")
        parser = make_parser()
        opts = parser.parse_args(args)

    fpath = opts.fpath + "/" if not opts.fpath.endswith("/") else opts.fpath
    opath = opts.opath + "/" if not opts.opath.endswith("/") else opts.opath

    # plot chains
    print("Plotting Chains")
    fig = mcmc_util.plot_chains(opath)
    fig.savefig(fpath + "chains.pdf")
    plt.close(fig)

    print("Need to continue chains:", end=" ")
    for i in range(32):
        ngood = mcmc_util.determine_nburn(
            filename=opath + f"mwpot14-fitsigma-{i:02}.dat", return_nsamples=True,
        )
        if ngood < 4000:
            print(f"{i:02} (N={ngood})", end=", ")

    ###############################################################
    # RESULTING PDFS

    data, _, weights, _ = read_mcmc(nburn=None, skip=1, evi_func=lambda x: 1.0)

    plot_corner(data, weights=weights)
    plt.savefig("figures/PDFs/corner.pdf")
    plt.close()

    # --------------

    savefilename = "output/pal5_forces_mcmc.pkl"
    if not os.path.exists(savefilename):
        data_wf, index_wf, weights_wf, evi_wf = read_mcmc(
            nburn=None, addforces=True, skip=1, evi_func=lambda x: 1.0
        )
        save_pickles(savefilename, data_wf, index_wf, weights_wf, evi_wf)
    else:
        with open(savefilename, "rb") as savefile:
            data_wf = pickle.load(savefile)
            index_wf = pickle.load(savefile)
            weights_wf = pickle.load(savefile)
            evi_wf = pickle.load(savefile)

    # --------------
    plot_corner(data_wf, weights=weights_wf, addvcprior=False)
    plt.savefig("figures/PDFs/corner_wf.pdf")
    plt.close()

    # --------------
    # Which potential is preferred?
    data_noforce, potindx, weights, evidences = read_mcmc(evi_func=evi_harmonic)

    fig = plt.figure(figsize=(6, 4))
    bovy_plot.bovy_plot(
        potindx,
        np.log(evidences),
        "o",
        xrange=[-1, 34],
        yrange=[-35, -22],
        xlabel=r"$\mathrm{Potential\ index}$",
        ylabel=r"$\ln\ \mathrm{evidence}$",
    )
    data_noforce, potindx, weights, evidences = read_mcmc(evi_func=evi_laplace)
    bovy_plot.bovy_plot(potindx, np.log(evidences) - 30.0, "d", overplot=True)
    data_noforce, potindx, weights, evidences = read_mcmc(
        evi_func=lambda x: np.exp(np.amax(x[:, -1]))
    )
    bovy_plot.bovy_plot(potindx, np.log(evidences) - 8.0, "s", overplot=True)
    data_noforce, potindx, weights, evidences = read_mcmc(
        evi_func=lambda x: np.exp(-25.0)
        if (np.log(evi_harmonic(x)) > -25.0)
        else np.exp(-50.0)
    )
    bovy_plot.bovy_plot(potindx, np.log(evidences), "o", overplot=True)
    plt.savefig("figures/PDFs/preferred_pot.pdf")
    plt.close()

    ###############################################################
    # Look at the results for individual potentials

    # --------------
    # The flattening $c$
    npot = 32
    nwalkers = 12

    plt.figure(figsize=(16, 6))
    cmap = cm.plasma
    maxl = np.zeros((npot, 2))
    for en, ii in enumerate(range(npot)):
        data_ip, _, weights_ip, evi_ip = read_mcmc(singlepot=ii, evi_func=evi_harmonic)
        try:
            maxl[en, 0] = np.amax(data_ip[:, -1])
            maxl[en, 1] = np.log(evi_ip[0])
        except ValueError:
            maxl[en] = -10000000.0
        plt.subplot(2, 4, en // 4 + 1)
        bovy_plot.bovy_hist(
            data_ip[:, 0],
            range=[0.5, 2.0],
            bins=26,
            histtype="step",
            color=cmap((en % 4) / 3.0),
            normed=True,
            xlabel=r"$c$",
            lw=1.5,
            overplot=True,
        )
        if en % 4 == 0:
            bovy_plot.bovy_text(
                r"$\mathrm{Potential\ %i\ to\ % i}$" % (en, en + 3),
                size=17.0,
                top_left=True,
            )
    plt.tight_layout()
    plt.savefig("figures/flattening_c.pdf")
    plt.close()

    ###############################################################
    # What is the effective prior in $(F_R,F_Z)$?

    frfzprior_savefilename = "frfzprior.pkl"
    if not os.path.exists(frfzprior_savefilename):
        # Compute for each potential separately
        nvoc = 10000
        ro = 8.0
        npot = 32
        fs = np.zeros((2, nvoc, npot))
        for en, ii in tqdm(enumerate(range(npot))):
            fn = f"output/fitsigma/mwpot14-fitsigma-{i:02}.dat"
            # Read the potential parameters
            with open(fn, "r") as savefile:
                line1 = savefile.readline()
            potparams = [float(s) for s in (line1.split(":")[1].split(","))]
            for jj in range(nvoc):
                c = np.random.uniform() * 1.5 + 0.5
                tvo = np.random.uniform() * 50.0 + 200.0
                pot = mw_pot.setup_potential(potparams, c, False, False, REFR0, tvo)
                fs[:, jj, ii] = np.array(pal5_util.force_pal5(pot, 23.46, REFR0, tvo))[
                    :2
                ]
        save_pickles(frfzprior_savefilename, fs)
    else:
        with open(frfzprior_savefilename, "rb") as savefile:
            fs = pickle.load(savefile)

    # --------------
    plt.figure(figsize=(6, 6))
    bovy_plot.scatterplot(
        fs[0].flatten(),
        fs[1].flatten(),
        "k,",
        xrange=[-1.75, -0.25],
        yrange=[-2.5, -1.2],
        xlabel=r"$F_R(\mathrm{Pal\ 5})$",
        ylabel=r"$F_Z(\mathrm{Pal\ 5})$",
        onedhists=True,
    )
    bovy_plot.scatterplot(
        data_wf[:, 7],
        data_wf[:, 8],
        weights=weights_wf,
        bins=26,
        xrange=[-1.75, -0.25],
        yrange=[-2.5, -1.2],
        justcontours=True,
        cntrcolors="w",
        overplot=True,
        onedhists=True,
    )
    plt.axvline(-0.81, color=sns.color_palette()[0])
    plt.axhline(-1.85, color=sns.color_palette()[0])
    plt.savefig("figures/effective_force_prior.pdf")
    plt.close()

    # --------------
    # The ratio of the posterior and the prior

    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=14.0,
        ytick_labelsize=14.0,
    )
    plt.figure(figsize=(12.5, 4))

    def axes_white():
        for k, spine in plt.gca().spines.items():  # ax.spines is a dictionary
            spine.set_color("w")
        plt.gca().tick_params(axis="x", which="both", colors="w")
        plt.gca().tick_params(axis="y", which="both", colors="w")
        [t.set_color("k") for t in plt.gca().xaxis.get_ticklabels()]
        [t.set_color("k") for t in plt.gca().yaxis.get_ticklabels()]
        return None

    bins = 32
    trange = [[-1.75, -0.25], [-2.5, -1.2]]
    tw = copy.deepcopy(weights_wf)
    tw[index_wf == 14] = 0.0  # Didn't converge properly
    H_prior, xedges, yedges = np.histogram2d(
        fs[0].flatten(), fs[1].flatten(), bins=bins, range=trange, normed=True
    )
    H_post, xedges, yedges = np.histogram2d(
        data_wf[:, 7], data_wf[:, 8], weights=tw, bins=bins, range=trange, normed=True,
    )
    H_like = H_post / H_prior
    H_like[H_prior == 0.0] = 0.0
    plt.subplot(1, 3, 1)
    bovy_plot.bovy_dens2d(
        H_prior.T,
        origin="lower",
        cmap="viridis",
        interpolation="nearest",
        xrange=[xedges[0], xedges[-1]],
        yrange=[yedges[0], yedges[-1]],
        xlabel=r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$",
        ylabel=r"$F_Z(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$",
        gcf=True,
    )
    bovy_plot.bovy_text(r"$\mathbf{Prior}$", top_left=True, size=19.0, color="w")
    axes_white()
    plt.subplot(1, 3, 2)
    bovy_plot.bovy_dens2d(
        H_post.T,
        origin="lower",
        cmap="viridis",
        interpolation="nearest",
        xrange=[xedges[0], xedges[-1]],
        yrange=[yedges[0], yedges[-1]],
        xlabel=r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$",
        gcf=True,
    )
    bovy_plot.bovy_text(r"$\mathbf{Posterior}$", top_left=True, size=19.0, color="w")
    axes_white()
    plt.subplot(1, 3, 3)
    bovy_plot.bovy_dens2d(
        H_like.T,
        origin="lower",
        cmap="viridis",
        interpolation="nearest",
        vmin=0.1,
        vmax=4.0,
        xrange=[xedges[0], xedges[-1]],
        yrange=[yedges[0], yedges[-1]],
        xlabel=r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$",
        gcf=True,
    )
    bovy_plot.bovy_text(r"$\mathbf{Likelihood}$", top_left=True, size=19.0, color="w")
    axes_white()

    def qline(FR, q=0.95):
        return 2.0 * FR / q ** 2.0

    q = 0.94
    plt.plot([-1.25, -0.2], [qline(-1.25, q=q), qline(-0.2, q=q)], "w--")
    bovy_plot.bovy_text(-1.7, -2.2, r"$q_\Phi = 0.94$", size=16.0, color="w")
    plt.plot((-1.25, -1.02), (-2.19, qline(-1.02, q=q)), "w-", lw=0.8)

    plt.tight_layout()
    plt.savefig(
        "figures/pal5post.pdf", bbox_inches="tight",
    )
    plt.close()

    # --------------
    # Projection onto the direction perpendicular to constant $q = 0.94$:
    frs = np.tile(0.5 * (xedges[:-1] + xedges[1:]), (len(yedges) - 1, 1)).T
    fzs = np.tile(0.5 * (yedges[:-1] + yedges[1:]), (len(xedges) - 1, 1))
    plt.figure(figsize=(6, 4))
    txlabel = r"$F_\perp$"
    dum = bovy_plot.bovy_hist(
        (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten(),
        weights=H_prior.flatten(),
        bins=21,
        histtype="step",
        lw=2.0,
        xrange=[-1.5, 1.5],
        xlabel=txlabel,
        normed=True,
    )
    dum = bovy_plot.bovy_hist(
        (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten(),
        weights=H_post.flatten(),
        bins=21,
        histtype="step",
        lw=2.0,
        overplot=True,
        xrange=[-1.5, 1.5],
        normed=True,
    )
    dum = bovy_plot.bovy_hist(
        (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten(),
        weights=H_like.flatten(),
        bins=21,
        histtype="step",
        lw=2.0,
        overplot=True,
        xrange=[-1.5, 1.5],
        normed=True,
    )
    plt.savefig("figures/PDFs/projection_perp_to_q0p94.pdf")
    plt.close()

    mq = (
        np.sum(
            (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten()
            * H_like.flatten()
        )
    ) / np.sum(H_like.flatten())

    print(
        mq,
        np.sqrt(
            (
                np.sum(
                    ((-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten() - mq)
                    ** 2.0
                    * H_like.flatten()
                )
            )
            / np.sum(H_like.flatten())
        ),
    )

    # --------------
    # Projection onto the direction parallel to constant $q = 0.94$:
    frs = np.tile(0.5 * (xedges[:-1] + xedges[1:]), (len(yedges) - 1, 1)).T
    fzs = np.tile(0.5 * (yedges[:-1] + yedges[1:]), (len(xedges) - 1, 1))
    plt.figure(figsize=(6, 4))
    txlabel = r"$F_\parallel$"
    dum = bovy_plot.bovy_hist(
        (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten(),
        weights=H_prior.flatten(),
        bins=21,
        histtype="step",
        lw=2.0,
        xrange=[-2.5, 2.5],
        xlabel=txlabel,
        normed=True,
    )
    dum = bovy_plot.bovy_hist(
        (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten(),
        weights=H_post.flatten(),
        bins=21,
        histtype="step",
        lw=2.0,
        overplot=True,
        xrange=[-2.5, 2.5],
        normed=True,
    )
    dum = bovy_plot.bovy_hist(
        (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten(),
        weights=H_like.flatten(),
        bins=21,
        histtype="step",
        lw=2.0,
        overplot=True,
        xrange=[-2.5, 2.5],
        normed=True,
    )
    plt.savefig("figures/PDFs/projection_prll_to_q0p94.pdf")
    plt.close()
    mq = (
        np.sum(
            (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten()
            * H_like.flatten()
        )
    ) / np.sum(H_like.flatten())
    print(
        mq,
        np.sqrt(
            (
                np.sum(
                    ((0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten() - mq)
                    ** 2.0
                    * H_like.flatten()
                )
            )
            / np.sum(H_like.flatten())
        ),
    )

    # --------------
    # Thus, there is only a weak constraint on $F_\parallel$.

    nrow = int(np.ceil(npot / 4.0))
    plt.figure(figsize=(16, nrow * 4))
    for en, ii in enumerate(range(npot)):
        plt.subplot(nrow, 4, en + 1)
        if ii % 4 == 0:
            tylabel = r"$F_Z(\mathrm{Pal\ 5})$"
        else:
            tylabel = None
        if ii // 4 == nrow - 1:
            txlabel = r"$F_R(\mathrm{Pal\ 5})$"
        else:
            txlabel = None
        bovy_plot.scatterplot(
            fs[0][:, en],
            fs[1][:, en],
            "k,",
            xrange=[-1.75, -0.25],
            yrange=[-2.5, -1.0],
            xlabel=txlabel,
            ylabel=tylabel,
            gcf=True,
        )
        bovy_plot.scatterplot(
            data_wf[:, 7],
            data_wf[:, 8],
            weights=weights_wf,
            bins=26,
            xrange=[-1.75, -0.25],
            yrange=[-2.5, -1.0],
            justcontours=True,
            cntrcolors="w",
            overplot=True,
        )
        bovy_plot.scatterplot(
            data_wf[index_wf == ii, 7],
            data_wf[index_wf == ii, 8],
            weights=weights_wf[index_wf == ii],
            bins=26,
            xrange=[-1.75, -0.25],
            yrange=[-2.5, -1.0],
            justcontours=True,
            # cntrcolors=sns.color_palette()[2],
            overplot=True,
        )
        plt.axvline(-0.80, color=sns.color_palette()[0])
        plt.axhline(-1.83, color=sns.color_palette()[0])
        bovy_plot.bovy_text(r"$\mathrm{Potential}\ %i$" % ii, size=17.0, top_left=True)
    plt.savefig("figures/PDFs/constain_F_prll.pdf")
    plt.close()

    # --------------
    # Let's plot four representative ones for the paper:

    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=14.0,
        ytick_labelsize=14.0,
    )
    nullfmt = NullFormatter()
    nrow = 1

    plt.figure(figsize=(15, nrow * 4))
    for en, ii in enumerate([0, 15, 24, 25]):
        plt.subplot(nrow, 4, en + 1)
        if en % 4 == 0:
            tylabel = (
                r"$F_Z(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$"
            )
        else:
            tylabel = None
        if en // 4 == nrow - 1:
            txlabel = (
                r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$"
            )
        else:
            txlabel = None
        bovy_plot.scatterplot(
            fs[0][:, ii],
            fs[1][:, ii],
            "k,",
            bins=31,
            xrange=[-1.75, -0.25],
            yrange=[-2.5, -1.0],
            xlabel=txlabel,
            ylabel=tylabel,
            gcf=True,
        )
        bovy_plot.scatterplot(
            data_wf[:, 7],
            data_wf[:, 8],
            weights=weights_wf,
            bins=21,
            xrange=[-1.75, -0.25],
            yrange=[-2.5, -1.0],
            justcontours=True,
            cntrcolors=sns.color_palette("colorblind")[2],
            cntrls="--",
            cntrlw=2.0,
            overplot=True,
        )
        bovy_plot.scatterplot(
            data_wf[index_wf == ii, 7],
            data_wf[index_wf == ii, 8],
            weights=weights_wf[index_wf == ii],
            bins=21,
            xrange=[-1.75, -0.25],
            yrange=[-2.5, -1.0],
            justcontours=True,
            cntrcolors=sns.color_palette("colorblind")[0],
            cntrlw=2.5,
            overplot=True,
        )
        if en > 0:
            plt.gca().yaxis.set_major_formatter(nullfmt)

    plt.tight_layout()
    plt.savefig(
        "figures/pal5post_examples.pdf", bbox_inches="tight",
    )
    plt.close()

    ###############################################################
    # What about $q_\Phi$?

    bins = 47
    plt.figure(figsize=(6, 4))
    dum = bovy_plot.bovy_hist(
        np.sqrt(2.0 * fs[0].flatten() / fs[1].flatten()),
        histtype="step",
        lw=2.0,
        bins=bins,
        xlabel=r"$q_\mathrm{\Phi}$",
        xrange=[0.7, 1.25],
        normed=True,
    )
    dum = bovy_plot.bovy_hist(
        np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]),
        weights=weights_wf,
        histtype="step",
        lw=2.0,
        bins=bins,
        overplot=True,
        xrange=[0.7, 1.25],
        normed=True,
    )
    mq = np.sum(
        np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]) * weights_wf
    ) / np.sum(weights_wf)
    sq = np.sqrt(
        np.sum(
            (np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]) - mq) ** 2.0
            * weights_wf
        )
        / np.sum(weights_wf)
    )
    print("From posterior samples: q = %.3f +/- %.3f" % (mq, sq))
    Hq_post, xedges = np.histogram(
        np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]),
        weights=weights_wf,
        bins=bins,
        range=[0.7, 1.25],
        normed=True,
    )
    Hq_prior, xedges = np.histogram(
        np.sqrt(2.0 * fs[0].flatten() / fs[1].flatten()),
        bins=bins,
        range=[0.7, 1.25],
        normed=True,
    )
    qs = 0.5 * (xedges[:-1] + xedges[1:])
    Hq_like = Hq_post / Hq_prior
    Hq_like[Hq_post == 0.0] = 0.0
    mq = np.sum(qs * Hq_like) / np.sum(Hq_like)
    sq = np.sqrt(np.sum((qs - mq) ** 2.0 * Hq_like) / np.sum(Hq_like))
    print("From likelihood of samples: q = %.3f +/- %.3f" % (mq, sq))

    plt.savefig("figures/q_phi.pdf")
    plt.close()

    # It appears that $q_\Phi$ is the quantity that is the most strongly constrained by the Pal 5 data.

    ###############################################################
    # A sampling of tracks from the MCMC

    savefilename = "mwpot14-pal5-mcmcTracks.pkl"
    pmdecpar = 2.257 / 2.296
    pmdecperp = -2.296 / 2.257
    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            pal5_track_samples = pickle.load(savefile)
            forces = pickle.load(savefile)
            all_potparams = pickle.load(savefile)
            all_params = pickle.load(savefile)
    else:
        np.random.seed(1)
        ntracks = 21
        multi = 8
        pal5_track_samples = np.zeros((ntracks, 2, 6, pal5varyc[0].shape[1]))
        forces = np.zeros((ntracks, 2))
        all_potparams = np.zeros((ntracks, 5))
        all_params = np.zeros((ntracks, 7))
        for ii in range(ntracks):
            # Pick a random potential from among the set, but leave 14 out
            pindx = 14
            while pindx == 14:
                pindx = np.random.permutation(32)[0]
            # Load this potential
            fn = f"output/fitsigma/mwpot14-fitsigma-{pindx:02}.dat"
            with open(fn, "r") as savefile:
                line1 = savefile.readline()
            potparams = [float(s) for s in (line1.split(":")[1].split(","))]
            all_potparams[ii] = potparams
            # Now pick a random sample from this MCMC chain
            tnburn = mcmc_util.determine_nburn(fn)
            tdata = np.loadtxt(fn, comments="#", delimiter=",")
            tdata = tdata[tnburn::]
            tdata = tdata[np.random.permutation(len(tdata))[0]]
            all_params[ii] = tdata
            tvo = tdata[1] * REFV0
            pot = mw_pot.setup_potential(potparams, tdata[0], False, False, REFR0, tvo)
            forces[ii, :] = pal5_util.force_pal5(pot, 23.46, REFR0, tvo)[:2]
            # Now compute the stream model for this setup
            dist = tdata[2] * 22.0
            pmra = -2.296 + tdata[3] + tdata[4]
            pmdecpar = 2.257 / 2.296
            pmdecperp = -2.296 / 2.257
            pmdec = -2.257 + tdata[3] * pmdecpar + tdata[4] * pmdecperp
            vlos = -58.7
            sigv = 0.4 * np.exp(tdata[5])
            prog = Orbit(
                [229.018, -0.124, dist, pmra, pmdec, vlos],
                radec=True,
                ro=REFR0,
                vo=tvo,
                solarmotion=[-11.1, 24.0, 7.25],
            )
            tsdf_trailing, tsdf_leading = pal5_util.setup_sdf(
                pot,
                prog,
                sigv,
                10.0,
                REFR0,
                tvo,
                multi=multi,
                nTrackChunks=8,
                trailing_only=False,
                verbose=True,
                useTM=False,
            )
            # Compute the track
            for jj, sdf in enumerate([tsdf_trailing, tsdf_leading]):
                trackRADec = bovy_coords.lb_to_radec(
                    sdf._interpolatedObsTrackLB[:, 0],
                    sdf._interpolatedObsTrackLB[:, 1],
                    degree=True,
                )
                trackpmRADec = bovy_coords.pmllpmbb_to_pmrapmdec(
                    sdf._interpolatedObsTrackLB[:, 4],
                    sdf._interpolatedObsTrackLB[:, 5],
                    sdf._interpolatedObsTrackLB[:, 0],
                    sdf._interpolatedObsTrackLB[:, 1],
                    degree=True,
                )
                # Store the track
                pal5_track_samples[ii, jj, 0] = trackRADec[:, 0]
                pal5_track_samples[ii, jj, 1] = trackRADec[:, 1]
                pal5_track_samples[ii, jj, 2] = sdf._interpolatedObsTrackLB[:, 2]
                pal5_track_samples[ii, jj, 3] = sdf._interpolatedObsTrackLB[:, 3]
                pal5_track_samples[ii, jj, 4] = trackpmRADec[:, 0]
                pal5_track_samples[ii, jj, 5] = trackpmRADec[:, 1]
        save_pickles(
            savefilename, pal5_track_samples, forces, all_potparams, all_params
        )

    # --------------
    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=14.0,
        ytick_labelsize=14.0,
    )
    plt.figure(figsize=(12, 8))
    gs = gridspec.GridSpec(2, 2, wspace=0.225, hspace=0.1, right=0.94)
    ntracks = pal5_track_samples.shape[0]
    cmap = cm.plasma
    alpha = 0.7
    for ii in range(ntracks):
        tc = cmap((forces[ii, 1] + 2.5) / 1.0)
        for jj in range(2):
            # RA, Dec
            plt.subplot(gs[0])
            plt.plot(
                pal5_track_samples[ii, jj, 0],
                pal5_track_samples[ii, jj, 1],
                "-",
                color=tc,
                alpha=alpha,
            )
            # RA, Vlos
            plt.subplot(gs[1])
            plt.plot(
                pal5_track_samples[ii, jj, 0],
                pal5_track_samples[ii, jj, 3],
                "-",
                color=tc,
                alpha=alpha,
            )
            # RA, Dist
            plt.subplot(gs[2])
            plt.plot(
                pal5_track_samples[ii, jj, 0],
                pal5_track_samples[ii, jj, 2] - all_params[ii, 2] * 22.0,
                "-",
                color=tc,
                alpha=alpha,
            )
            # RA, pm_parallel
            plt.subplot(gs[3])
            plt.plot(
                pal5_track_samples[ii, jj, 0, : 500 + 500 * (1 - jj)],
                np.sqrt(1.0 + (2.257 / 2.296) ** 2.0)
                * (
                    (pal5_track_samples[ii, jj, 4, : 500 + 500 * (1 - jj)] + 2.296)
                    * pmdecperp
                    - (pal5_track_samples[ii, jj, 5, : 500 + 500 * (1 - jj)] + 2.257)
                )
                / (pmdecpar - pmdecperp),
                "-",
                color=tc,
                alpha=alpha,
            )
    plot_data_add_labels(
        p1=(gs[0],), p2=(gs[1],), noxlabel_dec=True, noxlabel_vlos=True
    )
    plt.subplot(gs[2])
    plt.xlim(250.0, 221.0)
    plt.ylim(-3.0, 1.5)
    bovy_plot._add_ticks()
    plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$")
    plt.ylabel(r"$\Delta\mathrm{Distance}\,(\mathrm{kpc})$")
    plt.subplot(gs[3])
    plt.xlim(250.0, 221.0)
    plt.ylim(-0.5, 0.5)
    bovy_plot._add_ticks()
    plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$")
    plt.ylabel(r"$\Delta\mu_\parallel\,(\mathrm{mas\,yr}^{-1})$")
    # Colorbar
    gs2 = gridspec.GridSpec(2, 1, wspace=0.0, left=0.95, right=0.975)
    plt.subplot(gs2[:, -1])
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-2.5, vmax=-1.5))
    sm._A = []
    CB1 = plt.colorbar(sm, orientation="vertical", cax=plt.gca())
    CB1.set_label(
        r"$F_Z(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$",
        fontsize=18.0,
    )
    plt.savefig(
        "figures/pal5tracksamples.pdf", bbox_inches="tight",
    )
    plt.close()

    ###############################################################
    # What about Kuepper et al. (2015)?

    # Can we recover the Kuepper et al. (2015) result as prior + $q_\Phi =
    # 0.94 \pm 0.05$ + $V_c(R_0)$ between 200 and 280 km/s? For simplicity
    # we will not vary $R_0$, which should not have a big impact.

    s = sample_kuepper_flattening_post(50000, 0.94, 0.05)
    plot_kuepper_samples(s)
    plt.savefig("figures/kuepper_samples.pdf")
    plt.close()

    # The constraint on the potential flattening gets you far, but there
    # is more going on (the constraint on the halo mass and scale
    # parameter appear to come completely from the $V_c(R_0)$ constraint).
    # Let's add the weak constraint on the sum of the forces, scaled to
    # Kuepper et al.'s best-fit acceleration (which is higher than ours):

    s = sample_kuepper_flatteningforce_post(50000, 0.94, 0.05, -0.83, 0.36)
    plot_kuepper_samples(s)
    plt.savefig("figures/kuepper_samples_flatF.pdf")
    plt.close()

    # This gets a tight relation between $M_\mathrm{halo}$ and the scale
    # parameter of the halo, but does not lead to a constraint on either
    # independently; the halo potential flattening constraint is that of
    # Kuepper et al. Based on this, it appears that the information that
    # ties down $M_\mathrm{halo}$ comes from the overdensities, which may
    # be spurious (Thomas et al. 2016) and whose use in dynamical modeling
    # is dubious anyway.

    # What is Kuepper et al.'s prior on $a_{\mathrm{Pal\ 5}}$?

    apal5s = []
    ns = 100000
    for ii in range(ns):
        Mh = np.random.uniform() * (10.0 - 0.001) + 0.001
        a = np.random.uniform() * (100.0 - 0.1) + 0.1
        q = np.random.uniform() * (1.8 - 0.2) + 0.2
        pot = setup_potential_kuepper(Mh, a)
        FR, FZ = force_pal5_kuepper(pot, q)
        apal5s.append(np.sqrt(FR ** 2.0 + FZ ** 2.0))
    apal5s = np.array(apal5s)

    plt.figure(figsize=(6, 4))
    dum = bovy_plot.bovy_hist(
        apal5s, range=[0.0, 10.0], lw=2.0, bins=51, histtype="step", normed=True,
    )
    plt.savefig("figures/kuepper_samples_prior.pdf")
    plt.close()
Ejemplo n.º 15
0
def elements(elem, *args, **kwargs):
    """
    NAME:
       elements
    PURPOSE:
       make a plot of measurements of the elemental abundances vs. atomic number
    INPUT:
       elem - dictionary with elemental abundances relative to H
       wrtFe= (True) if True, plot elements wrt Fe on the left Y
       inclwrtH= (True) if True, indicate what X/H is on the right Y
       bovy_plot.bovy_plot args and kwargs
    OUTPUT:
       plot to output
    HISTORY:
       2015-03-10 - Written - Bovy (IAS)
    """
    # Process the input dictionary
    xs = []
    names = []
    ys = []
    wrtFe = kwargs.pop('wrtFe', True)
    for el in elem:
        try:
            xs.append(atomic_number(el))
        except KeyError:  # ignore things that aren't known elements
            continue
        names.append(r'$\mathrm{%s}$' % el.lower().capitalize())
        try:
            if not wrtFe: raise KeyError
            ys.append(elem[el] - elem['Fe'])
        except KeyError:
            ys.append(elem[el])
            wrtFe = False
    xs = numpy.array(xs, dtype='int')
    ys = numpy.array(ys)
    names = numpy.array(names)
    # sort
    sindx = numpy.argsort(xs)
    xs = xs[sindx]
    ys = ys[sindx]
    names = names[sindx]
    # add second y axis?
    inclwrtH = kwargs.pop('inclwrtH', True)
    if wrtFe:
        feh = elem['Fe']
        ylabel = kwargs.pop('ylabel', r'$[\mathrm{X/Fe}]$')
    else:
        ylabel = kwargs.pop('ylabel', r'$[\mathrm{X/H}]$')
    if not kwargs.get('overplot', False):
        bovy_plot.bovy_print(fig_width=7., fig_height=4.)
    basezorder = kwargs.pop('zorder', 0)
    yrange = kwargs.pop('yrange', [-0.5, 0.5])
    ls = kwargs.pop('ls', '-')
    lw = kwargs.pop('lw', 0.25)
    bovy_plot.bovy_plot(xs,
                        ys,
                        *args,
                        ylabel=ylabel,
                        xrange=[4, numpy.amax(xs) + 2],
                        yrange=yrange,
                        zorder=2 + basezorder,
                        ls=ls,
                        lw=lw,
                        **kwargs)
    pyplot.xticks(list(xs), names)
    pyplot.tick_params(axis='x', labelsize=11.)
    if wrtFe and inclwrtH:
        bovy_plot.bovy_plot([4, numpy.amax(xs) + 2], [0., 0.],
                            '-',
                            lw=2.,
                            color='0.65',
                            overplot=True,
                            zorder=basezorder)
        ax = pyplot.gca()
        ax2 = ax.twinx()
        ax2.set_ylim(yrange[0] + feh, yrange[1] + feh)
        ax2.set_ylabel(r'$[\mathrm{X/H}]$')
        pyplot.sca(ax2)
        bovy_plot._add_ticks(yticks=True, xticks=False)
    return None
Ejemplo n.º 16
0
def illustrateBestR(options,args):
    if options.sample.lower() == 'g':
        npops= 62
    elif options.sample.lower() == 'k':
        npops= 54
    if options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    savefile.close()
    #For bin 10, calculate the correlation between sigma and Rd
    bin= options.index
    derivProps= calcAllSurfErr(bin,options,args)
    #rs= numpy.linspace(4.5,9.,101)
    #derivProps= numpy.zeros((101,6))
    rs= derivProps[:,0]
    #also calculate the full surface density profile for each Rd's best fh
    if _NOTDONEYET:
        spl= options.restart.split('.')
    else:
        spl= args[0].split('.')
    newname= ''
    for jj in range(len(spl)-1):
        newname+= spl[jj]
        if not jj == len(spl)-2: newname+= '.'
    newname+= '_%i.' % bin
    newname+= spl[-1]
    options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
    options.fitdvt= False
    savefile= open(newname,'rb')
    try:
        if not _NOTDONEYET:
            params= pickle.load(savefile)
            mlogl= pickle.load(savefile)
        logl= pickle.load(savefile)
    except:
        raise
    finally:
        savefile.close()
    if _NOTDONEYET:
        logl[(logl == 0.)]= -numpy.finfo(numpy.dtype(numpy.float64)).max
    logl[numpy.isnan(logl)]= -numpy.finfo(numpy.dtype(numpy.float64)).max
    marglogl= numpy.zeros((logl.shape[0],logl.shape[3]))
    sigs= numpy.zeros((logl.shape[0],len(rs)))
    rds= numpy.linspace(2.,3.4,8)
    fhs= numpy.linspace(0.,1.,16)
    hiresfhs= numpy.linspace(0.,1.,101)
    ro= 1.
    vo= options.fixvc/_REFV0
    for jj in range(logl.shape[0]):
        for kk in range(logl.shape[3]):
            marglogl[jj,kk]= misc.logsumexp(logl[jj,0,0,kk,:,:,:,0].flatten())
        #interpolate
        tindx= marglogl[jj,:] > -1000000000.
        intp= interpolate.InterpolatedUnivariateSpline(fhs[tindx],marglogl[jj,tindx],
                                                       k=3)
        ml= intp(hiresfhs)
        indx= numpy.argmax(ml)
        indx2= numpy.argmax(marglogl[jj,:])
        #Setup potential to calculate stuff
        potparams= numpy.array([numpy.log(rds[jj]/8.),vo,numpy.log(options.fixzh/8000.),hiresfhs[indx],options.dlnvcdlnr])
        try:
            pot= setup_potential(potparams,options,0,returnrawpot=True)
        except RuntimeError:
            continue
        #Total surface density
        for ll in range(len(rs)):
            surfz= 2.*integrate.quad((lambda zz: potential.evaluateDensities(rs[ll]/_REFR0,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
            sigs[jj,ll]= surfz
    #Now plot sigs
    bovy_plot.bovy_print(fig_height=7.,fig_width=5.)
    left, bottom, width, height= 0.1, 0.35, 0.8, 0.4
    axTop= pyplot.axes([left,bottom,width,height])
    fig= pyplot.gcf()
    fig.sca(axTop)
    ii= 0
    bovy_plot.bovy_plot(rs,sigs[ii,:],'k-',
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$\Sigma(R,|Z| \leq 1.1\,\mathrm{kpc})\ (M_\odot\,\mathrm{pc}^{-2})$',
                        xrange=[4.,10.],
                        yrange=[10,1050.],
                        semilogy=True,overplot=True)
    for ii in range(1,logl.shape[0]):
        bovy_plot.bovy_plot(rs,sigs[ii,:],'k-',overplot=True)
    thisax= pyplot.gca()
    thisax.set_yscale('log')
    nullfmt   = NullFormatter()         # no labels
    thisax.xaxis.set_major_formatter(nullfmt)
    thisax.set_ylim(10.,1050.)
    thisax.set_xlim(4.,10.)
    pyplot.ylabel(r'$\Sigma_{1.1}(R)\ (M_\odot\,\mathrm{pc}^{-2})$')
    bovy_plot._add_ticks(yticks=False)
    bovy_plot.bovy_text(r'$[\mathrm{Fe/H}] = %.2f$' % (fehs[bin])
                        +'\n'
                        r'$[\alpha/\mathrm{Fe}] = %.3f$' % (afes[bin]),
                        size=16.,top_right=True)

    left, bottom, width, height= 0.1, 0.1, 0.8, 0.25
    ax2= pyplot.axes([left,bottom,width,height])
    fig= pyplot.gcf()
    fig.sca(ax2)
    bovy_plot.bovy_plot(rs,derivProps[:,2],'k-',lw=2.,
                        xrange=[4.,10.],
                        overplot=True)
    indx= numpy.argmin(numpy.fabs(derivProps[:,2]))
    bovy_plot.bovy_plot([4.,10.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot([rs[indx],rs[indx]],[derivProps[indx,2],1000.],
                        'k--',overplot=True)
    thisax= pyplot.gca()
    pyplot.ylabel(r'$\mathrm{Correlation\ between}$'+'\n'+r'$\!\!\!\!\!\!\!\!R_d\ \&\ \Sigma_{1.1}(R)$')
    pyplot.xlabel(r'$R\ (\mathrm{kpc})$')   
    pyplot.xlim(4.,10.)
    pyplot.ylim(-.5,.5)
    bovy_plot._add_ticks()
    pyplot.sca(axTop)
    bovy_plot.bovy_plot([rs[indx],rs[indx]],[0.01,sigs[3,indx]],
                        'k--',overplot=True)   
    bovy_plot.bovy_end_print(options.outfilename)
Ejemplo n.º 17
0
def plot_bestfit(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata)
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    #Cut inner disk locations
    #data= data[(data['GLON'] > 75.)]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        if options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
        if options.dwarf:
            iso = [
                iso,
                isomodel.isomodel(imfmodel=options.imfmodel,
                                  Z=options.Z,
                                  dwarf=True,
                                  expsfh=options.expsfh)
            ]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, 'wb')
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data['H0MAG'][ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) +
                                    (data['J0MAG'] - data['K0MAG'])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF,
                                 _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data['H0MAG'][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) +
                                         (data['J0MAG'] - data['K0MAG'])[ii],
                                         mh)
    else:
        logpisodwarf = None
    #Calculate data means etc.
    #Calculate means
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    sigerr_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
        avg_plate[ii] = numpy.mean(data['VHELIO'][indx])
        sig_plate[ii] = numpy.std(data['VHELIO'][indx])
        siga_plate[ii] = numpy.std(data['VHELIO'][indx]) / numpy.sqrt(
            numpy.sum(indx))
        sigerr_plate[ii] = bootstrap_sigerr(data['VHELIO'][indx])
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile = open(args[0], 'rb')
    params = pickle.load(savefile)
    if not options.index is None:
        params = params[options.index]
    savefile.close()
    #params[0]= 245./235.
    #params[1]= 8.5/8.
    avg_plate_model = numpy.zeros(nlocs)
    sig_plate_model = numpy.zeros(nlocs)
    for ii in range(nlocs):
        #Calculate vlos | los
        indx = (data['LOCATION'] == locations[ii])
        thesedata = data[indx]
        thislogpiso = logpiso[indx, :]
        if options.dwarf:
            thislogpisodwarf = logpisodwarf[indx, :]
        else:
            thislogpisodwarf = None
        vlos = numpy.linspace(-200., 200., options.nvlos)
        pvlos = numpy.zeros(options.nvlos)
        if not options.multi is None:
            pvlos = multi.parallel_map(
                (lambda x: pvlosplate(params, vlos[x], thesedata, df, options,
                                      thislogpiso, thislogpisodwarf, iso)),
                range(options.nvlos),
                numcores=numpy.amin(
                    [len(vlos),
                     multiprocessing.cpu_count(), options.multi]))
        else:
            for jj in range(options.nvlos):
                print jj
                pvlos[jj] = pvlosplate(params, vlos[jj], thesedata, df,
                                       options, thislogpiso, thislogpisodwarf,
                                       iso)
        pvlos -= logsumexp(pvlos)
        pvlos = numpy.exp(pvlos)
        #Calculate mean and velocity dispersion
        avg_plate_model[ii] = numpy.sum(vlos * pvlos)
        sig_plate_model[ii]= numpy.sqrt(numpy.sum(vlos**2.*pvlos)\
                                            -avg_plate_model[ii]**2.)
    #Plot everything
    left, bottom, width, height = 0.1, 0.4, 0.8, 0.5
    axTop = pyplot.axes([left, bottom, width, height])
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.3
    axMean = pyplot.axes([left, bottom, width, height])
    #left, bottom, width, height= 0.1, 0.1, 0.8, 0.2
    #axSig= pyplot.axes([left,bottom,width,height])
    fig = pyplot.gcf()
    fig.sca(axTop)
    pyplot.ylabel(r'$\mathrm{Heliocentric\ velocity}\ [\mathrm{km\ s}^{-1}]$')
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    pyplot.ylim(-200., 200.)
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_plot(data['GLON'],
                        data['VHELIO'],
                        'k,',
                        yrange=[-200., 200.],
                        xrange=[0., 360.],
                        overplot=True)
    ndata_t = int(math.floor(len(data) / 1000.))
    ndata_h = len(data) - ndata_t * 1000
    bovy_plot.bovy_plot(l_plate,
                        avg_plate,
                        'o',
                        overplot=True,
                        mfc='0.5',
                        mec='none')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate_model,
                        'x',
                        overplot=True,
                        ms=10.,
                        mew=1.5,
                        color='0.7')
    #Legend
    bovy_plot.bovy_plot([260.], [150.], 'k,', overplot=True)
    bovy_plot.bovy_plot([260.], [120.],
                        'o',
                        mfc='0.5',
                        mec='none',
                        overplot=True)
    bovy_plot.bovy_plot([260.], [90.],
                        'x',
                        ms=10.,
                        mew=1.5,
                        color='0.7',
                        overplot=True)
    bovy_plot.bovy_text(270., 145., r'$\mathrm{data}$')
    bovy_plot.bovy_text(270., 115., r'$\mathrm{data\ mean}$')
    bovy_plot.bovy_text(270., 85., r'$\mathrm{model\ mean}$')
    bovy_plot._add_ticks()
    #Now plot the difference
    fig.sca(axMean)
    bovy_plot.bovy_plot([0., 360.], [0., 0.], '-', color='0.5', overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    pyplot.ylabel(r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}}$')
    pyplot.ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #axMean.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
    #Sigma
    fig.sca(axSig)
    pyplot.plot([0., 360.], [1., 1.], '-', color='0.5')
    bovy_plot.bovy_plot(l_plate,
                        sig_plate / sig_plate_model,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    sig_plate / sig_plate_model,
                    yerr=sigerr_plate / sig_plate_model,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    pyplot.ylabel(
        r'$\sigma_{\mathrm{los}}^{\mathrm{data}}/ \sigma_{\mathrm{los}}^{\mathrm{model}}$'
    )
    pyplot.ylim(0.5, 1.5)
Ejemplo n.º 18
0
def singleBandExample(filename='../data/SDSSJ203817.37+003029.8.fits',
                      band='g',
                      constraints=None,
                      basefilename='SDSSJ203817.37+003029.8',
                      covarType='SF'):
    """
    NAME:
       singleBandExample
    PURPOSE:
       show an example of a power-law structure function or damped-random walk
       GP covariance function fit to an SDSS quasar
    INPUT:
       filename - filename with the data
       band - band to consider
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
       covarType - 'SF' or 'DRW'
    OUTPUT:
       writes several plots
    HISTORY:
       2010-06-20 - Written - Bovy (NYU)
    """
    file = fu.table_fields(filename)
    if band == 'u':
        mjd_g = nu.array(file.mjd_u) / 365.25
        g = nu.array(file.u)
        err_g = nu.array(file.err_u)
    elif band == 'g':
        mjd_g = nu.array(file.mjd_g) / 365.25
        g = nu.array(file.g)
        err_g = nu.array(file.err_g)
    elif band == 'r':
        mjd_g = nu.array(file.mjd_r) / 365.25
        g = nu.array(file.r)
        err_g = nu.array(file.err_r)
    elif band == 'i':
        mjd_g = nu.array(file.mjd_i) / 365.25
        g = nu.array(file.i)
        err_g = nu.array(file.err_i)
    elif band == 'z':
        mjd_g = nu.array(file.mjd_z) / 365.25
        g = nu.array(file.z)
        err_g = nu.array(file.err_z)

    mask = (mjd_g != 0) * (g < 20.6) * (g > 19.7)  #Adjust for non-g
    g = g[mask]
    g -= nu.mean(g)
    err_g = err_g[mask]
    mjd_g = mjd_g[mask]
    mjd_g -= nu.amin(mjd_g)
    meanErr_g = nu.mean(err_g)

    nu.random.seed(4)
    nGP = 5
    nx = 201
    params_mean = ()
    if covarType == 'SF':
        from powerlawSF import covarFunc
        params = {'gamma': array([0.49500723]), 'logA': array([-3.36044037])}
    else:
        from OU_ARD import covarFunc
        params = {'logl': array([-1.37742591]), 'loga2': array([-3.47341754])}
    cf = covarFunc(**params)
    params_covar = (cf)
    ndata = len(g)
    if constraints is None:
        listx = mjd_g
        listy = g
        noise = err_g
        trainSet = trainingSet(listx=listx, listy=listy, noise=noise)
        constraints = trainSet
    else:
        constraints = None

    useconstraints = constraints
    xs = nu.linspace(-0.1, 6.5, nx)
    GPsamples = eval_gp(xs,
                        mean,
                        covar, (),
                        params_covar,
                        nGP=nGP,
                        constraints=useconstraints)
    thismean = calc_constrained_mean(xs, mean, params_mean, covar,
                                     params_covar, useconstraints)
    thiscovar = calc_constrained_covar(xs, covar, params_covar, useconstraints)
    #If unconstrained, subtract the mean
    if constraints is None:
        for ii in range(nGP):
            GPsamples[ii, :] = GPsamples[ii, :] - nu.mean(GPsamples[ii, :])

    #Calculate loglike
    if not constraints is None:
        (params, packing) = pack_params(cf)
        covarFuncName = inspect.getmodule(cf).__name__
        thisCovarClass = __import__(covarFuncName)
        loglike = marginalLikelihood(params, constraints, packing,
                                     thisCovarClass)
    plot.bovy_print()
    pyplot.plot(xs, GPsamples[0, :], '-', color='0.25')
    if not constraints is None:
        plot.bovy_plot(mjd_g, g, 'k.', zorder=5, ms=10, overplot=True)
    title = re.split(r'_', basefilename)[0]
    if covarType == 'SF':
        method = '\mathrm{power-law\ structure\ function}'
    else:
        method = '\mathrm{damped\ random\ walk}'
    plot.bovy_text(r'$\mathrm{' + title + '\ / \ ' + method + r'}$',
                   title=True)
    if not constraints is None:
        plot.bovy_text(r'$\log P({\bf x}|\mathrm{parameters}) = %5.2f$' %
                       (-loglike),
                       top_left=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(nGP):
        pyplot.plot(xs,
                    GPsamples[ii, :],
                    '-',
                    color=str(0.25 + ii * .5 / (nGP - 1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints is None:
        pyplot.errorbar(6.15, -0.25, yerr=meanErr_g, color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$' + band + r'-\langle ' + band +
                  r' \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1, 6.5)
    if constraints is None:
        pyplot.ylim(-.6, .6)
    else:
        pyplot.ylim(-.6, .6)
    plot._add_ticks()
    plot.bovy_end_print(basefilename + '_full.ps')

    plot.bovy_print()
    pyplot.plot(xs, GPsamples[0, :], '-', color='0.25')
    if not constraints is None:
        plot.bovy_plot(mjd_g, g, 'k.', zorder=5, ms=10, overplot=True)
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1, nGP):
        pyplot.plot(xs,
                    GPsamples[ii, :],
                    '-',
                    color=str(0.25 + ii * .5 / (nGP - 1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints == []:
        pyplot.errorbar(6.15, -0.25, yerr=meanErr_g, color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$' + band + '-\langle ' + band +
                  '\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(3, 6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename + '_zoom.ps')

    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        pyplot.loglog(
            sc.arange(1.,
                      len(GPsamples[ii, :]) / 2) * (xs[1] - xs[0]),
            2. * sc.var(GPsamples[ii, :]) -
            2. * sc.correlate(GPsamples[ii, :] - sc.mean(GPsamples[ii, :]),
                              GPsamples[ii, :] - sc.mean(GPsamples[ii, :]),
                              "same")[1:len(GPsamples[ii, :]) / 2][::-1] /
            len(GPsamples[ii, :]),
            color=str(0.25 + ii * .5 / (nGP - 1)))
    xline = [(xs[1] - xs[0]), xs[len(xs) / 2]]
    pyplot.loglog(xline,
                  nu.exp(-3.36044037) * nu.array(xline)**(0.49500723), 'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename + '_structfunc.ps')
Ejemplo n.º 19
0
def plot_lb():
    #Read basic data
    data = readVclosData()
    ndata = len(data)
    if _PLOTHIGHB:
        yrange = [-6., 6.]
    else:
        yrange = [-2.5, 2.5]
    #Plot
    if OUTEXT == 'ps':
        bovy_plot.bovy_print(fig_width=8.5, fig_height=6. / 16. * 8.5)
    else:
        bovy_plot.bovy_print(fig_width=16., fig_height=6.)
    fig = pyplot.figure()
    #Set up axes
    nullfmt = NullFormatter()  # no labels
    # definitions for the axes
    left, width = 0.1, 0.7
    bottom, height = 0.1, 0.85
    bottom_h = left_h = left + width
    rect_scatter = [left, bottom, width, height]
    rect_histy = [left_h, bottom, 0.15, height]
    axScatter = pyplot.axes(rect_scatter)
    axHisty = pyplot.axes(rect_histy)
    # no labels
    axHisty.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)
    fig.sca(axScatter)
    bovy_plot.bovy_plot(data['GLON'],
                        data['GLAT'],
                        'k.',
                        ms=1.5,
                        overplot=True)
    pyplot.xlim(0., 250.)
    pyplot.ylim(yrange[0], yrange[1])
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ l\ \mathrm{[deg]}$')
    pyplot.ylabel(r'$\mathrm{Galactic\ latitude}\ b\ \mathrm{[deg]}$')
    bovy_plot._add_ticks()
    #bovy_plot.bovy_end_print(os.path.join(OUTDIR,'data_lb.'+OUTEXT))
    if _PLOTHIGHB:
        #Read other data
        otherdata = readVclosData(meanb=-4., bmax=10.)
        nmdata = len(otherdata)
        otherl = list(otherdata['GLON'])
        otherb = list(otherdata['GLAT'])
        otherdata2 = readVclosData(meanb=4., bmax=10.)
        npdata = len(otherdata2)
        otherl.extend(list(otherdata2['GLON']))
        otherb.extend(list(otherdata2['GLAT']))
        bovy_plot.bovy_plot(otherl,
                            otherb,
                            '.',
                            mec='0.5',
                            mfc='0.5',
                            ms=1.5,
                            overplot=True)
        #Add histogram of bs
        otherl.extend(list(data['GLON']))
        otherb.extend(list(data['GLAT']))
    else:
        #Add histogram of bs
        otherl = list(data['GLON'])
        otherb = list(data['GLAT'])
        nmdata, npdata = 0, 0
    histy, edges, patches = axHisty.hist(otherb,
                                         bins=49,
                                         orientation='horizontal',
                                         normed=True,
                                         histtype='step',
                                         range=yrange,
                                         color='k',
                                         zorder=2)
    #Overlay predictions
    #Center, constant
    ys = numpy.linspace(-1.5, 1.5, 1001)
    pdf = numpy.sqrt(1.5**2. - ys**2.)
    pdf *= float(ndata) / (ndata + nmdata + npdata) / numpy.sum(pdf) / (ys[1] -
                                                                        ys[0])
    axHisty.plot(pdf, ys, 'k-', zorder=-2)
    constpdf = pdf
    #Center, exponential disk
    """
    dfc= dehnendf(beta=0.,correct=True,niter=20)
    pdf= numpy.zeros(len(ys))
    plates= list(set(data['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= data[(data['PLATE'] == plates[ii])]
        thisl= numpy.mean(data['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(ys[jj],thisl,0.,dmax/ro,0.,dfc,hz/ro)
        pdf+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdf*= float(ndata)/(ndata+nmdata+npdata)/numpy.sum(pdf)/(ys[1]-ys[0])
    axHisty.plot(pdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    #axHisty.plot(.8*pdf+.2*constpdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    """
    if _PLOTHIGHB:
        #positive b, constant
        constpdf *= float(npdata) / ndata
        axHisty.plot(constpdf, ys + 4., 'k-', zorder=-2)
        """
        #Positive, exponential disk
        pdfp= numpy.zeros(len(ys))
        plates= list(set(otherdata2['PLATE']))
        for ii in range(len(plates)):
            print ii
            #For each plate, calculate pdf and add with data weights
            thisdata= otherdata2[(otherdata2['PLATE'] == plates[ii])]
            thisl= numpy.mean(otherdata2['GLON'])
            thisndata= len(thisdata)
            thispdf= numpy.zeros(len(ys))
            for jj in range(len(ys)):
                thispdf[jj]= surfacemassLOSd(4.+ys[jj],
                thisl,0.,dmax/ro,4.,dfc,hz/ro)
            pdfp+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
        pdfp*= float(npdata)/(ndata+nmdata+npdata)/numpy.sum(pdfp)/(ys[1]-ys[0])
        axHisty.plot(pdfp,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        #axHisty.plot(.8*pdfp+.2*constpdf,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        """
        #negative b, constant
        constpdf *= nmdata / float(npdata)
        axHisty.plot(constpdf, ys - 4., 'k-', zorder=-2.)
    """
    #Negative, exponential disk
    pdfm= numpy.zeros(len(ys))
    plates= list(set(otherdata['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= otherdata[(otherdata['PLATE'] == plates[ii])]
        thisl= numpy.mean(otherdata['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(-4.+ys[jj],
                                          thisl,0.,dmax/ro,-4.,dfc,hz/ro)
        pdfm+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdfm*= float(nmdata)/(ndata+nmdata+npdata)/numpy.sum(pdfm)/(ys[1]-ys[0])
    axHisty.plot(pdfm,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    #axHisty.plot(.8*pdfm+.2*constpdf,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    """
    axHisty.set_ylim(yrange[0], yrange[1])
    axHisty.set_xlim(0, 1.2 * numpy.amax(histy))
    pyplot.sca(axHisty)
    bovy_plot._add_ticks()
    bovy_plot.bovy_end_print(os.path.join(OUTDIR, 'data_lb.' + OUTEXT))
    return None
Ejemplo n.º 20
0
def dualBandExample(filename='../data/SDSSJ203817.37+003029.8.fits',
                    constraints=None,basefilename='SDSSJ203817.37+003029.8',
                    covarType='SF'):
    """
    NAME:
       dualBandExample
    PURPOSE:
       show an example of a power-law structure function GP covariance function
       fit to an SDSS quasar for g and r
    INPUT:
       filename - filename with the data
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
       covarType - 'SF' or 'DRW'
    OUTPUT:
       writes several plots
    HISTORY:
       2010-08-11 - Written - Bovy (NYU)
    """
    file= fu.table_fields(filename)
    mjd_g= nu.array(file.mjd_g)/365.25
    g= nu.array(file.g)
    err_g= nu.array(file.err_g)
    mjd_r= nu.array(file.mjd_r)/365.25
    r= nu.array(file.r)
    err_r= nu.array(file.err_r)

    mask= (mjd_g != 0)*(g < 20.6)*(g > 19.7)#Adjust for non-g
    g= g[mask]
    g-= nu.mean(g)
    err_g= err_g[mask]
    mjd_g= mjd_g[mask]
    mjd_g-= nu.amin(mjd_g)
    meanErr_g= nu.mean(err_g)

    r= r[mask]
    r-= nu.mean(r)
    err_r= err_r[mask]
    mjd_r= mjd_r[mask]
    mjd_r-= nu.amin(mjd_r)
    meanErr_r= nu.mean(err_r)
    
    meanErr_gr= nu.mean(nu.sqrt(err_r**2.+err_g**2.))

    nu.random.seed(4)
    nGP=5
    nx=201
    params_mean= ()
    if covarType == 'SF':
        from powerlawSFgr import covarFunc
        params= {'logGamma': array([-7.33271548]), 'logGammagr': array([-10.5]), 'gamma': array([ 0.4821092]), 'gammagr': array([ 0.5])}
        params= {'logGamma': array([-7.79009776]), 'logGammagr': array([-28.0487848]), 'gamma': array([ 0.45918053]), 'gammagr': array([ 0.21333858])}
    else:
        from OUgr import covarFunc
        params= {'logl': array([ 1.94844503]), 'loglgr': array([ 7.36282174]), 'logagr2': array([ 1.0196474]), 'loga2': array([-0.00588868])}
        params= {'logl':-1.37742591,'loga':-3.47341754,
                 'loglgr': -2.3777,'logagr': -4.}
        params= {'logl': array([-1.38968195]), 'loglgr': array([-2.46684501]), 'logagr2': array([-6.62320832]), 'loga2': array([-3.52099305])}
    paramsSF= params
    cf= covarFunc(**params)
    params_covar= (cf)
    ndata= len(g)
    if constraints is None:
        listx= [(t,'g') for t in mjd_g]
        listx.extend([(t,'r') for t in mjd_r])
        listy= [m for m in g]
        listy.extend([m for m in r])
        listy= nu.array(listy)
        noise= [m for m in err_g]
        noise.extend([m for m in err_r])
        noise= nu.array(noise)
        trainSet= trainingSet(listx=listx,listy=listy,noise=noise)
        constraints= trainSet
    else:
        constraints= nu.array([])

    useconstraints= constraints
    txs= nu.linspace(-0.1,6.5,nx)
    xs= [(txs[ii],'g') for ii in range(nx)]
    xs.extend([(txs[ii],'r') for ii in range(nx)])
    GPsamples= eval_gp(xs,mean,covar,(),params_covar,nGP=nGP,constraints=useconstraints,tiny_cholesky=.00000001)
    thismean= calc_constrained_mean(xs,mean,params_mean,covar,params_covar,useconstraints)
    thiscovar= calc_constrained_covar(xs,covar,params_covar,useconstraints)
    #Calculate loglike
    if isinstance(constraints,trainingSet):
        (params,packing)= pack_params(cf)
        covarFuncName= inspect.getmodule(cf).__name__
        thisCovarClass= __import__(covarFuncName)
        loglike= marginalLikelihood(params,constraints,packing,
                                    thisCovarClass)

    plot.bovy_print()
    pyplot.plot(txs,GPsamples[0,:nx],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_g,g,'k.',zorder=5,ms=10)
    title= re.split(r'_',basefilename)[0]
    if covarType == 'SF':
        method= '\mathrm{power-law\ structure\ functions}'
    else:
        method= '\mathrm{damped\ random\ walk}'
    plot.bovy_text(r'$\mathrm{'+title+'\ / \ '+method+r'}$',title=True)
    if isinstance(constraints,trainingSet):
        plot.bovy_text(r'$\log P({\bf x}|\mathrm{parameters}) = %5.2f$' %(-loglike),
                       top_left=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,:nx],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(txs,thismean[:nx],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-\langle g\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    pyplot.ylim(-0.6,0.6)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_fullg.ps')


    plot.bovy_print()
    pyplot.figure()
    pyplot.plot(txs,GPsamples[0,nx-1:-1],'-',color='0.25')
    if isinstance(constraints,trainingSet):
        pyplot.plot(mjd_r,r,'k.',zorder=5,ms=10)
    #plot.bovy_text(r'$\mathrm{'+title+'\ / \ '+method+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(txs,GPsamples[ii,nx-1:-1],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(txs,thismean[nx-1:-1],'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_r,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$r-\langle r\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    pyplot.ylim(-0.6,0.6)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_fullr.ps')


    plot.bovy_print()
    pyplot.figure()
    ii= 0
    colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
    if not isinstance(constraints,trainingSet):
        colors= colors-nu.mean(colors)
    pyplot.plot(txs,colors,'-',color='0.25')
    if isinstance(constraints,trainingSet):
        plot.bovy_plot(mjd_g,g-r,'k.',zorder=5,ms=10,overplot=True)
    #plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        colors= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        if not isinstance(constraints,trainingSet):
            colors= colors-nu.mean(colors)
        pyplot.plot(txs,colors,'-',color=str(0.25+ii*.5/(nGP-1)))
    plotthismean= nu.zeros(nx)
    for ii in range(nx):
        plotthismean[ii]= thismean[ii]-thismean[ii+nx]
    #pyplot.plot(txs,plotthismean,'k-',linewidth=2)
    if isinstance(constraints,trainingSet):
        pyplot.errorbar(6.15,-0.18,yerr=meanErr_gr,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$g-r- \langle g - r \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    if isinstance(constraints,trainingSet):
        pyplot.ylim(-0.25,.25)
    else:
        pass #pyplot.ylim(-10.,10.)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_color.ps')

    if covarType == 'DRW':
        return

    #Plot structure functions

    #g
    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        thisSample= GPsamples[ii,:nx]
        pyplot.loglog(sc.arange(1.,len(thisSample)/2)*(txs[1]-txs[0]),
                      2.*sc.var(thisSample)\
                          -2.*sc.correlate(thisSample-sc.mean(thisSample),thisSample-sc.mean(thisSample),"same")[1:len(thisSample)/2][::-1]/len(thisSample),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(txs[1]-txs[0]),txs[len(txs)/2]]
    pyplot.loglog(xline,(nu.exp(paramsSF['logGamma'])*nu.array(xline))**(paramsSF['gamma']),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function\ in}\ g$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfuncg.ps')


    #r
    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        thisSample= GPsamples[ii,nx-1:-1]
        pyplot.loglog(sc.arange(1.,len(thisSample)/2)*(txs[1]-txs[0]),
                      2.*sc.var(thisSample)\
                          -2.*sc.correlate(thisSample-sc.mean(thisSample),thisSample-sc.mean(thisSample),"same")[1:len(thisSample)/2][::-1]/len(thisSample),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(txs[1]-txs[0]),txs[len(txs)/2]]
    pyplot.loglog(xline,(nu.exp(paramsSF['logGamma'])*nu.array(xline))**(paramsSF['gamma']),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function\ in}\ r$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfuncr.ps')


    #g-r
    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        thisSample= nu.array([GPsamples[ii,jj]-GPsamples[ii,jj+nx] for jj in range(nx)])
        pyplot.loglog(sc.arange(1.,len(thisSample)/2)*(txs[1]-txs[0]),
                      2.*sc.var(thisSample)\
                          -2.*sc.correlate(thisSample-sc.mean(thisSample),thisSample-sc.mean(thisSample),"same")[1:len(thisSample)/2][::-1]/len(thisSample),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(txs[1]-txs[0]),txs[len(txs)/2]]
    pyplot.loglog(xline,(nu.exp(paramsSF['logGammagr'])*nu.array(xline))**(paramsSF['gammagr']),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{color\ structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfuncgr.ps')
Ejemplo n.º 21
0
def plot_lb():
    #Read basic data
    data= readVclosData()
    ndata= len(data)
    if _PLOTHIGHB:
        yrange= [-6.,6.]
    else:
        yrange= [-2.5,2.5]
    #Plot
    if OUTEXT == 'ps':
        bovy_plot.bovy_print(fig_width=8.5,fig_height=6./16.*8.5)
    else:
        bovy_plot.bovy_print(fig_width=16.,fig_height=6.)
    fig= pyplot.figure()
    #Set up axes
    nullfmt   = NullFormatter()         # no labels
    # definitions for the axes
    left, width = 0.1, 0.7
    bottom, height = 0.1, 0.85
    bottom_h = left_h = left+width
    rect_scatter = [left, bottom, width, height]
    rect_histy = [left_h, bottom, 0.15, height]
    axScatter = pyplot.axes(rect_scatter)
    axHisty = pyplot.axes(rect_histy)
    # no labels
    axHisty.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)
    fig.sca(axScatter)  
    bovy_plot.bovy_plot(data['GLON'],data['GLAT'],'k.',ms=1.5,
                        overplot=True)
    pyplot.xlim(0.,250.)
    pyplot.ylim(yrange[0],yrange[1])
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ l\ \mathrm{[deg]}$')
    pyplot.ylabel(r'$\mathrm{Galactic\ latitude}\ b\ \mathrm{[deg]}$')
    bovy_plot._add_ticks()
    #bovy_plot.bovy_end_print(os.path.join(OUTDIR,'data_lb.'+OUTEXT))
    if _PLOTHIGHB:
        #Read other data
        otherdata= readVclosData(meanb=-4.,bmax=10.)
        nmdata= len(otherdata)
        otherl= list(otherdata['GLON'])
        otherb= list(otherdata['GLAT'])
        otherdata2= readVclosData(meanb=4.,bmax=10.)
        npdata= len(otherdata2)
        otherl.extend(list(otherdata2['GLON']))
        otherb.extend(list(otherdata2['GLAT']))
        bovy_plot.bovy_plot(otherl,otherb,'.',mec='0.5',mfc='0.5',ms=1.5,
                            overplot=True)
        #Add histogram of bs
        otherl.extend(list(data['GLON']))
        otherb.extend(list(data['GLAT']))
    else:
        #Add histogram of bs
        otherl= list(data['GLON'])
        otherb= list(data['GLAT'])
        nmdata, npdata= 0,0
    histy, edges, patches= axHisty.hist(otherb,
                                        bins=49,
                                        orientation='horizontal',
                                        normed=True,
                                        histtype='step',
                                        range=yrange,
                                        color='k',zorder=2)
    #Overlay predictions
    #Center, constant
    ys= numpy.linspace(-1.5,1.5,1001)
    pdf= numpy.sqrt(1.5**2.-ys**2.)
    pdf*= float(ndata)/(ndata+nmdata+npdata)/numpy.sum(pdf)/(ys[1]-ys[0])
    axHisty.plot(pdf,ys,'k-',zorder=-2)
    constpdf= pdf
    #Center, exponential disk
    """
    dfc= dehnendf(beta=0.,correct=True,niter=20)
    pdf= numpy.zeros(len(ys))
    plates= list(set(data['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= data[(data['PLATE'] == plates[ii])]
        thisl= numpy.mean(data['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(ys[jj],thisl,0.,dmax/ro,0.,dfc,hz/ro)
        pdf+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdf*= float(ndata)/(ndata+nmdata+npdata)/numpy.sum(pdf)/(ys[1]-ys[0])
    axHisty.plot(pdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    #axHisty.plot(.8*pdf+.2*constpdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    """
    if _PLOTHIGHB:
        #positive b, constant
        constpdf*= float(npdata)/ndata
        axHisty.plot(constpdf,ys+4.,'k-',zorder=-2)
        """
        #Positive, exponential disk
        pdfp= numpy.zeros(len(ys))
        plates= list(set(otherdata2['PLATE']))
        for ii in range(len(plates)):
            print ii
            #For each plate, calculate pdf and add with data weights
            thisdata= otherdata2[(otherdata2['PLATE'] == plates[ii])]
            thisl= numpy.mean(otherdata2['GLON'])
            thisndata= len(thisdata)
            thispdf= numpy.zeros(len(ys))
            for jj in range(len(ys)):
                thispdf[jj]= surfacemassLOSd(4.+ys[jj],
                thisl,0.,dmax/ro,4.,dfc,hz/ro)
            pdfp+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
        pdfp*= float(npdata)/(ndata+nmdata+npdata)/numpy.sum(pdfp)/(ys[1]-ys[0])
        axHisty.plot(pdfp,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        #axHisty.plot(.8*pdfp+.2*constpdf,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        """
        #negative b, constant
        constpdf*= nmdata/float(npdata)
        axHisty.plot(constpdf,ys-4.,'k-',zorder=-2.)
    """
    #Negative, exponential disk
    pdfm= numpy.zeros(len(ys))
    plates= list(set(otherdata['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= otherdata[(otherdata['PLATE'] == plates[ii])]
        thisl= numpy.mean(otherdata['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(-4.+ys[jj],
                                          thisl,0.,dmax/ro,-4.,dfc,hz/ro)
        pdfm+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdfm*= float(nmdata)/(ndata+nmdata+npdata)/numpy.sum(pdfm)/(ys[1]-ys[0])
    axHisty.plot(pdfm,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    #axHisty.plot(.8*pdfm+.2*constpdf,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    """
    axHisty.set_ylim(yrange[0],yrange[1])
    axHisty.set_xlim( 0, 1.2*numpy.amax(histy))
    pyplot.sca(axHisty)
    bovy_plot._add_ticks()
    bovy_plot.bovy_end_print(os.path.join(OUTDIR,'data_lb.'+OUTEXT))
    return None
Ejemplo n.º 22
0
def plot_rckinematics(plotfilename,subsun=False):
    #Set up 3 axes
    bovy_plot.bovy_print(fig_width=8.,axes_labelsize=14)
    axdx= 1./3.
    #APOGEE-RC observations
    tdy= (_RCYMAX-_RCYMIN+4.5)/(_RCXMAX-_RCXMIN+4.5)*axdx
    obsAxes= pyplot.axes([0.1,(1.-tdy)/2.,axdx,tdy])
    pyplot.sca(obsAxes)
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    data= data[indx]
    #Get velocity field
    pixrc= pixelize_sample.pixelXY(data,
                                   xmin=_RCXMIN-2.25,xmax=_RCXMAX+2.25,
                                   ymin=_RCYMIN-2.25,ymax=_RCYMAX+2.25,
                                   dx=_RCDX,dy=_RCDX)
    vmin, vmax= -16.,16.
    img= pixrc.plot(lambda x: dvlosgal(x,vtsun=220.+24.),
                    vmin=vmin,vmax=vmax,overplot=True,
                    colorbar=False)
    resv= pixrc.plot(lambda x: dvlosgal(x,vtsun=220.+24.),
                     justcalc=True,returnz=True) #for later
    pyplot.annotate(r'$\mathrm{APOGEE\!-\!RC\ data}$',
                    (0.5,1.09),xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',size=10.)
    pyplot.axis([pixrc.xmin,pixrc.xmax,pixrc.ymin,pixrc.ymax])
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$',
                              r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$')
    #Colorbar
    cbaxes = pyplot.axes([0.1+axdx/2.,(1.-tdy)/2.+tdy+0.065,2.*axdx-0.195,0.02])
    CB1= pyplot.colorbar(img,orientation='horizontal',
                         cax=cbaxes)#,ticks=[-16.,-8.,0.,8.,16.])
    CB1.set_label(r'$\mathrm{median}\ \Delta V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.)
    #Now calculate the expected field
    expec_vlos= galpy_simulations.vlos_altrect('../sim/bar_altrect_alpha0.015_hivres.sav')*220.
    modelAxes= pyplot.axes([0.03+axdx,(1.-tdy)/2.,axdx,tdy])
    pyplot.sca(modelAxes)
    xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$'
    ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$'
    indx= True-numpy.isnan(resv)
    plotthis= copy.copy(expec_vlos)
    plotthis[numpy.isnan(resv)]= numpy.nan #turn these off
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xlabel=xlabel,ylabel=ylabel,
                          xrange=[_RCXMIN-2.25,_RCXMAX+2.25],
                          yrange=[_RCYMIN-2.25,_RCYMAX+2.25],
                          contours=False,
                          vmin=vmin,vmax=vmax,overplot=True,zorder=3)
    if True:
       #Now plot the pixels outside the APOGEE data set
        plotthis= copy.copy(expec_vlos)
        plotthis[True-numpy.isnan(resv)]= numpy.nan #turn these off
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              alpha=0.3,
                              xrange=[_RCXMIN-2.25,_RCXMAX+2.25],
                              yrange=[_RCYMIN-2.25,_RCYMAX+2.25],
                              contours=False,
                              vmin=vmin,vmax=vmax,overplot=True,
                              zorder=0)
    pyplot.annotate(r'$\mathrm{Favored\ bar\ model}$',
                    (1.02,1.09),xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',size=10.,zorder=3)
    pyplot.axis([_RCXMIN-2.25,_RCXMAX+2.25,_RCYMIN-2.25,_RCYMAX+2.25])
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(xlabel,r'$ $')
    #Finally, add a polar plot of the whole disk
    res= 51
    rmin, rmax= 0.2, 2.4
    xgrid= numpy.linspace(0.,2.*numpy.pi*(1.-1./res/2.),
                          2.*res)
    ygrid= numpy.linspace(rmin,rmax,res)
    expec_vlos= galpy_simulations.vlos_polar('../sim/bar_polar_alpha0.015_hivres.sav')*220.
    plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2.,
                              xgrid[-1]+(xgrid[1]-xgrid[0])/2.,
                              len(xgrid)+1)
    plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2.,
                           ygrid[-1]+(ygrid[1]-ygrid[0])/2.,
                           len(ygrid)+1)
    fullmodelAxes= pyplot.axes([-0.05+2.*axdx,(1.-tdy)/2.,axdx,tdy],polar=True)
    ax= fullmodelAxes
    pyplot.sca(fullmodelAxes)
    out= ax.pcolor(plotxgrid,plotygrid,expec_vlos.T,cmap='jet',
                   vmin=vmin,vmax=vmax,clip_on=False)
    from matplotlib.patches import FancyArrowPatch
    arr= FancyArrowPatch(posA=(numpy.pi+0.1,1.8),
                         posB=(3*numpy.pi/2.+0.1,1.8),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (numpy.pi/8.-0.05),
                         shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, 
                         mutation_aspect=None,fc='k',zorder=10)
    ax.add_patch(arr)
    bovy_plot.bovy_text(numpy.pi+0.17,1.7,r'$\mathrm{Galactic\ rotation}$',
                        rotation=-30.,size=9.)
    radii= numpy.array([0.5,1.,1.5,2.,2.5])
    labels= []
    for r in radii:
        ax.plot(numpy.linspace(0.,2.*numpy.pi,501,),
                numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5)
        labels.append(r'$%i$' % int(r*8.))
    pyplot.rgrids(radii,labels=labels,angle=147.5)
    thetaticks = numpy.arange(0,360,45)
    # set ticklabels location at x times the axes' radius
    ax.set_thetagrids(thetaticks,frac=1.16,backgroundcolor='w',zorder=3)
    bovy_plot.bovy_text(3.*numpy.pi/4.+0.06,2.095,r'$\mathrm{kpc}$',size=10.)
    pyplot.ylim(0.,2.8)
    # Plot the bar position
    ets= numpy.linspace(0.,2.*numpy.pi,501,)
    a= 0.421766
    b= a*0.4
    dtr= numpy.pi/180.
    ax.plot(ets,
            a*b/numpy.sqrt((b*numpy.cos(ets-25.*dtr))**2.
                           +(a*numpy.sin(ets-25.*dtr))**2.),
            zorder=1,lw=1.5,color='w')
    #Plot the box
    xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101)
    ys= numpy.ones(101)*(_RCYMIN-2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101)
    ys= numpy.ones(101)*(_RCYMAX+2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101)
    xs= numpy.ones(101)*(_RCXMIN-2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101)
    xs= numpy.ones(101)*(_RCXMAX+2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the connectors on the modelAxes
    xlow=-4.*8.
    ylow= 2.77*8.
    xs= numpy.linspace(xlow,(_RCXMAX+2.25),101)
    ys= (ylow-(_RCYMAX+2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2)
    line[0].set_clip_on(False)
    xlow=-4.*8.
    ylow= -2.77*8.
    xs= numpy.linspace(xlow,(_RCXMAX+2.25),101)
    ys= (ylow-(_RCYMIN-2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2)
    line[0].set_clip_on(False)
    bovy_plot.bovy_end_print(plotfilename,dpi=300)
    return None
Ejemplo n.º 23
0
def verysimplenfwfit(plotfilename,wcprior=False,wmassprior=False):
    #Fit
    p= optimize.fmin_powell(chi2,[-0.5,0.7],args=(wcprior,wmassprior))
    print mvir(p), conc(p)*numpy.exp(p[1])*8.
    vo= numpy.exp(p[0])
    a= numpy.exp(p[1])
    nfw= potential.NFWPotential(normalize=1.,a=a)
    rs= numpy.linspace(0.01,350.,1001)
    masses= numpy.array([nfw.mass(r/8.) for r in rs])
    bovy_plot.bovy_print(fig_width=6.)
    bovy_plot.bovy_plot(rs,
                        masses*bovy_conversion.mass_in_1010msol(220.*vo,8.)/100.,
                        'k-',loglog=True,
                        xlabel=r'$R\,(\mathrm{kpc})$',
                        ylabel=r'$M(<R)\,(10^{12}\,M_\odot)$',
                        yrange=[0.01,1.2],
                        xrange=[3.,400.])
    if _USE_ALL_XUE:
        plotx= [10.]
        plotx.extend(list(_XUER))
        ploty= [4.5/100.]
        ploty.extend(list(_XUEMASS/100.))
        plotyerr= [1.5/100]
        plotyerr.extend(list(_XUEMASS_ERR/100.))
        pyplot.errorbar(plotx,ploty,yerr=plotyerr,marker='o',ls='none',
                        color='k')
    else:
        pyplot.errorbar([10.,60.],[4.5/100.,3.5/10.],yerr=[1.5/100.,0.7/10.],
                        marker='o',ls='none',color='k')
    pyplot.errorbar([150.],[7.5/10.],[2.5/10.],marker='None',color='k')
    dx= .5
    arr= FancyArrowPatch(posA=(7.,4./100.),posB=(numpy.exp(numpy.log(7.)+dx),numpy.exp(numpy.log(4./100.)+1.5*dx)),arrowstyle='->',connectionstyle='arc3,rad=%4.2f' % (0.),shrinkA=2.0, shrinkB=2.0,mutation_scale=20.0, mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    #Sample MCMC to get virial mass uncertainty
    samples= bovy_mcmc.markovpy(p,
                                0.05,
                                lnlike,
                                (wcprior,wmassprior),
                                isDomainFinite=[[False,False],[False,False]],
                                domain=[[0.,0.],[0.,0.]],
                                nsamples=10000,
                                nwalkers=6)
    mvirs= numpy.array([mvir(x) for x in samples])
    concs= numpy.array([conc(x) for x in samples])
    indx= True-numpy.isnan(mvirs)
    mvirs= mvirs[indx]
    indx= True-numpy.isnan(concs)
    concs= concs[indx]
    rvirs= concs[indx]*numpy.array([numpy.exp(x[1]) for x in samples])*8.
    bovy_plot.bovy_text(r'$M_{\mathrm{vir}} = %.2f\pm%.2f\times10^{12}\,M_\odot$' % (numpy.median(mvirs),1.4826*numpy.median(numpy.fabs(mvirs-numpy.median(mvirs)))) +'\n'+
                        r'$r_{\mathrm{vir}} = %i\pm%i\,\mathrm{kpc}$' % (numpy.median(rvirs),1.4826*numpy.median(numpy.fabs(rvirs-numpy.median(rvirs))))+'\n'+
                        r'$c = %.1f\pm%.1f$' % (numpy.median(concs),1.4826*numpy.median(numpy.fabs(concs-numpy.median(concs)))),
                        top_left=True,size=18.)
    #Create inset with PDF
    insetAxes= pyplot.axes([0.55,0.22,0.3,0.3])
    pyplot.sca(insetAxes)
    bovy_plot.bovy_hist(mvirs,range=[0.,3.],bins=51,histtype='step',
                        color='k',
                        normed=True,
                        overplot=True)
    insetAxes.set_xlim(0.,3.)
    insetAxes.set_ylim(0.,1.49)
    insetAxes.set_xlabel(r'$M_{\mathrm{vir}}\,(10^{12}\,M_\odot)$')
    bovy_plot._add_ticks()
    bovy_plot.bovy_end_print(plotfilename)
Ejemplo n.º 24
0
def plot_rckinematics(plotfilename,subsun=False):
    #Set up 3 axes
    bovy_plot.bovy_print(fig_width=8.,axes_labelsize=14)
    axdx= 1./3.
    #APOGEE-RC observations
    tdy= (_RCYMAX-_RCYMIN+4.5)/(_RCXMAX-_RCXMIN+4.5)*axdx
    obsAxes= pyplot.axes([0.1,(1.-tdy)/2.,axdx,tdy])
    pyplot.sca(obsAxes)
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    data= data[indx]
    #Get velocity field
    pixrc= pixelize_sample.pixelXY(data,
                                   xmin=_RCXMIN-2.25,xmax=_RCXMAX+2.25,
                                   ymin=_RCYMIN-2.25,ymax=_RCYMAX+2.25,
                                   dx=_RCDX,dy=_RCDX)
    if subsun:
        vmin, vmax= 0., 250.
        pixrc.plot(lambda x: vlosgal(x),
                   func=lambda x: numpy.fabs(numpy.median(x)),
                   zlabel=r'$|\mathrm{median}\ V^{\mathrm{GC}}_{\mathrm{los}}|\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax)
    else:
        vmin, vmax= -75., 75.
        img= pixrc.plot('VHELIO_AVG',
                        vmin=vmin,vmax=vmax,overplot=True,
                        colorbar=False)
        resv= pixrc.plot('VHELIO_AVG',
                         justcalc=True,returnz=True) #for later
        bovy_plot.bovy_text(r'$\mathrm{typical\ uncertainty\!:}\ 3\,\mathrm{km\,s}^{-1}$',
                            bottom_left=True,size=8.25)
        bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',top_right=True,size=10.)
    pyplot.annotate(r'$\mathrm{APOGEE\!-\!RC\ data}$',
                    (0.5,1.09),xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',size=10.)
    pyplot.axis([pixrc.xmin,pixrc.xmax,pixrc.ymin,pixrc.ymax])
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$',
                              r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$')
    #Colorbar
    cbaxes = pyplot.axes([0.1625,(1.-tdy)/2.+tdy+0.065,2.*axdx-0.195,0.02])
    CB1= pyplot.colorbar(img,orientation='horizontal',
                         cax=cbaxes)#,ticks=[-16.,-8.,0.,8.,16.])
    CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.)
    #Now calculate the expected field
    xgrid= numpy.arange(_RCXMIN-2.25+_RCDX/2.,_RCXMAX+2.25+_RCDX/2.,_RCDX)
    ygrid= numpy.arange(_RCYMIN-2.25+_RCDX/2.,_RCYMAX+2.25+_RCDX/2.,_RCDX)
    xv,yv= numpy.meshgrid(xgrid,ygrid,indexing='ij')
    rs= numpy.sqrt(xv**2.+yv**2.)
    phis= numpy.arctan2(yv,xv)
    d,l= bovy_coords.rphi_to_dl_2d(rs/8.,phis)
    expec_vlos= numpy.empty((len(xgrid),len(ygrid)))
    for ii in range(len(xgrid)):
        for jj in range(len(ygrid)):
            expec_vlos[ii,jj]= modelvlosgal(rs[ii,jj],phis[ii,jj],l[ii,jj],
                                            vc=218.,vtsun=242.)
    modelAxes= pyplot.axes([0.03+axdx,(1.-tdy)/2.,axdx,tdy])
    pyplot.sca(modelAxes)
    xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$'
    ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$'
    indx= True-numpy.isnan(resv)
    plotthis= copy.copy(expec_vlos)
    plotthis[numpy.isnan(resv)]= numpy.nan #turn these off
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xlabel=xlabel,ylabel=ylabel,
                          xrange=[_RCXMIN-2.25,_RCXMAX+2.25],
                          yrange=[_RCYMIN-2.25,_RCYMAX+2.25],
                          contours=False,
                          vmin=vmin,vmax=vmax,overplot=True,zorder=3)
    if True:
       #Now plot the pixels outside the APOGEE data set
        plotthis= copy.copy(expec_vlos)
        plotthis[True-numpy.isnan(resv)]= numpy.nan #turn these off
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              alpha=0.3,
                              xrange=[_RCXMIN-2.25,_RCXMAX+2.25],
                              yrange=[_RCYMIN-2.25,_RCYMAX+2.25],
                              contours=False,
                              vmin=vmin,vmax=vmax,overplot=True,
                              zorder=0)
    pyplot.annotate(r'$\mathrm{Bovy\ et.\ al\ (2012)\ model}$',
                    (1.02,1.09),xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',size=10.,zorder=3)
    pyplot.axis([_RCXMIN-2.25,_RCXMAX+2.25,_RCYMIN-2.25,_RCYMAX+2.25])
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(xlabel,r'$ $')
    #Finally, add a polar plot of the whole disk
    res= 51
    rmin, rmax= 0.2, 2.4
    xgrid= numpy.linspace(0.,2.*numpy.pi*(1.-1./res/2.),
                          2.*res)
    ygrid= numpy.linspace(rmin,rmax,res)
    nx= len(xgrid)
    ny= len(ygrid)
    savefile= 'expec_vlos.sav'
    if os.path.exists(savefile):
        savefile= open(savefile,'rb')
        expec_vlos= pickle.load(savefile)
        savefile.close()
    else:
        expec_vlos= numpy.zeros((nx,ny))
        for ii in range(nx):
            for jj in range(ny):
                R, phi= ygrid[jj], xgrid[ii]
                d,l= bovy_coords.rphi_to_dl_2d(R,phi)
                expec_vlos[ii,jj]= modelvlosgal(R*8.,phi,l,
                                                vc=218.,vtsun=242.)
        save_pickles(savefile,expec_vlos)
    plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2.,
                              xgrid[-1]+(xgrid[1]-xgrid[0])/2.,
                              len(xgrid)+1)
    plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2.,
                           ygrid[-1]+(ygrid[1]-ygrid[0])/2.,
                           len(ygrid)+1)
    fullmodelAxes= pyplot.axes([-0.05+2.*axdx,(1.-tdy)/2.,axdx,tdy],polar=True)
    ax= fullmodelAxes
    pyplot.sca(fullmodelAxes)
    vmin, vmax= -150., 150.
    zlabel= r'$\mathrm{line\!-\!of\!-\!sight\ velocity}\ (\mathrm{km\,s}^{-1})$'
    out= ax.pcolor(plotxgrid,plotygrid,expec_vlos.T,cmap='jet',
                   vmin=vmin,vmax=vmax,clip_on=False)
    shrink= 0.8
    if False:
        CB1= pyplot.colorbar(out,shrink=shrink)
        bbox = CB1.ax.get_position().get_points()
        CB1.ax.set_position(transforms.Bbox.from_extents(bbox[0,0]+0.025,
                                                         bbox[0,1],
                                                         bbox[1,0],
                                                         bbox[1,1]))
        CB1.set_label(zlabel)
    from matplotlib.patches import FancyArrowPatch
    arr= FancyArrowPatch(posA=(numpy.pi+0.1,1.8),
                         posB=(3*numpy.pi/2.+0.1,1.8),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (numpy.pi/8.-0.05),
                         shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(numpy.pi+0.17,1.7,r'$\mathrm{Galactic\ rotation}$',
                        rotation=-30.,size=9.)
    radii= numpy.array([0.5,1.,1.5,2.,2.5])
    labels= []
    for r in radii:
        ax.plot(numpy.linspace(0.,2.*numpy.pi,501,),
                numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5)
        labels.append(r'$%i$' % int(r*8.))
    pyplot.rgrids(radii,labels=labels,angle=147.5)
    thetaticks = numpy.arange(0,360,45)
    # set ticklabels location at x times the axes' radius
    ax.set_thetagrids(thetaticks,frac=1.16,backgroundcolor='w',zorder=3)
    bovy_plot.bovy_text(3.*numpy.pi/4.+0.06,2.095,r'$\mathrm{kpc}$',size=10.)
    pyplot.ylim(0.,2.8)
    #Plot the box
    xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101)
    ys= numpy.ones(101)*(_RCYMIN-2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101)
    ys= numpy.ones(101)*(_RCYMAX+2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101)
    xs= numpy.ones(101)*(_RCXMIN-2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101)
    xs= numpy.ones(101)*(_RCXMAX+2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the connectors on the modelAxes
    xlow=-4.*8.
    ylow= 2.77*8.
    xs= numpy.linspace(xlow,(_RCXMAX+2.25),101)
    ys= (ylow-(_RCYMAX+2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2)
    line[0].set_clip_on(False)
    xlow=-4.*8.
    ylow= -2.77*8.
    xs= numpy.linspace(xlow,(_RCXMAX+2.25),101)
    ys= (ylow-(_RCYMIN-2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2)
    line[0].set_clip_on(False)
    #Colorbar
    cbaxes = pyplot.axes([0.01+2.*axdx,(1.-tdy)/2.+tdy+0.065,axdx-0.125,0.02])
    CB1= pyplot.colorbar(out,orientation='horizontal',
                         cax=cbaxes,ticks=[-150.,-75.,0.,75.,150.])
    #CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.)
    bovy_plot.bovy_end_print(plotfilename,dpi=300)
    return None
Ejemplo n.º 25
0
def plot_distancedist(basesavefilename):
    #First read the sample
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Histogram
    bovy_plot.bovy_print(fig_width=6.)
    bovy_plot.bovy_hist(data['RC_DIST'],
                        histtype='step',
                        color='k',
                        lw=1.5,
                        bins=51,
                        xrange=[0.,10.],
                        xlabel=r'$\mathrm{distance}\,(\mathrm{kpc})$',
                        ylabel=r'$\mathrm{Number\ of\ stars}$',zorder=10)
    ax= pyplot.gca()
    ax2= ax.twinx()
    pyplot.sca(ax2)
    bovy_plot.bovy_plot(sorted(data['RC_DIST']),
                        numpy.linspace(1./len(data),1.,len(data)),
                        'k-',
                        overplot=True)
    ax2.set_xlim(0.,10.)
    ax2.set_ylim(0.,1.)
    bovy_plot._add_ticks()
    ax2.set_ylabel(r'$\mathrm{cumulative\ distribution}$')
    bovy_plot.bovy_end_print(basesavefilename+'_hist.'+_EXT)
    #RZ
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['RC_GALR'],data['RC_GALZ'],
                        'k.',ms=2.,
                        xrange=[0.,16.],
                        yrange=[-3.,3.],
                        xlabel=r'$R\,(\mathrm{kpc})$',
                        ylabel=r'$Z\,(\mathrm{kpc})$',
                        onedhists=True)
    xarr, dx=1.5, -1.
    from matplotlib.patches import FancyArrowPatch
    _legendsize= 16
    arr= FancyArrowPatch(posA=(xarr+0.05,0.),
                         posB=(xarr+dx*10./8.,0.),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (0.), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    bovy_plot.bovy_text(xarr+7.*dx/8.,-0.45,r'$\mathrm{GC}$',
                        size=_legendsize)
    arr= FancyArrowPatch(posA=(1.5,-0.05),
                         posB=(1.5,.75),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (0.), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                                 mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    bovy_plot.bovy_text(1.59,0.2,r'$\mathrm{NGP}$',
                        size=_legendsize)
    bovy_plot.bovy_end_print(basesavefilename+'_RZ.'+_EXT)
    #XY
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['RC_GALR']*numpy.cos(data['RC_GALPHI']),
                        data['RC_GALR']*numpy.sin(data['RC_GALPHI']),
                        'k.',
                        xrange=[0.,16.],
                        yrange=[5.,-5.],
                        xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$',
                        ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$',
                        onedhists=True,ms=2.)
    xarr, dx= 2.2, -2.
    arr= FancyArrowPatch(posA=(xarr,0.),
                         posB=(xarr+dx,0.),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (0.), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    bovy_plot.bovy_text(xarr+7.*dx/8.,-0.25,r'$\mathrm{GC}$',
                        size=_legendsize)
    xcen, ycen, dr, t= -2., 0., 4., 14.*numpy.pi/180.
    arr= FancyArrowPatch(posA=(xcen+dr*numpy.cos(t),
                               ycen+dr*numpy.sin(t)),
                         posB=(xcen+dr*numpy.cos(-t),
                               ycen+dr*numpy.sin(-t)),
                         arrowstyle='<-', 
                         connectionstyle='arc3,rad=%4.2f' % (2.*t), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_end_print(basesavefilename+'_XY.'+_EXT)
Ejemplo n.º 26
0
def waveregions(*args,**kwargs):
    """
    NAME:
       waveregions
    PURPOSE:
       plot selected regions of the spectrum in one row
    INPUT:
       Either:
          (a) wavelength, spectrum (\AA,spectrum units)
          (b) spectrum (assumed on standard APOGEE re-sampled wavelength grid)
          (c) location ID, APOGEE ID (default loads aspcapStar, loads extension ext(=1); apStar=True loads apStar spectrum)
    KEYWORDS:
       File loading:
          ext= (1) extension to load
          apStar= (False) if True, load the apStar spectrum
          apStarIndx= (1) index in the apStar spectrum to load
       Chunks position:
          startlams, endlams= start and end wavelength in \AA of the various chunks (takes precedence over startindxs, endindxs)
          startindxs, endindxs= star and end index in the wavelength array of the various chunks
       Plotting-specific keywords
          labelLines= (True) label some lines
          noMolecLines= (False) don't label the molecules
          cleanZero= (True) replace <= zero entries with NaN
          labelID= A string ID that will be placed in the top-left corner
          labelTeff, labellogg, labelmetals, labelafe= parameter labels that will be placed in the top-right corner
          noxlabel= (False) if True, don't label the x axis
          pyplot.plot args and kwargs
    OUTPUT:
       plot to output
       The final axes allow one to put additional labels on the plot, e.g., for adding the APOGEE ID:
       bovy_plot.bovy_text(r'$\mathrm{%s}$' % '2M02420597+0837017',top_left=True)       
       Note that an ID (e.g., the apogee ID) and Teff, logg, metallicity, and alpha-enhancement labels can be added using the keywords label* above
    HISTORY:
       2015-01-18 - Written (based on older code) - Bovy (IAS)
    """
    # Grab non-pyplot.plot kwargs
    apStar= kwargs.pop('apStar',False)
    labelLines= kwargs.pop('labelLines',not 'overplot' in kwargs)
    noMolecLines= kwargs.pop('noMolecLines',False)
    cleanZero= kwargs.pop('cleanZero',True)
    noxticks= kwargs.pop('_noxticks',False)
    noxlabel= kwargs.pop('noxlabel',False)
    noskipdiags= kwargs.pop('_noskipdiags',False)
    labelwav= kwargs.pop('_labelwav',False)
    plotw= kwargs.pop('_plotw',None)
    markLines= kwargs.pop('markLines',False)
    markwav= kwargs.pop('_markwav',None)
    # Labels
    labelID= kwargs.pop('labelID',None)
    labelTeff= kwargs.pop('labelTeff',None)
    labellogg= kwargs.pop('labellogg',None)
    labelmetals= kwargs.pop('labelmetals',None)
    labelafe= kwargs.pop('labelafe',None)
    # Clean bad lines
    if cleanZero:
        args[1][args[1] <= 0.]= numpy.nan
    # Chunk parameters
    if 'startlams' in kwargs:
        # Turn startlams into a startindxs and similar for endlams
        startlams= kwargs.pop('startlams')
        endlams= kwargs.pop('endlams')
        startindxs= []
        endindxs= []
        for ii in range(len(startlams)):
            startindxs.append(numpy.argmin(numpy.fabs(startlams[ii]-args[0])))
            endindxs.append(numpy.argmin(numpy.fabs(endlams[ii]-args[0])))
    else:
        startindxs= kwargs.pop('startindxs',
                               [322,1794,2707,3850,4740,5820,7185])
        endindxs= kwargs.pop('endindxs',
                             [590,1940,2857,4025,5070,5955,7400])
    nregions= len(startindxs)
    # Calculate the width of the plot
    dx= numpy.array([args[0][numpy.amin([len(args[0])-1,endindxs[ii]])]\
                         -args[0][numpy.amax([0,startindxs[ii]-1])] \
                         for ii in range(nregions)],
                    dtype='float')
    # Adjust 0 (and -1) to start (end) a little further
    startendskip= kwargs.pop('_startendskip',_STARTENDSKIP)
    dx[0]= args[0][numpy.amin([len(args[0])-1,endindxs[0]])]\
        -args[0][numpy.amax([0,startindxs[0]-startendskip])] 
    dx[-1]= args[0][numpy.amin([len(args[0])-1,endindxs[-1]+startendskip])]\
        -args[0][numpy.amax([0,startindxs[-1]-1])] 
    if nregions == 1: #special case
        dx= [args[0][numpy.amin([len(args[0])-1,endindxs[0]+startendskip])]\
                 -args[0][numpy.amax([0,startindxs[0]-startendskip])]]
    # Determine a good step for the tickmarks
    tickStepTmp= numpy.log10(numpy.sum(dx)/10.) % 1
    if tickStepTmp > numpy.log10(1.5) and tickStepTmp < numpy.log10(3.5):
        tickStep= 2.*10.**int(numpy.log10(numpy.sum(dx)/10.))
    elif tickStepTmp > numpy.log10(3.5) and tickStepTmp < numpy.log10(7.5):
        tickStep= 5.*10.**int(numpy.log10(numpy.sum(dx)/10.))
    else:
        tickStep= 10.**int(numpy.log10(numpy.sum(dx)/10.))
    dx/= numpy.sum(dx)
    if noxticks:
        totdx= 0.825
    else:
        totdx= 0.85
    skipdx= kwargs.pop('skipdx',0.015)
    dx*= (totdx-(nregions-1)*skipdx)
    # Setup plot
    overplot= kwargs.pop('overplot',False)
    if not overplot:
        bovy_plot.bovy_print(fig_width=kwargs.pop('fig_width',8.4),
                             fig_height=kwargs.pop('fig_height',2.5),
                             axes_labelsize=16,text_fontsize=14,
                             legend_fontsize=12,
                             xtick_labelsize=12,ytick_labelsize=12)
        pyplot.figure()
    if overplot:
        yrange= numpy.array(pyplot.gca().get_ylim())
        kwargs.pop('yrange',None) # pop if there
    elif apStar:
        yrange= kwargs.pop('yrange',[0.,1.1*numpy.nanmax(args[1])])
    else:
        yrange= kwargs.pop('yrange',[0.2,1.2])
    # Deal with the label
    if apStar:
        ylabel= kwargs.pop('ylabel',r'$f_\lambda(\lambda)\,(10^{-17}\,\mathrm{erg\, s}^{-1}\,\mathrm{cm}^{-2}\,\AA^{-1})$')
    else:
        ylabel= kwargs.pop('ylabel',r'$f/f_c(\lambda)$')
    kwargs['zorder']= kwargs.get('zorder',10)
    for ii in range(nregions):
        # Setup the axes
        if ii == 0:
            left, bottom, width, height= 0.1+(0.85-totdx)*2., 0.125, dx[ii],0.8
        else:
            left, bottom, width, height= 0.1+(0.85-totdx)*2.+numpy.cumsum(dx)[ii-1]+skipdx*ii,\
                0.125, dx[ii], 0.8
        thisax= pyplot.axes([left,bottom,width,height])
        fig= pyplot.gcf()
        fig.sca(thisax)
        startindx, endindx= startindxs[ii], endindxs[ii]
        if ii == 0 and nregions == 1:
            xrange=[args[0][numpy.amax([0,startindx-startendskip])]-_LAMBDASUB,
                    args[0][numpy.amin([len(args[0])-1,endindx+startendskip])]-_LAMBDASUB]
        elif ii == 0:
            xrange=[args[0][numpy.amax([0,startindx-startendskip])]-_LAMBDASUB,
                    args[0][numpy.amin([len(args[0])-1,endindx])]-_LAMBDASUB]
        elif ii == (nregions-1):
            xrange=[args[0][numpy.amax([0,startindx-1])]-_LAMBDASUB,
                    args[0][numpy.amin([len(args[0])-1,endindx+startendskip])]-_LAMBDASUB]
        else:
            xrange=[args[0][numpy.amax([0,startindx-1])]-_LAMBDASUB,
                    args[0][numpy.amin([len(args[0])-1,endindx])]-_LAMBDASUB]
        thisax.plot(args[0][startindx:endindx]-_LAMBDASUB,
                    args[1][startindx:endindx],
                    *args[2:],**kwargs)
        if not plotw is None:
            thisax.plot(args[0][startindx:endindx]-_LAMBDASUB,
                        plotw[startindx:endindx],
                        '-',lw=2.,color='0.65',zorder=1)
        thisax.set_xlim(xrange[0],xrange[1])
        thisax.set_ylim(yrange[0],yrange[1])
        if noxticks:
            nullfmtx= NullFormatter()         # no labels, assume 1\AA
            thisax.xaxis.set_major_formatter(nullfmtx)
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(2.))
        else:
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(tickStep))
        bovy_plot._add_ticks(xticks=True-noxticks)
        if ii > 0:
            nullfmt   = NullFormatter()         # no labels
            thisax.yaxis.set_major_formatter(nullfmt)
        elif not overplot:
            pyplot.ylabel(ylabel)
        # Remove spines between different wavelength regions
        if ii == 0 and not nregions == 1:
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(right=False,which='both')
        elif ii == (nregions-1) and not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False,which='both')
        elif not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False,which='both')
            thisax.tick_params(right=False,which='both')
        # Plot cut-out markers
        cutOutkwargs = dict(transform=thisax.transAxes,color='k',
                            clip_on=False)
        if not noskipdiags:
            d = .015 # how big to make the diagonal lines in axes coordinates
            slope= 1./(dx[ii]+0.2*skipdx)/3.
            if ii == 0 and not nregions == 1:
                thisax.plot((1-slope*d,1+slope*d),(-d,+d), **cutOutkwargs)
                thisax.plot((1-slope*d,1+slope*d),(1-d,1+d), **cutOutkwargs)
            elif ii == (nregions-1) and not nregions == 1:
                thisax.plot((-slope*d,+slope*d),(-d,+d), **cutOutkwargs)
                thisax.plot((-slope*d,+slope*d),(1-d,1+d), **cutOutkwargs)
            elif not nregions == 1:
                thisax.plot((1-slope*d,1+slope*d),(-d,+d), **cutOutkwargs)
                thisax.plot((1-slope*d,1+slope*d),(1-d,1+d), **cutOutkwargs)
                thisax.plot((-slope*d,+slope*d),(-d,+d), **cutOutkwargs)
                thisax.plot((-slope*d,+slope*d),(1-d,1+d), **cutOutkwargs)
        else: #plot gray bands
            cutOutkwargs['color']= '0.5'
            thisax.fill_between((1.,1.+skipdx),(0.,0.),(1.,1.),**cutOutkwargs)
        # Label the lines
        if labelLines:
            _label_all_lines(args[0][startindx],args[0][endindx],
                             thisax,args[0],args[1],noMolecLines)
        # Mark the lines
        if markLines:
           _mark_lines(markwav,args[0][startindx],args[0][endindx],
                       thisax,args[0],args[1])
        # Label the largest round wavelength in angstrom for windows
        if labelwav:
            bovy_plot.bovy_text(2*numpy.floor((xrange[1]-(nregions > 15))/2.),
                                yrange[0]+0.05*(yrange[1]-yrange[0]),
                                r'$\lambda\kern 0.1em%i,%03i$' % (15+int(numpy.floor(xrange[1]/1000.)),
                                                        int(2.*numpy.floor((xrange[1]-(nregions > 15))/2.) % 1000.)),
                                horizontalalignment='center',
                                verticalalignment='bottom',
                                rotation='vertical',fontsize=10.)
    # Add the x-axis label
    if not nregions == 1:
        thisax= pyplot.axes([0.1+(0.85-totdx)*2.,0.125,totdx,0.8])
        pyplot.gcf().sca(thisax)
        thisax.set_ylim(yrange[0],yrange[1])
        thisax.spines['left'].set_visible(False)
        thisax.spines['right'].set_visible(False)
        thisax.spines['bottom'].set_visible(False)
        thisax.spines['top'].set_visible(False)
        thisax.tick_params(labelleft='off')
        thisax.tick_params(left=False,which='both')
        thisax.tick_params(right=False,which='both')
        thisax.tick_params(labelbottom='off')
        thisax.tick_params(bottom=False,which='both')
        thisax.tick_params(top=False,which='both')
    if not overplot and not noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda-%i,000\,(\AA)$' % (int(_LAMBDASUB/1000.)),
                          labelpad=10-(nregions == 1)*10)
    elif not overplot and noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda\,(\AA)$',
                          labelpad=3-(nregions == 1)*3)
    if not nregions == 1:
        thisax.set_zorder(-1)
        # Start another axis object for later labeling
        thisax= pyplot.axes([0.1+(0.85-totdx)*2.,0.125,totdx,0.8])
        pyplot.gcf().sca(thisax)
        thisax.patch.set_facecolor('None')
        thisax.set_zorder(10)
    # Labels
    if not labelID is None:
        bovy_plot.bovy_text(r'$\mathrm{%s}$' % labelID,
                            top_left=True,fontsize=10)
    if not labelTeff is None or not labellogg is None \
            or not labelmetals is None or not labelafe is None:
        nParamLabels= int(not labelTeff is None)\
            +int(not labellogg is None)\
            +int(not labelmetals is None)\
            +int(not labelafe is None)
        # Label parameters
        paramStr= ''
        if not labelTeff is None:
            paramStr+= r'T_\mathrm{eff}= %i\,\mathrm{K}' % (int(labelTeff))
            nParamLabels-= 1
            if nParamLabels > 0:
                paramStr+= ',\ '
        if not labellogg is None:
            paramStr+= r'\log g= %.1f' % labellogg
            nParamLabels-= 1
            if nParamLabels > 0:
                paramStr+= ',\ '
        if not labelmetals is None:
            paramStr+= r'[\mathrm{M/H}]= %.2f' % labelmetals
            nParamLabels-= 1
            if nParamLabels > 0:
                paramStr+= ',\ '
        if not labelafe is None:
            paramStr+= r'[\alpha/\mathrm{M}]= %.2f' % labelafe
            nParamLabels-= 1
            if nParamLabels > 0:
                paramStr+= ',\ '           
        bovy_plot.bovy_text(r'$%s$' % paramStr,top_right=True,fontsize=10)
    return None
Ejemplo n.º 27
0
def showExample(filename='../data/SDSSJ203817.37+003029.8.fits',band='g',
                constraints=None,basefilename='SDSSJ203817.37+003029.8'):
    """
    NAME:
       showExample
    PURPOSE:
       show an example of a power-law structure function GP covariance function
       fit to an SDSS quasar
    INPUT:
       filename - filename with the data
       band - band to consider
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
    OUTPUT:
       writes several plots
    HISTORY:
       2010-06-20 - Written - Bovy (NYU)
    """
    file= fu.table_fields(filename)
    if band == 'u':
        mjd_g= nu.array(file.mjd_u)/365.25
        g= nu.array(file.u)
        err_g= nu.array(file.err_u)
    elif band == 'g':
        mjd_g= nu.array(file.mjd_g)/365.25
        g= nu.array(file.g)
        err_g= nu.array(file.err_g)
    elif band == 'r':
        mjd_g= nu.array(file.mjd_r)/365.25
        g= nu.array(file.r)
        err_g= nu.array(file.err_r)
    elif band == 'i':
        mjd_g= nu.array(file.mjd_i)/365.25
        g= nu.array(file.i)
        err_g= nu.array(file.err_i)
    elif band == 'z':
        mjd_g= nu.array(file.mjd_z)/365.25
        g= nu.array(file.z)
        err_g= nu.array(file.err_z)

    mask= (mjd_g != 0)*(g < 20.6)*(g > 19.7)#Adjust for non-g
    g= g[mask]
    g-= nu.mean(g)
    err_g= err_g[mask]
    mjd_g= mjd_g[mask]
    mjd_g-= nu.amin(mjd_g)
    meanErr_g= nu.mean(err_g)


    nu.random.seed(4)
    nGP=5
    nx=201
    params_mean= ()
    from powerlawSFgr import covarFunc
    params= {'logA': array([ 1.63714183]), 'gamma': array([ 0.60216581])}
    params= {'gamma': array([ 0.49500723]), 'logA': array([-3.36044037])}
    cf= covarFunc(**params)
    params_covar= (cf)
    ndata= len(g)
    if constraints is None:
        listx= mjd_g
        listy= g
        noise= err_g
        trainSet= trainingSet(listx=listx,listy=listy,noise=noise)
        constraints= trainSet
    else:
        constraints= None

    useconstraints= constraints
    xs= nu.linspace(-0.1,6.5,nx)
    GPsamples= eval_gp(xs,mean,covar,(),params_covar,nGP=nGP,constraints=useconstraints)
    thismean= calc_constrained_mean(xs,mean,params_mean,covar,params_covar,useconstraints)
    thiscovar= calc_constrained_covar(xs,covar,params_covar,useconstraints)
    plot.bovy_print()
    pyplot.plot(xs,GPsamples[0,:],'-',color='0.25')
    if not constraints is None:
        plot.bovy_plot(mjd_g,g,'k.',zorder=5,ms=10,overplot=True)
    plot.bovy_text(r'$\mathrm{'+basefilename+r'}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(nGP):
        pyplot.plot(xs,GPsamples[ii,:],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints == []:
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$m-\langle m\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    pyplot.ylim(-1.,1.)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_full.ps')

    plot.bovy_print()
    pyplot.plot(xs,GPsamples[0,:],'-',color='0.25')
    if not constraints is None:
        plot.bovy_plot(mjd_g,g,'k.',zorder=5,ms=10,overplot=True)
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(xs,GPsamples[ii,:],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints == []:
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$m-\langle m\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(3,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_zoom.ps')


    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        pyplot.loglog(sc.arange(1.,len(GPsamples[ii,:])/2)*(xs[1]-xs[0]),
                      2.*sc.var(GPsamples[ii,:])-2.*sc.correlate(GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),"same")[1:len(GPsamples[ii,:])/2][::-1]/len(GPsamples[ii,:]),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(xs[1]-xs[0]),xs[len(xs)/2]]
    pyplot.loglog(xline,nu.exp(-3.02045715)*nu.array(xline)**(0.5868293),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfunc.ps')
Ejemplo n.º 28
0
def plot_bestfit(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    # Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  # if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata,
    )
    # HACK
    indx = data["J0MAG"] - data["K0MAG"] < 0.5
    data["J0MAG"][indx] = 0.5 + data["K0MAG"][indx]
    # Cut inner disk locations
    # data= data[(data['GLON'] > 75.)]
    # Cut outliers
    # data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    # Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, "rb")
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        if options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            # Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data["LOCATION"]))
            iso = []
            for ii in range(len(locs)):
                indx = data["LOCATION"] == locs[ii]
                locl = numpy.mean(data["GLON"][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, marginalizefeh=True, glon=locl)
                )
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, expsfh=options.expsfh)
        if options.dwarf:
            iso = [iso, isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, dwarf=True, expsfh=options.expsfh)]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, "wb")
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data["H0MAG"][ii] - dm
        if options.indivfeh:
            # Find closest Z
            thisZ = isodist.FEH2Z(data[ii]["FEH"])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        elif options.varfeh:
            # Find correct iso
            indx = locl == data[ii]["LOCATION"]
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF, _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data["H0MAG"][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    else:
        logpisodwarf = None
    # Calculate data means etc.
    # Calculate means
    locations = list(set(data["LOCATION"]))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    sigerr_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = data["LOCATION"] == locations[ii]
        l_plate[ii] = numpy.mean(data["GLON"][indx])
        avg_plate[ii] = numpy.mean(data["VHELIO"][indx])
        sig_plate[ii] = numpy.std(data["VHELIO"][indx])
        siga_plate[ii] = numpy.std(data["VHELIO"][indx]) / numpy.sqrt(numpy.sum(indx))
        sigerr_plate[ii] = bootstrap_sigerr(data["VHELIO"][indx])
    # Calculate plate means and variances from the model
    # Load initial parameters from file
    savefile = open(args[0], "rb")
    params = pickle.load(savefile)
    if not options.index is None:
        params = params[options.index]
    savefile.close()
    # params[0]= 245./235.
    # params[1]= 8.5/8.
    avg_plate_model = numpy.zeros(nlocs)
    sig_plate_model = numpy.zeros(nlocs)
    for ii in range(nlocs):
        # Calculate vlos | los
        indx = data["LOCATION"] == locations[ii]
        thesedata = data[indx]
        thislogpiso = logpiso[indx, :]
        if options.dwarf:
            thislogpisodwarf = logpisodwarf[indx, :]
        else:
            thislogpisodwarf = None
        vlos = numpy.linspace(-200.0, 200.0, options.nvlos)
        pvlos = numpy.zeros(options.nvlos)
        if not options.multi is None:
            pvlos = multi.parallel_map(
                (lambda x: pvlosplate(params, vlos[x], thesedata, df, options, thislogpiso, thislogpisodwarf, iso)),
                range(options.nvlos),
                numcores=numpy.amin([len(vlos), multiprocessing.cpu_count(), options.multi]),
            )
        else:
            for jj in range(options.nvlos):
                print jj
                pvlos[jj] = pvlosplate(params, vlos[jj], thesedata, df, options, thislogpiso, thislogpisodwarf, iso)
        pvlos -= logsumexp(pvlos)
        pvlos = numpy.exp(pvlos)
        # Calculate mean and velocity dispersion
        avg_plate_model[ii] = numpy.sum(vlos * pvlos)
        sig_plate_model[ii] = numpy.sqrt(numpy.sum(vlos ** 2.0 * pvlos) - avg_plate_model[ii] ** 2.0)
    # Plot everything
    left, bottom, width, height = 0.1, 0.4, 0.8, 0.5
    axTop = pyplot.axes([left, bottom, width, height])
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.3
    axMean = pyplot.axes([left, bottom, width, height])
    # left, bottom, width, height= 0.1, 0.1, 0.8, 0.2
    # axSig= pyplot.axes([left,bottom,width,height])
    fig = pyplot.gcf()
    fig.sca(axTop)
    pyplot.ylabel(r"$\mathrm{Heliocentric\ velocity}\ [\mathrm{km\ s}^{-1}]$")
    pyplot.xlabel(r"$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$")
    pyplot.xlim(0.0, 360.0)
    pyplot.ylim(-200.0, 200.0)
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_plot(data["GLON"], data["VHELIO"], "k,", yrange=[-200.0, 200.0], xrange=[0.0, 360.0], overplot=True)
    ndata_t = int(math.floor(len(data) / 1000.0))
    ndata_h = len(data) - ndata_t * 1000
    bovy_plot.bovy_plot(l_plate, avg_plate, "o", overplot=True, mfc="0.5", mec="none")
    bovy_plot.bovy_plot(l_plate, avg_plate_model, "x", overplot=True, ms=10.0, mew=1.5, color="0.7")
    # Legend
    bovy_plot.bovy_plot([260.0], [150.0], "k,", overplot=True)
    bovy_plot.bovy_plot([260.0], [120.0], "o", mfc="0.5", mec="none", overplot=True)
    bovy_plot.bovy_plot([260.0], [90.0], "x", ms=10.0, mew=1.5, color="0.7", overplot=True)
    bovy_plot.bovy_text(270.0, 145.0, r"$\mathrm{data}$")
    bovy_plot.bovy_text(270.0, 115.0, r"$\mathrm{data\ mean}$")
    bovy_plot.bovy_text(270.0, 85.0, r"$\mathrm{model\ mean}$")
    bovy_plot._add_ticks()
    # Now plot the difference
    fig.sca(axMean)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model, "ko", overplot=True)
    pyplot.errorbar(
        l_plate, avg_plate - avg_plate_model, yerr=siga_plate, marker="o", color="k", linestyle="none", elinestyle="-"
    )
    pyplot.ylabel(r"$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}}$")
    pyplot.ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # axMean.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r"$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$")
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
    # Sigma
    fig.sca(axSig)
    pyplot.plot([0.0, 360.0], [1.0, 1.0], "-", color="0.5")
    bovy_plot.bovy_plot(l_plate, sig_plate / sig_plate_model, "ko", overplot=True)
    pyplot.errorbar(
        l_plate,
        sig_plate / sig_plate_model,
        yerr=sigerr_plate / sig_plate_model,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    pyplot.ylabel(r"$\sigma_{\mathrm{los}}^{\mathrm{data}}/ \sigma_{\mathrm{los}}^{\mathrm{model}}$")
    pyplot.ylim(0.5, 1.5)
Ejemplo n.º 29
0
 def plot_popmass(self):
     """
     NAME:
        plot_popmass
     PURPOSE:
        plot the stellar-population mass for each RC star
     INPUT:
         bovy_plot.bovy_plot **kwargs
     OUTPUT:
        bovy_plot.bovy_plot output
     HISTORY:
        2014-02-28 - Written in this form - Bovy (IAS)
     """
     if not _BOVY_PLOT_LOADED:
         raise ImportError("galpy.util.bovy_plot could not be imported")
     fehs = numpy.linspace(-1., 0.5, 101)
     lages = self._coarselages
     plotthis = numpy.empty((len(fehs), len(lages)))
     for ii in range(len(fehs)):
         for jj in range(len(lages)):
             plotthis[ii, jj] = self.popmass(fehs[ii], lages[jj])
     fig = pyplot.gcf()
     left, bottom, width, height = 0.1, 0.1, 0.8, 0.6
     axBottom = pyplot.axes([left, bottom, width, height])
     fig.sca(axBottom)
     xlimits = [fehs[0], fehs[-1]]
     dlages = (lages[1] - lages[0])
     ylimits = [lages[0] - dlages, lages[-1] + dlages]
     vmin, vmax = 0., 50000.
     vmin2, vmax2 = 0., 25000.
     zlabel = r'$\mathrm{Stellar\ population\ mass\ per\ RC\ star}\,(M_\odot)$'
     xlabel = r'$[\mathrm{Fe/H}]\,(\mathrm{dex})$'
     out = bovy_plot.bovy_dens2d(plotthis.T,
                                 origin='lower',
                                 cmap='jet',
                                 xrange=xlimits,
                                 yrange=ylimits,
                                 vmin=vmin,
                                 vmax=vmax,
                                 interpolation='nearest',
                                 colorbar=True,
                                 shrink=.9,
                                 zlabel=zlabel,
                                 overplot=True)
     extent = xlimits + ylimits
     pyplot.axis(extent)
     bovy_plot._add_axislabels(
         xlabel, r'$\log_{10}\,\mathrm{Age} / 1\,\mathrm{Gyr}$')
     bovy_plot._add_ticks()
     left, bottom, width, height = 0.1, 0.68, 0.64, 0.2
     axTop = pyplot.axes([left, bottom, width, height])
     fig.sca(axTop)
     #Plot the average over SFH
     lages = numpy.linspace(-1., 1., 16)
     mtrend = numpy.zeros(len(self._zs))
     exppage = 10.**self._coarselages * numpy.exp(
         (10.**(self._coarselages + 2.)) / 800.)  #e.g., Binney (2010)
     exexppage = 10.**self._coarselages * numpy.exp(
         (10.**(self._coarselages + 2.)) / 100.)  #e.g., Binney (2010)
     page = 10.**self._coarselages
     plotthis = self._coarsemass[:-1, :] / self._omega[:-1, :]
     mtrend = 1. / (numpy.sum(page * 1. / plotthis, axis=1) /
                    numpy.sum(page))
     expmtrend = 1. / (numpy.sum(exppage * 1. / plotthis, axis=1) /
                       numpy.sum(exppage))
     exexpmtrend = 1. / (numpy.sum(exexppage * 1. / plotthis, axis=1) /
                         numpy.sum(exexppage))
     fehs = isodist.Z2FEH(self._zs[:-1], zsolar=zsolar())
     pyplot.plot(fehs, mtrend, 'k-')
     pyplot.plot(fehs, expmtrend, 'k--')
     pyplot.plot(fehs, exexpmtrend, 'k-.')
     pyplot.ylim(vmin2, vmax2)
     pyplot.xlim(xlimits[0], xlimits[1])
     nullfmt = NullFormatter()  # no labels
     thisax = pyplot.gca()
     thisax.xaxis.set_major_formatter(nullfmt)
     bovy_plot._add_ticks()
     return out
Ejemplo n.º 30
0
def waveregions(*args, **kwargs):
    """
    NAME:
       waveregions
    PURPOSE:
       plot selected regions of the spectrum in one row
    INPUT:
       Either:
          (a) wavelength, spectrum (\AA,spectrum units)
          (b) spectrum (assumed on standard APOGEE re-sampled wavelength grid)
          (c) location ID, APOGEE ID (default loads aspcapStar, loads extension ext(=1); apStar=True loads apStar spectrum)
    KEYWORDS:
       File loading:
          ext= (1) extension to load
          apStar= (False) if True, load the apStar spectrum
          apStarIndx= (1) index in the apStar spectrum to load
       Chunks position:
          startlams, endlams= start and end wavelength in \AA of the various chunks (takes precedence over startindxs, endindxs)
          startindxs, endindxs= star and end index in the wavelength array of the various chunks
       Plotting-specific keywords
          labelLines= (True) label some lines
          noMolecLines= (False) don't label the molecules
          cleanZero= (True) replace <= zero entries with NaN
          labelID= A string ID that will be placed in the top-left corner
          labelTeff, labellogg, labelmetals, labelafe= parameter labels that will be placed in the top-right corner
          noxlabel= (False) if True, don't label the x axis
          pyplot.plot args and kwargs
    OUTPUT:
       plot to output
       The final axes allow one to put additional labels on the plot, e.g., for adding the APOGEE ID:
       bovy_plot.bovy_text(r'$\mathrm{%s}$' % '2M02420597+0837017',top_left=True)       
       Note that an ID (e.g., the apogee ID) and Teff, logg, metallicity, and alpha-enhancement labels can be added using the keywords label* above
    HISTORY:
       2015-01-18 - Written (based on older code) - Bovy (IAS)
    """
    # Grab non-pyplot.plot kwargs
    apStar = kwargs.pop('apStar', False)
    labelLines = kwargs.pop('labelLines', not 'overplot' in kwargs)
    noMolecLines = kwargs.pop('noMolecLines', False)
    cleanZero = kwargs.pop('cleanZero', True)
    noxticks = kwargs.pop('_noxticks', False)
    noxlabel = kwargs.pop('noxlabel', False)
    noskipdiags = kwargs.pop('_noskipdiags', False)
    labelwav = kwargs.pop('_labelwav', False)
    plotw = kwargs.pop('_plotw', None)
    markLines = kwargs.pop('markLines', False)
    markwav = kwargs.pop('_markwav', None)
    # Labels
    labelID = kwargs.pop('labelID', None)
    labelTeff = kwargs.pop('labelTeff', None)
    labellogg = kwargs.pop('labellogg', None)
    labelmetals = kwargs.pop('labelmetals', None)
    labelafe = kwargs.pop('labelafe', None)
    # Clean bad lines
    if cleanZero:
        args[1][args[1] <= 0.] = numpy.nan
    # Chunk parameters
    if 'startlams' in kwargs:
        # Turn startlams into a startindxs and similar for endlams
        startlams = kwargs.pop('startlams')
        endlams = kwargs.pop('endlams')
        startindxs = []
        endindxs = []
        for ii in range(len(startlams)):
            startindxs.append(numpy.argmin(numpy.fabs(startlams[ii] -
                                                      args[0])))
            endindxs.append(numpy.argmin(numpy.fabs(endlams[ii] - args[0])))
    else:
        startindxs = kwargs.pop('startindxs',
                                [322, 1794, 2707, 3850, 4740, 5820, 7185])
        endindxs = kwargs.pop('endindxs',
                              [590, 1940, 2857, 4025, 5070, 5955, 7400])
    nregions = len(startindxs)
    # Calculate the width of the plot
    dx= numpy.array([args[0][numpy.amin([len(args[0])-1,endindxs[ii]])]\
                         -args[0][numpy.amax([0,startindxs[ii]-1])] \
                         for ii in range(nregions)],
                    dtype='float')
    # Adjust 0 (and -1) to start (end) a little further
    startendskip = kwargs.pop('_startendskip', _STARTENDSKIP)
    dx[0]= args[0][numpy.amin([len(args[0])-1,endindxs[0]])]\
        -args[0][numpy.amax([0,startindxs[0]-startendskip])]
    dx[-1]= args[0][numpy.amin([len(args[0])-1,endindxs[-1]+startendskip])]\
        -args[0][numpy.amax([0,startindxs[-1]-1])]
    if nregions == 1:  #special case
        dx= [args[0][numpy.amin([len(args[0])-1,endindxs[0]+startendskip])]\
                 -args[0][numpy.amax([0,startindxs[0]-startendskip])]]
    # Determine a good step for the tickmarks
    tickStepTmp = numpy.log10(numpy.sum(dx) / 10.) % 1
    if tickStepTmp > numpy.log10(1.5) and tickStepTmp < numpy.log10(3.5):
        tickStep = 2. * 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    elif tickStepTmp > numpy.log10(3.5) and tickStepTmp < numpy.log10(7.5):
        tickStep = 5. * 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    else:
        tickStep = 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    dx /= numpy.sum(dx)
    if noxticks:
        totdx = 0.825
    else:
        totdx = 0.85
    skipdx = kwargs.pop('skipdx', 0.015)
    dx *= (totdx - (nregions - 1) * skipdx)
    # Setup plot
    overplot = kwargs.pop('overplot', False)
    if not overplot:
        bovy_plot.bovy_print(fig_width=kwargs.pop('fig_width', 8.4),
                             fig_height=kwargs.pop('fig_height', 2.5),
                             axes_labelsize=16,
                             text_fontsize=14,
                             legend_fontsize=12,
                             xtick_labelsize=12,
                             ytick_labelsize=12)
        pyplot.figure()
    if overplot:
        yrange = numpy.array(pyplot.gca().get_ylim())
        kwargs.pop('yrange', None)  # pop if there
    elif apStar:
        yrange = kwargs.pop('yrange', [0., 1.1 * numpy.nanmax(args[1])])
    else:
        yrange = kwargs.pop('yrange', [0.2, 1.2])
    # Deal with the label
    if apStar:
        ylabel = kwargs.pop(
            'ylabel',
            r'$f_\lambda(\lambda)\,(10^{-17}\,\mathrm{erg\, s}^{-1}\,\mathrm{cm}^{-2}\,\AA^{-1})$'
        )
    else:
        ylabel = kwargs.pop('ylabel', r'$f/f_c(\lambda)$')
    kwargs['zorder'] = kwargs.get('zorder', 10)
    for ii in range(nregions):
        # Setup the axes
        if ii == 0:
            left, bottom, width, height = 0.1 + (
                0.85 - totdx) * 2., 0.125, dx[ii], 0.8
        else:
            left, bottom, width, height= 0.1+(0.85-totdx)*2.+numpy.cumsum(dx)[ii-1]+skipdx*ii,\
                0.125, dx[ii], 0.8
        thisax = pyplot.axes([left, bottom, width, height])
        fig = pyplot.gcf()
        fig.sca(thisax)
        startindx, endindx = startindxs[ii], endindxs[ii]
        if ii == 0 and nregions == 1:
            xrange = [
                args[0][numpy.amax([0, startindx - startendskip])] -
                _LAMBDASUB, args[0][numpy.amin(
                    [len(args[0]) - 1, endindx + startendskip])] - _LAMBDASUB
            ]
        elif ii == 0:
            xrange = [
                args[0][numpy.amax([0, startindx - startendskip])] -
                _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx])] - _LAMBDASUB
            ]
        elif ii == (nregions - 1):
            xrange = [
                args[0][numpy.amax([0, startindx - 1])] - _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx + startendskip
                                    ])] - _LAMBDASUB
            ]
        else:
            xrange = [
                args[0][numpy.amax([0, startindx - 1])] - _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx])] - _LAMBDASUB
            ]
        thisax.plot(args[0][startindx:endindx] - _LAMBDASUB,
                    args[1][startindx:endindx], *args[2:], **kwargs)
        if not plotw is None:
            thisax.plot(args[0][startindx:endindx] - _LAMBDASUB,
                        plotw[startindx:endindx],
                        '-',
                        lw=2.,
                        color='0.65',
                        zorder=1)
        thisax.set_xlim(xrange[0], xrange[1])
        thisax.set_ylim(yrange[0], yrange[1])
        if noxticks:
            nullfmtx = NullFormatter()  # no labels, assume 1\AA
            thisax.xaxis.set_major_formatter(nullfmtx)
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(2.))
        else:
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(tickStep))
        bovy_plot._add_ticks(xticks=True - noxticks)
        if ii > 0:
            nullfmt = NullFormatter()  # no labels
            thisax.yaxis.set_major_formatter(nullfmt)
        elif not overplot:
            pyplot.ylabel(ylabel)
        # Remove spines between different wavelength regions
        if ii == 0 and not nregions == 1:
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(right=False, which='both')
        elif ii == (nregions - 1) and not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False, which='both')
        elif not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False, which='both')
            thisax.tick_params(right=False, which='both')
        # Plot cut-out markers
        cutOutkwargs = dict(transform=thisax.transAxes,
                            color='k',
                            clip_on=False)
        if not noskipdiags:
            d = .015  # how big to make the diagonal lines in axes coordinates
            slope = 1. / (dx[ii] + 0.2 * skipdx) / 3.
            if ii == 0 and not nregions == 1:
                thisax.plot((1 - slope * d, 1 + slope * d), (-d, +d),
                            **cutOutkwargs)
                thisax.plot((1 - slope * d, 1 + slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
            elif ii == (nregions - 1) and not nregions == 1:
                thisax.plot((-slope * d, +slope * d), (-d, +d), **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
            elif not nregions == 1:
                thisax.plot((1 - slope * d, 1 + slope * d), (-d, +d),
                            **cutOutkwargs)
                thisax.plot((1 - slope * d, 1 + slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (-d, +d), **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
        else:  #plot gray bands
            cutOutkwargs['color'] = '0.5'
            thisax.fill_between((1., 1. + skipdx), (0., 0.), (1., 1.),
                                **cutOutkwargs)
        # Label the lines
        if labelLines:
            _label_all_lines(args[0][startindx], args[0][endindx], thisax,
                             args[0], args[1], noMolecLines)
        # Mark the lines
        if markLines:
            _mark_lines(markwav, args[0][startindx], args[0][endindx], thisax,
                        args[0], args[1])
        # Label the largest round wavelength in angstrom for windows
        if labelwav:
            bovy_plot.bovy_text(
                2 * numpy.floor((xrange[1] - (nregions > 15)) / 2.),
                yrange[0] + 0.05 * (yrange[1] - yrange[0]),
                r'$\lambda\kern 0.1em%i,%03i$' %
                (15 + int(numpy.floor(xrange[1] / 1000.)),
                 int(2. * numpy.floor(
                     (xrange[1] - (nregions > 15)) / 2.) % 1000.)),
                horizontalalignment='center',
                verticalalignment='bottom',
                rotation='vertical',
                fontsize=10.)
    # Add the x-axis label
    if not nregions == 1:
        thisax = pyplot.axes([0.1 + (0.85 - totdx) * 2., 0.125, totdx, 0.8])
        pyplot.gcf().sca(thisax)
        thisax.set_ylim(yrange[0], yrange[1])
        thisax.spines['left'].set_visible(False)
        thisax.spines['right'].set_visible(False)
        thisax.spines['bottom'].set_visible(False)
        thisax.spines['top'].set_visible(False)
        thisax.tick_params(labelleft='off')
        thisax.tick_params(left=False, which='both')
        thisax.tick_params(right=False, which='both')
        thisax.tick_params(labelbottom='off')
        thisax.tick_params(bottom=False, which='both')
        thisax.tick_params(top=False, which='both')
    if not overplot and not noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda-%i,000\,(\AA)$' %
                          (int(_LAMBDASUB / 1000.)),
                          labelpad=10 - (nregions == 1) * 10)
    elif not overplot and noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda\,(\AA)$',
                          labelpad=3 - (nregions == 1) * 3)
    if not nregions == 1:
        thisax.set_zorder(-1)
        # Start another axis object for later labeling
        thisax = pyplot.axes([0.1 + (0.85 - totdx) * 2., 0.125, totdx, 0.8])
        pyplot.gcf().sca(thisax)
        thisax.patch.set_facecolor('None')
        thisax.set_zorder(10)
    # Labels
    if not labelID is None:
        bovy_plot.bovy_text(r'$\mathrm{%s}$' % labelID,
                            top_left=True,
                            fontsize=10)
    if not labelTeff is None or not labellogg is None \
            or not labelmetals is None or not labelafe is None:
        nParamLabels= int(not labelTeff is None)\
            +int(not labellogg is None)\
            +int(not labelmetals is None)\
            +int(not labelafe is None)
        # Label parameters
        paramStr = ''
        if not labelTeff is None:
            paramStr += r'T_\mathrm{eff}= %i\,\mathrm{K}' % (int(labelTeff))
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labellogg is None:
            paramStr += r'\log g= %.1f' % labellogg
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labelmetals is None:
            paramStr += r'[\mathrm{M/H}]= %.2f' % labelmetals
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labelafe is None:
            paramStr += r'[\alpha/\mathrm{M}]= %.2f' % labelafe
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        bovy_plot.bovy_text(r'$%s$' % paramStr, top_right=True, fontsize=10)
    return None
Ejemplo n.º 31
0
        r'$|b|\ <\ 2^\circ,\ |l|\ >\ 35^\circ$' + '\n' +
        r'$%i,%03i\ \mathrm{stars}$' % (ndata_t, ndata_h) + '\n' +
        r'$\mathrm{assuming}\ R_0\ =\ 8\ \mathrm{kpc}$' + '\n' +
        r'$\frac{\mathrm{d} v_{\mathrm{circ}}}{\mathrm{d}R}\ =\ 0\ \mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}$',
        top_right=True)
    #Legend
    pyplot.legend((line1, line2, line3),
                  (r'$v_{\mathrm{circ}}\ =\ 230\ \mathrm{km\ s}^{-1}$',
                   r'$v_{\mathrm{circ}}\ =\ 210\ \mathrm{km\ s}^{-1}$',
                   r'$v_{\mathrm{circ}}\ =\ 250\ \mathrm{km\ s}^{-1}$'),
                  loc='upper right',
                  bbox_to_anchor=(.9, .375),
                  numpoints=2,
                  prop={'size': 12},
                  frameon=False)
bovy_plot._add_ticks()
if noSolar:
    bovy_plot.bovy_end_print('apogee_vcirc_l_vhelio_noSolar.' + ext)
    sys.exit(0)
elif justSolar:
    bovy_plot.bovy_end_print('apogee_vcirc_l_vhelio_justSolar.' + ext)
    sys.exit(0)
fig.sca(axBottom)
#Interpolate prediction
interpolPred = interpolate.InterpolatedUnivariateSpline(
    ls, 250. * avg_pred - vsolar)
bovy_plot.bovy_plot(l_plate,
                    avg_plate - interpolPred(l_plate),
                    'ko',
                    overplot=True)
pyplot.errorbar(l_plate,
def illustrate_track(plotfilename1,plotfilename2,plotfilename3):
    #Setup stream model
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                  leading=True,nTrackChunks=_NTRACKCHUNKS,
                  tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.))
    #First calculate meanOmega and sigOmega
    mOs= numpy.array([sdf.meanOmega(t,oned=True) for t in sdf._thetasTrack])
    sOs= numpy.array([sdf.sigOmega(t) for t in sdf._thetasTrack])
    mOs-= sdf._progenitor_Omega_along_dOmega
    mOs*= -bovy_conversion.freq_in_Gyr(220.,8.)
    sOs*= bovy_conversion.freq_in_Gyr(220.,8.)
    progAngle= numpy.dot(sdf._progenitor_angle,sdf._dsigomeanProgDirection)
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs,'ko',ms=8.,
                        xlabel=r'$\theta_\parallel$',
                        ylabel=r'$\Omega_\parallel\,(\mathrm{Gyr}^{-1})$',
                        xrange=[-0.2-1.14,1.6-1.14],
                        yrange=[22.05,22.55])
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs,'k-',lw=1.5,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,
                        mOs[0]*numpy.ones(len(sdf._thetasTrack))+0.03,
                        'ko',ls='--',dashes=(20,10),lw=1.5,overplot=True,
                        ms=6.)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs+2*sOs,'ko',ms=6.,mfc='none',
                        zorder=1,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs-2*sOs,'ko',ms=6.,mfc='none',
                        zorder=1,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs+2*sOs,'k-.',lw=1.5,
                        zorder=0,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs-2*sOs,'k-.',lw=1.5,
                        zorder=0,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,sdf._progenitor_Omega_along_dOmega*bovy_conversion.freq_in_Gyr(220.,8.)*numpy.ones(len(sdf._thetasTrack)),
                        'k--',lw=1.5,overplot=True)
    bovy_plot.bovy_plot((sdf._thetasTrack+progAngle)[0],(sdf._progenitor_Omega_along_dOmega*bovy_conversion.freq_in_Gyr(220.,8.)*numpy.ones(len(sdf._thetasTrack)))[0],
                        'ko',ms=6.,overplot=True)
    bovy_plot.bovy_text(1.05+progAngle,22.475,r'$\mathrm{progenitor\ orbit}$',size=16.)
    bovy_plot.bovy_text(progAngle+0.05,22.50,r'$\mathrm{current\ progenitor\ position}$',size=16.)
    bovy_plot.bovy_plot([progAngle+0.05,progAngle],[22.50,sdf._progenitor_Omega_along_dOmega*bovy_conversion.freq_in_Gyr(220.,8.)],'k:',overplot=True)
    bovy_plot.bovy_text(-1.2,22.35,r"$\mathrm{At\ the\ progenitor's}\ \theta_{\parallel}, \mathrm{we\ calculate\ an\ auxiliary\ orbit\ through}$"+'\n'+r"$(\mathbf{x}_a,\mathbf{v}_a) = (\mathbf{\Omega}_p+\Delta \mathbf{\Omega}^m,\boldsymbol{\theta}_p)\ \mathrm{using\ a\ linearized}\ (\mathbf{\Omega},\boldsymbol{\theta})\ \mathrm{to}\ (\mathbf{x},\mathbf{v}).$",size=16.)
    yarcs= numpy.linspace(22.30,22.39,101)
    bovy_plot.bovy_plot(sdf._thetasTrack[0]+progAngle-0.1*numpy.sqrt(1.-(yarcs-22.35)**2./0.05**2.),yarcs,'k:',
                        overplot=True)
    bovy_plot.bovy_text(-1.3,22.07,r'$\mathrm{At\ a\ small\ number\ of\ points, we\ calculate}$'+'\n'+r'$\partial(\mathbf{\Omega},\boldsymbol{\theta})/\partial (\mathbf{x},\mathbf{v}), \mathrm{the\ mean\ stream\ track\ in}\ (\mathbf{\Omega},\boldsymbol{\theta})^\dagger,$'+'\n'+r'$\mathrm{and\ estimate\ the\ spread\ around\ the\ track}.$',size=16.)
    bovy_plot.bovy_plot([-0.9,sdf._thetasTrack[1]+progAngle],
                        [22.185,mOs[1]+0.03],
                        'k:',overplot=True)
    bovy_plot.bovy_plot([-0.9,progAngle+sdf._thetasTrack[1]],
                        [22.185,mOs[1]],
                        'k:',overplot=True)
    bovy_plot.bovy_text(-0.18,22.265,r'$\mathrm{stream\ track\ +\ spread}$',
                         size=16.,
                        rotation=-20.)
    bovy_plot.bovy_end_print(plotfilename1)
    #Now plot Z,X
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    pyplot.figure()
    sdf.plotTrack(d1='z',d2='x',interp=True,
                  color='k',spread=2,overplot=True,lw=1.5,
                  scaleToPhysical=True)
    sdf.plotTrack(d1='z',d2='x',interp=False,marker='o',ms=8.,color='k',
                  overplot=True,ls='none',
                  scaleToPhysical=True)
    sdf.plotProgenitor(d1='z',d2='x',color='k',
                       overplot=True,ls='--',lw=1.5,dashes=(20,10),
                       scaleToPhysical=True)
    pyplot.plot(sdf._progenitor.z(sdf._trackts)*8.,
                sdf._progenitor.x(sdf._trackts)*8.,marker='o',ms=6.,
                ls='none',
                color='k')
    pyplot.xlim(8.,-3.)
    pyplot.ylim(12.,15.5)
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$Z\,(\mathrm{kpc})$',r'$X\,(\mathrm{kpc})$')
    bovy_plot.bovy_text(0.,14.25,r'$\mathrm{auxiliary\ orbit}$',
                        size=16.,rotation=-20.)
    bovy_plot.bovy_text(1.,13.78,r'$\mathrm{stream\ track\ +\ spread}$',
                        size=16.,rotation=-25.)
    bovy_plot.bovy_text(7.5,14.2,r"$\mathrm{At\ these\ points, we\ calculate\ the\ stream\ position\ in}\ (\mathbf{x},\mathbf{v})\ \mathrm{from}$"+
                         '\n'+r"$\mathrm{the\ auxiliary's}\ (\mathbf{x}_a,\mathbf{v}_a) = (\mathbf{\Omega}_a,\boldsymbol{\theta}_a), \mathrm{the\ mean\ offset} (\Delta \mathbf{\Omega},\Delta \boldsymbol{\theta}),$"+'\n'+
                         r"$\mathrm{and}\ \left(\frac{\partial(\mathbf{\Omega},\boldsymbol{\theta})}{\partial (\mathbf{x},\mathbf{v})}\right)^{-1 \, \dagger}.$",
                        size=16.)
    bovy_plot.bovy_plot([sdf._progenitor.z(sdf._trackts[1])*8.,4.5],
                        [sdf._progenitor.x(sdf._trackts[1])*8.,14.8],
                        'k:',overplot=True)
    bovy_plot.bovy_text(5.6,12.4,r"$\mathrm{We\ interpolate\ the\ track\ between\ the}$"+'\n'+r"$\mathrm{calculated\ points\ and\ use\ slerp\ to}$"+'\n'+r"$\mathrm{interpolate\ the\ estimated\ 6D\ spread.}$",
                         size=16.)
    bovy_plot.bovy_plot([3.,sdf._interpolatedObsTrackXY[500,2]*8.],
                        [13.3,sdf._interpolatedObsTrackXY[500,0]*8.],
                        'k:',overplot=True)
    bovy_plot.bovy_end_print(plotfilename2)
    #Finally plot l vs. d
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    pyplot.figure()
    sdf.plotTrack(d1='ll',d2='dist',interp=True,
                  color='k',spread=2,overplot=True,lw=1.5)
    sdf.plotTrack(d1='ll',d2='dist',interp=False,marker='o',ms=8.,color='k',
                  overplot=True,ls='none')
    sdf.plotProgenitor(d1='ll',d2='dist',color='k',dashes=(20,10),
                       overplot=True,ls='--',lw=1.5)
    pyplot.plot(sdf._progenitor.ll(sdf._trackts,
                                        obs=[sdf._R0,0.,sdf._Zsun],ro=sdf._Rnorm),
                sdf._progenitor.dist(sdf._trackts,
                                        obs=[sdf._R0,0.,sdf._Zsun],ro=sdf._Rnorm),
                marker='o',ms=6.,
                ls='none',
                color='k')
    pyplot.xlim(157.,260.)
    pyplot.ylim(7.4,15.5)
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$\mathrm{Galactic\ longitude\, (deg)}$',
                              r'$\mathrm{distance\, (kpc)}$')
    bovy_plot.bovy_text(165.,13.5,r"$\mathrm{Finally, the\ interpolated\ track\ in}\ (\mathbf{x},\mathbf{v})\ \mathrm{is}$"+'\n'+r"$\mathrm{converted\ to\ observable\ quantities\ (here}, l\ \mathrm{and}\ D).$",
                        size=16.)
    bovy_plot.bovy_plot([230.,sdf._interpolatedObsTrackLB[850,0]],
                        [13.25,sdf._interpolatedObsTrackLB[850,2]],
                        'k:',overplot=True)
    bovy_plot.bovy_text(170.,9.4,r"$\mathrm{The\ estimated\ spread\ is\ propagated}$"+'\n'+r"$\mathrm{at\ the\ points\ directly\ from}\ (\mathbf{\Omega},\boldsymbol{\theta})\ \mathrm{to}$"+'\n'+r"$(l,b,D,\ldots)\ \mathrm{and\ interpolated}$"+'\n'+r"$\mathrm{using\ slerp}.$",
                        size=16.)
    bovy_plot.bovy_plot([195.,sdf._ObsTrackLB[1,0]],
                        [9.7,sdf._ObsTrackLB[1,2]],
                        'k:',overplot=True)
    bovy_plot.bovy_end_print(plotfilename3)
    return None
Ejemplo n.º 33
0
def singleBandExample(filename='../data/SDSSJ203817.37+003029.8.fits',band='g',
                      constraints=None,basefilename='SDSSJ203817.37+003029.8',
                      covarType='SF'):
    """
    NAME:
       singleBandExample
    PURPOSE:
       show an example of a power-law structure function or damped-random walk
       GP covariance function fit to an SDSS quasar
    INPUT:
       filename - filename with the data
       band - band to consider
       constraints - if None, use all constraints, if [] use no constraints!
       basefilename - basefilename for plots
       covarType - 'SF' or 'DRW'
    OUTPUT:
       writes several plots
    HISTORY:
       2010-06-20 - Written - Bovy (NYU)
    """
    file= fu.table_fields(filename)
    if band == 'u':
        mjd_g= nu.array(file.mjd_u)/365.25
        g= nu.array(file.u)
        err_g= nu.array(file.err_u)
    elif band == 'g':
        mjd_g= nu.array(file.mjd_g)/365.25
        g= nu.array(file.g)
        err_g= nu.array(file.err_g)
    elif band == 'r':
        mjd_g= nu.array(file.mjd_r)/365.25
        g= nu.array(file.r)
        err_g= nu.array(file.err_r)
    elif band == 'i':
        mjd_g= nu.array(file.mjd_i)/365.25
        g= nu.array(file.i)
        err_g= nu.array(file.err_i)
    elif band == 'z':
        mjd_g= nu.array(file.mjd_z)/365.25
        g= nu.array(file.z)
        err_g= nu.array(file.err_z)

    mask= (mjd_g != 0)*(g < 20.6)*(g > 19.7)#Adjust for non-g
    g= g[mask]
    g-= nu.mean(g)
    err_g= err_g[mask]
    mjd_g= mjd_g[mask]
    mjd_g-= nu.amin(mjd_g)
    meanErr_g= nu.mean(err_g)

    nu.random.seed(4)
    nGP=5
    nx=201
    params_mean= ()
    if covarType == 'SF':
        from powerlawSF import covarFunc
        params= {'gamma': array([ 0.49500723]), 'logA': array([-3.36044037])}
    else:
        from OU_ARD import covarFunc
        params= {'logl': array([-1.37742591]), 'loga2': array([-3.47341754])}
    cf= covarFunc(**params)
    params_covar= (cf)
    ndata= len(g)
    if constraints is None:
        listx= mjd_g
        listy= g
        noise= err_g
        trainSet= trainingSet(listx=listx,listy=listy,noise=noise)
        constraints= trainSet
    else:
        constraints= None

    useconstraints= constraints
    xs= nu.linspace(-0.1,6.5,nx)
    GPsamples= eval_gp(xs,mean,covar,(),params_covar,nGP=nGP,constraints=useconstraints)
    thismean= calc_constrained_mean(xs,mean,params_mean,covar,params_covar,useconstraints)
    thiscovar= calc_constrained_covar(xs,covar,params_covar,useconstraints)
    #If unconstrained, subtract the mean
    if constraints is None:
        for ii in range(nGP):
            GPsamples[ii,:]= GPsamples[ii,:]-nu.mean(GPsamples[ii,:])

    #Calculate loglike
    if not constraints is None:
        (params,packing)= pack_params(cf)
        covarFuncName= inspect.getmodule(cf).__name__
        thisCovarClass= __import__(covarFuncName)
        loglike= marginalLikelihood(params,constraints,packing,
                                    thisCovarClass)
    plot.bovy_print()
    pyplot.plot(xs,GPsamples[0,:],'-',color='0.25')
    if not constraints is None:
        plot.bovy_plot(mjd_g,g,'k.',zorder=5,ms=10,overplot=True)
    title= re.split(r'_',basefilename)[0]
    if covarType == 'SF':
        method= '\mathrm{power-law\ structure\ function}'
    else:
        method= '\mathrm{damped\ random\ walk}'
    plot.bovy_text(r'$\mathrm{'+title+'\ / \ '+method+r'}$',title=True)
    if not constraints is None:
        plot.bovy_text(r'$\log P({\bf x}|\mathrm{parameters}) = %5.2f$' %(-loglike),
                       top_left=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(nGP):
        pyplot.plot(xs,GPsamples[ii,:],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints is None:
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$'+band+r'-\langle '+band+r' \rangle\ [\mathrm{mag}]$')
    pyplot.xlim(-0.1,6.5)
    if constraints is None:
        pyplot.ylim(-.6,.6)
    else:
        pyplot.ylim(-.6,.6)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_full.ps')

    plot.bovy_print()
    pyplot.plot(xs,GPsamples[0,:],'-',color='0.25')
    if not constraints is None:
        plot.bovy_plot(mjd_g,g,'k.',zorder=5,ms=10,overplot=True)
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    #pyplot.fill_between(xs,thismean-sc.sqrt(sc.diagonal(thiscovar)),thismean+sc.sqrt(sc.diagonal(thiscovar)),color='.75')
    for ii in range(1,nGP):
        pyplot.plot(xs,GPsamples[ii,:],'-',color=str(0.25+ii*.5/(nGP-1)))
    #pyplot.plot(xs,thismean,'k-',linewidth=2)
    if not constraints == []:
        pyplot.errorbar(6.15,-0.25,yerr=meanErr_g,color='k')
    pyplot.xlabel(r'$\mathrm{MJD-constant}\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$'+band+'-\langle '+band+'\rangle\ [\mathrm{mag}]$')
    pyplot.xlim(3,6.5)
    plot._add_ticks()
    plot.bovy_end_print(basefilename+'_zoom.ps')


    plot.bovy_print()
    pyplot.figure()
    for ii in range(nGP):
        pyplot.loglog(sc.arange(1.,len(GPsamples[ii,:])/2)*(xs[1]-xs[0]),
                      2.*sc.var(GPsamples[ii,:])-2.*sc.correlate(GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),GPsamples[ii,:]-sc.mean(GPsamples[ii,:]),"same")[1:len(GPsamples[ii,:])/2][::-1]/len(GPsamples[ii,:]),
                      color=str(0.25+ii*.5/(nGP-1)))
    xline= [(xs[1]-xs[0]),xs[len(xs)/2]]
    pyplot.loglog(xline,nu.exp(-3.36044037)*nu.array(xline)**(0.49500723),'k--')
    pyplot.xlabel(r'$\Delta t\ [\mathrm{yr}]$')
    pyplot.ylabel(r'$\mathrm{structure\ function}$')
    #plot.bovy_text(r'$\mathrm{SDSSJ203817.37+003029.8}$',title=True)
    plot.bovy_end_print(basefilename+'_structfunc.ps')
Ejemplo n.º 34
0
def plot_chi2(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Cut inner disk locations
    #data= data[(data['GLON'] > 75.)]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        if options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    if not options.index is None:
        params= params[options.index]
    savefile.close()
    #params[0]= 245./235.
    #params[1]= 8.5/8.
    #Calculate data means etc.
    #Calculate means
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    sigerr_plate= numpy.zeros(nlocs)
    fidlogl= logl.logl(init=params,data=data,options=options)
    logl_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
        sigerr_plate[ii]= bootstrap_sigerr(data['VHELIO'][indx])
        #Logl
        logl_plate[ii]= -2.*(numpy.sum(fidlogl[indx])-numpy.sum(fidlogl)/len(indx)*numpy.sum(indx))
    #Calculate plate means and variances from the model
    avg_plate_model= numpy.zeros(nlocs)
    sig_plate_model= numpy.zeros(nlocs)
    for ii in range(nlocs):
        #Calculate vlos | los
        indx= (data['LOCATION'] == locations[ii])
        thesedata= data[indx]
        thislogpiso= logpiso[indx,:]
        if options.dwarf:
            thislogpisodwarf= logpisodwarf[indx,:]
        else:
            thislogpisodwarf= None
        vlos= numpy.linspace(-200.,200.,options.nvlos)
        pvlos= numpy.zeros(options.nvlos)
        if not options.multi is None:
            pvlos= multi.parallel_map((lambda x: pvlosplate(params,vlos[x],
                                                            thesedata,
                                                            df,options,
                                                            thislogpiso,
                                                            thislogpisodwarf,iso)),
                                      range(options.nvlos),
                                      numcores=numpy.amin([len(vlos),multiprocessing.cpu_count(),options.multi]))
        else:
            for jj in range(options.nvlos):
                print jj
                pvlos[jj]= pvlosplate(params,vlos[jj],thesedata,df,options,
                                      thislogpiso,thislogpisodwarf,iso)
        pvlos-= logsumexp(pvlos)
        pvlos= numpy.exp(pvlos)
        #Calculate mean and velocity dispersion
        avg_plate_model[ii]= numpy.sum(vlos*pvlos)
        sig_plate_model[ii]= numpy.sqrt(numpy.sum(vlos**2.*pvlos)\
                                            -avg_plate_model[ii]**2.)
    #Plot everything
    left, bottom, width, height= 0.1, 0.4, 0.8, 0.3
    axTop= pyplot.axes([left,bottom,width,height])
    left, bottom, width, height= 0.1, 0.1, 0.8, 0.3
    axChi2= pyplot.axes([left,bottom,width,height])
    #left, bottom, width, height= 0.1, 0.1, 0.8, 0.2
    #axSig= pyplot.axes([left,bottom,width,height])
    fig= pyplot.gcf()
    #Plot the difference
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'ko',overplot=True)
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',linestyle='none',elinestyle='-')
    pyplot.ylabel(r'$\langle v_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle v_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Plot the chi2
    fig.sca(axChi2)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        logl_plate,
                        'ko',overplot=True)
    pyplot.ylabel(r'$\Delta \chi^2$')
    #pyplot.ylim(numpy.amin(logl_plate),numpy.amax(logl_plate))
    pyplot.ylim(-150.,150.)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Ejemplo n.º 35
0
def astro_sampling(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)
        # zs= numpy.arange(0.0005,0.06005,0.005)
    else:
        zs = numpy.arange(0.0005, 0.03005, 0.0005)
        # zs= numpy.arange(0.0005,0.03005,0.005)
    if os.path.exists(args[0]):
        savefile = open(args[0], "rb")
        plotthis = pickle.load(savefile)
        zs = pickle.load(savefile)
        lages = pickle.load(savefile)
        savefile.close()
        dlages = lages[1] - lages[0]
        if options.type == "massperrc":
            savefile = open(args[1], "rb")
            plotthis /= pickle.load(savefile)
            savefile.close()
        if options.type == "mass" and len(args) == 3:
            # Also load mass_coarseage and omega
            savefile = open(args[1], "rb")
            masscoarse = pickle.load(savefile)
            savefile.close()
            savefile = open(args[2], "rb")
            omega = pickle.load(savefile)
            savefile.close()
    else:
        nages = 31
        if options.type == "omega" or options.type == "numfrac" or options.coarseage:
            nages = 16
        lages = numpy.linspace(-1.0, 1.0, nages)
        dlages = lages[1] - lages[0]
        plotthis = numpy.zeros((len(zs), nages))
        multOut = multi.parallel_map(
            lambda x: _calc_one(zs[x], options, nages, lages, dlages), range(len(zs)), numcores=32
        )
        for ii in range(len(zs)):
            plotthis[ii, :] = multOut[ii]
        # Save
        savefile = open(args[0], "wb")
        pickle.dump(plotthis, savefile)
        pickle.dump(zs, savefile)
        pickle.dump(lages, savefile)
        savefile.close()
    # Plot
    # Fist cut out youngest ages, since they are irrelevant
    if _CUTLOWAGE:
        aindx = lages > numpy.log10(0.8)
        lages = lages[aindx]
        plotthis = plotthis[:, aindx]
    if options.type == "mass":
        vmin, vmax = 0.5, 2.3
        vmin2, vmax2 = 0.5, 2.0
        zlabel = r"$\langle M_{\mathrm{RC}} \rangle \,(M_\odot)$"
        # cmap= 'gist_yarg'
        cmap = "jet"
    elif options.type == "omega":
        vmin, vmax = 0.0, 0.03
        vmin2, vmax2 = 0.0, 0.015
        if options.allapogee:
            vmin, vmax = 0.0, 0.035
            zlabel = r"$\mathrm{Mass\ fraction\ in}\ (J-K_s)_0 > 0.5\ \mathrm{giants\ (\%)}$"
        elif options.redapogee:
            vmin, vmax = 0.0, 0.005
            vmin2, vmax2 = 0.0, 0.003
            zlabel = r"$\mathrm{Mass\ fraction\ in}\ (J-K_s)_0 > 0.8\ \mathrm{giants\ (\%)}$"
        else:
            zlabel = r"$\mathrm{Mass\ fraction\ in\ RC\ stars\ (\%)}$"
        # cmap= 'gist_yarg'
        cmap = "jet"
        plotthis *= 100.0
    elif options.type == "numfrac":
        vmin, vmax = 0.0, 0.005
        vmin2, vmax2 = 0.0, 0.004
        zlabel = r"$\mathrm{Number\ fraction\ in\ RC\ stars\ (\%)}$"
        # cmap= 'gist_yarg'
        cmap = "jet"
        plotthis *= 100.0
    elif options.type == "massperrc":
        vmin, vmax = 0.0, 50000.0
        vmin2, vmax2 = 0.0, 25000.0
        zlabel = r"$\mathrm{Stellar\ population\ mass\ per\ RC\ star}\,(M_\odot)$"
        # cmap= 'gist_yarg'
        cmap = "jet"
        if options.redapogee:
            vmin, vmax = 0.0, 100000.0
            vmin2, vmax2 = 0.0, 200000.0
            zlabel = r"$\mathrm{Mass\ fraction\ in}\ (J-K_s)_0 > 0.8\ \mathrm{giants\ (\%)}$"
    print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    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.03005, 0.0005) / 0.019 * 0.0198
        regularplotthis = numpy.zeros((nages, len(regularzs)))
        for jj in range(len(regularzs)):
            # Find z
            thisindx = numpy.argmin(numpy.fabs(regularzs[jj] - zs))
            for ii in range(nages):
                regularplotthis[ii, jj] = plotthis[ii, thisindx]
        zs = regularzs
        plotthis = regularplotthis
    if options.remapz:
        zs = zs[:-1]
        plotthis = plotthis[:-1, :]
        fehs = numpy.linspace(-1.05, isodist.Z2FEH(zs[-1], zsolar=0.017), len(zs))
        fehzs = isodist.FEH2Z(fehs, zsolar=0.017)
        new_plotthis = numpy.empty_like(plotthis)
        for ii in range(plotthis.shape[1]):
            goodz = True - numpy.isnan(plotthis[:, ii])
            tip = interpolate.InterpolatedUnivariateSpline(zs[goodz], plotthis[goodz, ii], k=3)
            new_plotthis[:, ii] = tip(fehzs)
            try:
                new_plotthis[fehs < numpy.nanmax(isodist.Z2FEH(zs[True - goodz], zsolar=0.017)), ii] = numpy.nan
            except ValueError:
                continue
        plotthis = new_plotthis
        xlabel = r"$[\mathrm{Fe/H}]\,(\mathrm{dex})$"
    else:
        xlabel = r"$Z$"
    bovy_plot.bovy_print(fig_height=7.0, fig_width=6.0)
    fig = pyplot.gcf()
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.6
    axBottom = pyplot.axes([left, bottom, width, height])
    fig.sca(axBottom)
    if options.remapz:
        xlimits = [fehs[0], fehs[-1]]
    else:
        xlimits = [zs[0], zs[-1]]
    ylimits = [lages[0] - dlages, lages[-1] + dlages]
    bovy_plot.bovy_dens2d(
        plotthis.T,
        origin="lower",
        cmap=cmap,
        xrange=xlimits,
        yrange=ylimits,
        vmin=vmin,
        vmax=vmax,
        interpolation="nearest",
        colorbar=True,
        shrink=0.9,
        zlabel=zlabel,
        overplot=True,
    )
    extent = xlimits + ylimits
    pyplot.axis(extent)
    bovy_plot._add_axislabels(xlabel, r"$\log_{10}\,\mathrm{Age} / 1\,\mathrm{Gyr}$")
    bovy_plot._add_ticks()
    left, bottom, width, height = 0.1, 0.68, 0.64, 0.2
    axTop = pyplot.axes([left, bottom, width, height])
    fig.sca(axTop)
    # Plot the average over SFH
    lages = numpy.linspace(-1.0, 1.0, 16)
    if _CUTLOWAGE:
        aindx = lages > numpy.log10(0.8)
        lages = lages[aindx]
        if options.type == "mass":
            omega = omega[:, aindx]
            masscoarse = masscoarse[:, aindx]
    mtrend = numpy.zeros(len(zs))
    exppage = 10.0 ** lages * numpy.exp((10.0 ** (lages + 2.0)) / 800.0)  # e.g., Binney (2010)
    exexppage = 10.0 ** lages * numpy.exp((10.0 ** (lages + 2.0)) / 100.0)  # e.g., Binney (2010)
    page = 10.0 ** lages
    if options.type == "massperrc":
        mtrend = 1.0 / (numpy.sum(page * 1.0 / plotthis, axis=1) / numpy.sum(page))
        expmtrend = 1.0 / (numpy.sum(exppage * 1.0 / plotthis, axis=1) / numpy.sum(exppage))
        exexpmtrend = 1.0 / (numpy.sum(exexppage * 1.0 / plotthis, axis=1) / numpy.sum(exexppage))
    elif options.type == "mass" and len(args) == 3:
        if options.remapz:
            omega = omega[:-1, :]
            masscoarse = masscoarse[:-1, :]
        mtrend = numpy.nansum(page * omega, axis=1) / numpy.nansum(page * omega / masscoarse, axis=1)
        expmtrend = numpy.nansum(exppage * omega, axis=1) / numpy.nansum(exppage * omega / masscoarse, axis=1)
        exexpmtrend = numpy.nansum(exexppage * omega, axis=1) / numpy.nansum(exexppage * omega / masscoarse, axis=1)
    else:
        mtrend = numpy.sum(page * plotthis, axis=1) / numpy.sum(page)
        expmtrend = numpy.sum(exppage * plotthis, axis=1) / numpy.sum(exppage)
        exexpmtrend = numpy.sum(exexppage * plotthis, axis=1) / numpy.sum(exexppage)
    if options.remapz:
        zs = fehs
    pyplot.plot(zs, mtrend, "k-")
    pyplot.plot(zs, expmtrend, "k--")
    pyplot.plot(zs, exexpmtrend, "k-.")
    pyplot.ylim(vmin2, vmax2)
    pyplot.xlim(xlimits[0], xlimits[1])
    nullfmt = NullFormatter()  # no labels
    thisax = pyplot.gca()
    thisax.xaxis.set_major_formatter(nullfmt)
    bovy_plot._add_ticks()
    if options.type == "mass":
        pyplot.ylabel(zlabel)
    if options.basti:
        pyplot.annotate(
            r"$\mathrm{BaSTI}$",
            (0.5, 1.08),
            xycoords="axes fraction",
            horizontalalignment="center",
            verticalalignment="top",
            size=16.0,
        )
    elif options.imfmodel == "kroupa2003":
        pyplot.annotate(
            r"$\mathrm{Padova, Kroupa\ (2003)\ IMF}$",
            (0.5, 1.08),
            xycoords="axes fraction",
            horizontalalignment="center",
            verticalalignment="top",
            size=16.0,
        )
    elif "expsfh" in args[0]:
        pyplot.annotate(
            r"$\mathrm{Padova, p(\mathrm{Age}) \propto e^{\mathrm{Age}/(8\,\mathrm{Gyr})}}$",
            (0.5, 1.08),
            xycoords="axes fraction",
            horizontalalignment="center",
            verticalalignment="top",
            size=16.0,
        )
    elif options.parsec:
        pass
        # pyplot.annotate(r'$\mathrm{PARSEC}$',
        #                (0.5,1.08),xycoords='axes fraction',
        #                horizontalalignment='center',
        #                verticalalignment='top',size=16.)
    else:
        pyplot.annotate(
            r"$\mathrm{Padova}$",
            (0.5, 1.08),
            xycoords="axes fraction",
            horizontalalignment="center",
            verticalalignment="top",
            size=16.0,
        )
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Ejemplo n.º 36
0
                  frameon=False)
else:
    bovy_plot.bovy_text(r'$|b|\ <\ 2^\circ,\ |l|\ >\ 35^\circ$'
                        +'\n'+r'$%i,%03i\ \mathrm{stars}$' % (ndata_t,ndata_h)
                        +'\n'+r'$\mathrm{assuming}\ R_0\ =\ 8\ \mathrm{kpc}$'
                        +'\n'+r'$\frac{\mathrm{d} v_{\mathrm{circ}}}{\mathrm{d}R}\ =\ 0\ \mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}$',
                        top_right=True)
    #Legend
    pyplot.legend((line1,line2,line3),(r'$v_{\mathrm{circ}}\ =\ 230\ \mathrm{km\ s}^{-1}$',
                                       r'$v_{\mathrm{circ}}\ =\ 210\ \mathrm{km\ s}^{-1}$',
                                       r'$v_{\mathrm{circ}}\ =\ 250\ \mathrm{km\ s}^{-1}$'),
                  loc='upper right',bbox_to_anchor=(.9,.375),
                  numpoints=2,
                  prop={'size':12},
                  frameon=False)
bovy_plot._add_ticks()
if noSolar:
    bovy_plot.bovy_end_print('apogee_vcirc_l_vhelio_noSolar.'+ext)
    sys.exit(0)
elif justSolar:
    bovy_plot.bovy_end_print('apogee_vcirc_l_vhelio_justSolar.'+ext)
    sys.exit(0)
fig.sca(axBottom)
#Interpolate prediction
interpolPred= interpolate.InterpolatedUnivariateSpline(ls,250.*avg_pred-vsolar)
bovy_plot.bovy_plot(l_plate,avg_plate-interpolPred(l_plate),'ko',overplot=True)
pyplot.errorbar(l_plate,avg_plate-interpolPred(l_plate),
                yerr=siga_plate,marker='o',color='k',linestyle='none',elinestyle='-')
if betas or hrs or dmaxs:
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'k-',overplot=True)
    bovy_plot.bovy_plot(ls,vcbetas*avg_pred2-vcbetas*avg_pred,'k--',overplot=True)
def plot_externalcomparison(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    #data= data[0:20]
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        elif options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Calculate data means etc.
    #Calculate means
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    if not options.index is None:
        params= params[options.index]
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf= None
    fid_logl= numpy.sum(logl.logl(init=params,data=data,options=copy.copy(options))) #Copy options, since logl sets multi=1
    avg_plate_model_fid= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #Plot everything
    bovy_plot.bovy_print(fig_height=6.,fig_width=7.)
    dx= 0.8/5.
    left, bottom, width, height= 0.1, 0.9-dx, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'ko',overplot=True)
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$',top_right=True,size=14.)
    thisax= pyplot.gca()
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Second is powerlaw with beta=0.15
    #fid_slope= params[5-options.nooutliermean+options.dwarf]
    #params[5-options.nooutliermean+options.dwarf]= 0.
    fid_params= copy.copy(params)
    if options.rotcurve.lower() == 'flat':
        params= list(params)
        params.insert(6,0.15)
        params= numpy.array(params)
        fid_rotcurve= options.rotcurve
        options.rotcurve= 'powerlaw'
    elif options.rotcurve.lower() == 'powerlaw':
        params[6]= 0.15
        fid_rotcurve= options.rotcurve
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #params[5-options.nooutliermean+options.dwarf]= fid_slope
    #Undo changes
    params= fid_params
    options.rotcurve= fid_rotcurve
    left, bottom, width, height= 0.1, 0.9-2.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{power\!\!-\!\!law\ rotation\ curve}, \beta = 0.15$',
                        top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Third is powerlaw with beta=-0.15
    #fid_slope= params[5-options.nooutliermean+options.dwarf]
    #params[5-options.nooutliermean+options.dwarf]= 0.
    fid_params= copy.copy(params)
    if options.rotcurve.lower() == 'flat':
        params= list(params)
        params.insert(6,-0.15)
        params= numpy.array(params)
        fid_rotcurve= options.rotcurve
        options.rotcurve= 'powerlaw'
    elif options.rotcurve.lower() == 'powerlaw':
        params[6]= -0.15
        fid_rotcurve= options.rotcurve
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #params[5-options.nooutliermean+options.dwarf]= fid_slope
    #Undo changes
    params= fid_params
    options.rotcurve= fid_rotcurve
    left, bottom, width, height= 0.1, 0.9-3.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{power\!\!-\!\!law\ rotation\ curve}, \beta = -0.15$',
                        top_right=True,size=14.)
    pyplot.ylabel(r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}}$')
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Second is vc=250
    #Load initial parameters from file
    savefile= open(options.vo250file,'rb')
    params= pickle.load(savefile)
    savefile.close()
    options.fixvo= 250.
    options.fixro= 8.4
    vo250_logl= numpy.sum(logl.logl(init=params,data=data,options=copy.copy(options)))
    avg_plate_modelr84= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #Load initial parameters from file
    savefile= open(options.vo250r8file,'rb')
    paramsr8= pickle.load(savefile)
    savefile.close()
    options.fixvo= 250.
    options.fixro= 8.
    vo250r8_logl= numpy.sum(logl.logl(init=paramsr8,data=data,options=copy.copy(options)))
    avg_plate_modelr8= calc_model(paramsr8,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    options.fixro= None
    options.fixvo= None
    left, bottom, width, height= 0.1, 0.9-4.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_modelr84,
                        'x',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_modelr84,
                    yerr=siga_plate,marker='x',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_modelr8,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_modelr8,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    #top_right=True,size=14.)
    bovy_plot.bovy_text(r'$\mathrm{best\!\!-\!\!fit}\ V_c(R_0) = 250\ \mathrm{km\ s}^{-1}, R_0 = %.1f\,\mathrm{kpc}, \Delta \chi^2 = %.0f\ (%.1f\sigma)$' % (8.,2.*(fid_logl-vo250r8_logl),special.erfinv(stats.chi2.cdf(2.*(fid_logl-vo250r8_logl),10.))*numpy.sqrt(2.)),
                        top_right=True,size=13.)
    bovy_plot.bovy_text(r'$\mathrm{best\!\!-\!\!fit}\ V_c(R_0) = 250\ \mathrm{km\ s}^{-1}, R_0 = %.1f\,\mathrm{kpc}, \Delta \chi^2 = %.0f\ (%.1f\sigma)$' % (8.4,2.*(fid_logl-vo250_logl),special.erfinv(stats.chi2.cdf(2.*(fid_logl-vo250_logl),10.))*numpy.sqrt(2.)),
                        bottom_right=True,size=13.)
    bovy_plot.bovy_plot([40.],[-15.],'kx',overplot=True)
    bovy_plot.bovy_plot([40.],[12.],'ko',overplot=True)
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Fourth = vpec=SBD10
    #Load sbd fit
    #Load initial parameters from file
    savefile= open(options.sbdfile,'rb')
    params= pickle.load(savefile)
    savefile.close()
    options.sbdvpec= True
    options.fitvpec= False
    sbd_logl= numpy.nansum(logl.logl(init=params,data=data,options=copy.copy(options)))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-5.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{best\!\!-\!\!fit}\ \vec{V}_\odot = \vec{V}_c(R_0) + \mathrm{SBD10}, \Delta \chi^2 = %.0f$' % (2.*(fid_logl-sbd_logl)),#,special.erfinv(stats.chi2.cdf(2.*(fid_logl-sbd_logl),10.))*numpy.sqrt(2.)),
                        top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    print fid_logl, sbd_logl, 2.*(fid_logl-sbd_logl),special.erfinv(stats.chi2.cdf(2.*(fid_logl-sbd_logl),10.))*numpy.sqrt(2.)
    return None