예제 #1
0
파일: plot_vr.py 프로젝트: jobovy/apogee-rc
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
예제 #2
0
def veldist_1d_rolr(plotfilename,phi=_DEFAULTPHI,R=_DEFAULTR,
                    ngrid=201,saveDir='../bar/1dvar/'):
    """
    NAME:
       veldist_1d_rolr
    PURPOSE:
       make a plot showing the influence of the bar R_OLR
    INPUT:
       plotfilename - filename for figure
       phi - Galactocentric azimuth
       R - Galactocentric radius
       ngrid - number of grid-points to calculate the los velocity distribution
               on
       saveDir - save pickles here
    OUTPUT:
       Figure in plotfilename
    HISTORY:
       2010-09-11 - Written - Bovy (NYU)
    """
    rolrs= [0.85,0.9,0.95]

    vloslinspace= (-.9,.9,ngrid)
    vloss= sc.linspace(*vloslinspace)

    vlosds= []
    basesavefilename= os.path.join(saveDir,'rolr_')
    for rolr in rolrs:
        thissavefilename= basesavefilename+'%.3f.sav' % rolr
        if os.path.exists(thissavefilename):
            print "Restoring los-velocity distribution at R_OLR %.2f" % rolr
            savefile= open(thissavefilename,'r')
            vlosd= pickle.load(savefile)
            savefile.close()
        else:
            print "Calculating los-velocity distribution at R_OLR %.2f" % rolr
            potparams= (rolr,0.01,25.*_degtorad,.8,None)
            vlosd= predictVlos(vloslinspace,
                               l=phi,
                               d=R,
                               distCoord='GCGC',
                               pot='bar',beta=0.,
                               potparams=potparams)
            vlosd= vlosd/(sc.nansum(vlosd)*(vloss[1]-vloss[0]))
            savefile= open(thissavefilename,'w')
            pickle.dump(vlosd,savefile)
            savefile.close()
        vlosds.append(vlosd)
    #Plot
    plot.bovy_print()
    plot.bovy_plot(vloss,vlosds[1],'k-',zorder=3,
                   xrange=[vloslinspace[0],vloslinspace[1]],
                   yrange=[0.,sc.amax(sc.array(vlosds).flatten())*1.1],
                   xlabel=r'$v_{\mathrm{los}} / v_0$')
    plot.bovy_plot(vloss,vlosds[0],ls='-',color='0.75',
                   overplot=True,zorder=2,lw=2.)
    plot.bovy_plot(vloss,vlosds[2],ls='-',color='0.5',
                   overplot=True,zorder=2,lw=1.5)
    plot.bovy_text(r'$\mathrm{bar}\ R_{\mathrm{OLR}}$',title=True)
    plot.bovy_text(0.36,.75,r'$R_{\mathrm{OLR}} = 0.95\ R_0$'+'\n'+r'$R_{\mathrm{OLR}} = 0.90\ R_0$'+ '\n'+r'$R_{\mathrm{OLR}} = 0.85\ R_0$')
    plot.bovy_end_print(plotfilename)
예제 #3
0
def veldist_1d_vrconvolve(plotfilename,phi=_DEFAULTPHI,R=_DEFAULTR,
                        ngrid=201,saveDir='../bar/1dvar/'):
    """
    NAME:
       veldist_1d_vrconvolve
    PURPOSE:
       make a plot showing the influence of the los velocity uncertainties
    INPUT:
       plotfilename - filename for figure
       phi - Galactocentric azimuth
       R - Galactocentric radius
       ngrid - number of grid-points to calculate the los velocity distribution
               on
       saveDir - save pickles here
    OUTPUT:
       Figure in plotfilename
    HISTORY:
       2010-09-11 - Written - Bovy (NYU)
    """
    convolves= [0.02,0.04,0.08]#0, 5, 10, 20 km/s

    vloslinspace= (-.9,.9,ngrid)
    vloss= sc.linspace(*vloslinspace)

    vlosds= []
    thissavefilename= os.path.join(saveDir,'convolve_')+'%.1f.sav' % 0.
    print "Restoring los-velocity distribution at distance uncertainties %.1f" % 0.
    savefile= open(thissavefilename,'r')
    vlosd= pickle.load(savefile)
    savefile.close()
    vlosds.append(vlosd)
    basesavefilename= os.path.join(saveDir,'vrconvolve_')
    for distsig in convolves:
        thissavefilename= os.path.join(saveDir,'convolve_')+'%.1f.sav' % 0.
        print "Restoring los-velocity distribution at distance uncertainties %.1f" % 0.
        savefile= open(thissavefilename,'r')
        vlosd= pickle.load(savefile)
        savefile.close()
        #Create Gaussian
        gauss= sc.exp(-0.5*vloss**2./distsig**2.)
        #gauss= gauss/sc.sum(gauss)/(vloss[1]-vloss[0])
        vlosd= signal.convolve(vlosd,gauss,mode='same')
        vlosd= vlosd/sc.sum(vlosd)/(vloss[1]-vloss[0])
        vlosds.append(vlosd)
    #Plot
    plot.bovy_print()
    plot.bovy_plot(vloss,vlosds[0],'k-',zorder=3,
                   xrange=[vloslinspace[0],vloslinspace[1]],
                   yrange=[0.,sc.nanmax(sc.array(vlosds).flatten())*1.1],
                   xlabel=r'$v_{\mathrm{los}} / v_0$')
    plot.bovy_plot(vloss,vlosds[1],ls='-',color='0.75',
                   overplot=True,zorder=2,lw=2.)
    plot.bovy_plot(vloss,vlosds[2],ls='-',color='0.6',
                   overplot=True,zorder=2,lw=2.)
    plot.bovy_plot(vloss,vlosds[3],ls='-',color='0.45',
                   overplot=True,zorder=2,lw=2.)
    kms= r' \mathrm{km\ s}^{-1}$'
    plot.bovy_text(r'$\mathrm{line-of-sight\ velocity\ uncertainties}$',title=True)
    plot.bovy_text(0.4,.65,r'$\sigma_v = 0\ '+kms+'\n'+r'$\sigma_v = 5\ '+kms+'\n'+r'$\sigma_v = 10\ '+kms+'\n'+r'$\sigma_v = 20\ '+kms)
    plot.bovy_end_print(plotfilename)
예제 #4
0
def plotJuricIvezicDiff(dir):
    #Plot difference for a few metallicities
    fehs= [0.,-0.1,-0.2,-0.3,-0.5,-1.,-1.5]
    colors= ['b','c','g','y','orange','m','r']
    #Set up plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([-100.,-100.],[-100.,-100],'k,',
                        xrange=[0.47,0.58],
                        yrange=[-1.,1.],
                        xlabel=r'$g-r\ [\mathrm{mag}]$',
                        ylabel=r'$\mathrm{DM}_{\mathrm{Juri\acute{c}}}-\mathrm{DM}_{\mathrm{Ivezi\acute{c}}}\ [\mathrm{mag}]$')
    xlegend, ylegend, dy= 0.55, 0.8,-0.12
    grs= numpy.linspace(0.48,0.55,1001)
    for ii in range(len(fehs)):
        ybright= -1.*(_mr_ri_bright(_ri_gr(grs))-_mr_gi(_gi_gr(grs),fehs[ii]))
        yfaint= -1.*(_mr_ri_faint(_ri_gr(grs))-_mr_gi(_gi_gr(grs),fehs[ii]))
        bovy_plot.bovy_plot(grs,
                            ybright,
                            '-',color=colors[ii],
                            overplot=True)
        bovy_plot.bovy_plot(grs,
                            yfaint,
                            '--',color=colors[ii],
                            overplot=True)
        bovy_plot.bovy_text(xlegend,ylegend+ii*dy,
                            r'$[\mathrm{Fe/H]=%+4.1f}$' % fehs[ii],
                            color=colors[ii])
    bovy_plot.bovy_end_print(os.path.join(dir,'dm_juric_ivezic.'+_EXT))
예제 #5
0
def plotprops(options,args):
    #Go through all of the bins
    if options.sample.lower() == 'g':
        npops= 62
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        npops= 30
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    ndatas= pickle.load(savefile)
    savefile.close()
    for ii in range(npops):
        bovy_plot.bovy_print()
        bovy_plot.bovy_text(r'$[\mathrm{Fe/H}] = %.2f$' % (fehs[ii])
                            +'\n'
                            r'$[\alpha/\mathrm{Fe}] = %.3f$' % (afes[ii])
                            +'\n'
                            r'$N_{\mathrm{data}} = %i$' % (ndatas[ii])
                            +'\n'
                            r'$\ln h_R / 8\,\mathrm{kpc} = %.1f$' % (numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii])/8.)) 
                            +'\n'
                            +r'$\ln \sigma_R / 220\,\mathrm{km\,s}^{-1} = %.1f$' % (numpy.log(monoAbundanceMW.sigmar(fehs[ii],afes[ii])/220.))
                            +'\n'
                            +r'$\ln \sigma_Z / 220\,\mathrm{km\,s}^{-1} = %.1f$' % (numpy.log(monoAbundanceMW.sigmaz(fehs[ii],afes[ii])/220.)),
                            top_left=True,size=16.)
        #Plotname
        spl= options.outfilename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        bovy_plot.bovy_end_print(newname)
def plotKz(pot,plotfilename,surfrs,kzs,kzerrs):
    krs= numpy.linspace(4./_REFR0,10./_REFR0,1001)
    modelkz= numpy.array([-potential.evaluatezforces(kr,1.1/_REFR0,pot)\
                               *bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0) for kr in krs])
    bovy_plot.bovy_print(fig_height=3.5)
    bovy_plot.bovy_plot(krs*_REFR0,modelkz,'-',color='0.6',lw=2.,
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$F_{Z}(R,|Z| = 1.1\,\mathrm{kpc})\ (2\pi G\,M_\odot\,\mathrm{pc}^{-2})$',
                        semilogy=True,
                        yrange=[10.,1000.],
                        xrange=[4.,10.],
                        zorder=0)
    pyplot.errorbar(surfrs,
                    kzs,
                    yerr=kzerrs,
                    marker='o',
                    elinewidth=1.,capsize=3,zorder=1,
                    color='k',linestyle='none')  
    pyplot.errorbar([_REFR0],[69.],yerr=[6.],marker='d',ms=10.,
                    elinewidth=1.,capsize=3,zorder=10,
                    color='0.4',linestyle='none')
    bovy_plot.bovy_end_print(plotfilename)
    #Do an exponential fit to the model Kz and return the scale length
    indx= krs < 9./_REFR0
    p= numpy.polyfit(krs[indx],numpy.log(modelkz[indx]),1)
    return -1./p[0]
예제 #7
0
def plot_rcdistancecomparison(plotfilename):
    # Get the sample
    rcdata = define_rcsample.get_rcsample()
    # Now plot the differece
    bovy_plot.bovy_print()
    levels = special.erf(numpy.arange(1, 3) / numpy.sqrt(2.))
    bovy_plot.scatterplot(
        rcdata['RC_DIST'],
        (rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
        conditional=True,
        levels=levels,
        linestyle='none',
        color='k',
        marker=',',
        xrange=[0., 7.49],
        yrange=[-0.075, 0.075],
        xlabel=r'$M_{K_s}\!-\!\mathrm{based\ distance\,(kpc)}$',
        ylabel=
        r'$\mathrm{Fractional\ difference\ of}\ M_H\ \mathrm{vs.}\ M_{K_s}$',
        onedhistx=True,
        bins=31)
    bovy_plot.bovy_plot([0., 10.], [0., 0.],
                        '--',
                        lw=2.,
                        color='0.75',
                        overplot=True)
    # Plot lowess
    lowess = sm.nonparametric.lowess
    z = lowess((rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
               rcdata['RC_DIST'],
               frac=.3)
    bovy_plot.bovy_plot(z[:, 0], z[:, 1], 'w--', lw=2., overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #8
0
def plot_dustwapogee(plotname):
    # Load the dust map
    green15map= dust.load_green15(5.,nest=True,nside_out=_NSIDE)
    green15map[green15map == healpy.UNSEEN]= -1.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,min=0.,max=.8,
                             format=r'$%g$',
                             title='',
                             cmap='gist_yarg',
                             unit='$A_H\,(\mathrm{mag})$')
    # Load the RC data to get the fields
    data= define_rcsample.get_rcsample()
    loc_ids= numpy.array(list(set(data['LOCATION_ID'])))
    # Load the selection function, just to get the field centers
    apo= apogee.select.apogeeSelect(_justprocessobslog=True)
    theta= numpy.empty(len(loc_ids))
    phi= numpy.empty(len(loc_ids))
    for ii,loc_id in enumerate(loc_ids):
        tl, tb= apo.glonGlat(loc_id)
        theta[ii]= (90.-tb)/180.*numpy.pi
        phi[ii]= tl/180.*numpy.pi
    hib= numpy.fabs((numpy.pi/2.-theta)) > (8./180.*numpy.pi)
    healpy.visufunc.projplot(theta[hib],phi[hib],'o',ms=5.,mfc='none',mew=0.8,
                             mec='k')
    lowb= True-hib
    healpy.visufunc.projplot(theta[lowb],phi[lowb],'o',ms=5.,mfc='none',
                             mec='w',mew=0.8)
    bovy_plot.bovy_end_print(plotname)
예제 #9
0
def plotMetallicityRZ(options,args):
    if options.png: ext= 'png'
    else: ext= 'ps'
    #Load data
    XYZ,vxvyvz,cov_vxvyvz,data= readData(metal=options.metal,
                                         sample=options.sample)
    R= ((8.-XYZ[:,0])**2.+XYZ[:,1]**2.)**0.5
    XYZ[:,2]+= _ZSUN
    #Set up ranges
    #Set up ranges
    if options.sample.lower() == 'g':
        xrange=[0.46,0.57]
        rmin, rmax= 14.5, 20.2
        grmin, grmax= 0.48, 0.55
        colorrange=[0.48,0.55]
    elif options.sample.lower() == 'k':
        xrange=[0.51,0.79]
        rmin, rmax= 14.5, 19.
        grmin, grmax= 0.55,0.75
        colorrange=[0.55,0.75]
    if options.metal.lower() == 'rich':
        yrange=[-0.55,0.5]
        fehrange= _APOORFEHRANGE
    elif options.metal.lower() == 'poor':
        yrange=[-1.6,0.3]
        fehrange= _ARICHFEHRANGE
    Zrange= [0.25,3.25]
    Rrange= [5.,12.]
    if options.plottype.lower() == 'z':
        _NBINS= 7
        Zranges= [[Zrange[0]+ii*(Zrange[1]-Zrange[0])/(_NBINS-1),
                   Zrange[0]+(ii+1)*(Zrange[1]-Zrange[0])/(_NBINS-1)] \
                      for ii in range(_NBINS-1)]
        Zranges.append([Zranges[-1][1],4.])
        Rranges= [Rrange for ii in range(_NBINS)]
    elif options.plottype.lower() == 'r':
        _NBINS= 7
        Zranges= [Zrange for ii in range(_NBINS)]
        Rranges= [[5.,7.]]
        Rranges.extend([[Rrange[0]+ii*(Rrange[1]-Rrange[0])/_NBINS,
                         Rrange[0]+(ii+1)*(Rrange[1]-Rrange[0])/_NBINS] \
                            for ii in range(1,_NBINS)])
    #First plot all data
    bovy_plot.bovy_print()
    _plotMRZ_single(XYZ,R,data,options,args,all=True,overplot=False,
                    xrange=xrange,yrange=yrange,colorrange=colorrange,
                    fehrange=fehrange,
                    Zrange=Zrange,Rrange=Rrange)
    _overplot_model(data,xrange=xrange,yrange=yrange,fehrange=fehrange,
                    colorrange=colorrange)
    bovy_plot.bovy_end_print(os.path.join(args[0],'FeH_'+options.plottype+'_'+options.sample+'_'+options.metal+'.'+ext))
    #Then plot them in ranges
    for ii in range(_NBINS):
        _plotMRZ_single(XYZ,R,data,options,args,all=False,overplot=False,
                        xrange=xrange,Zrange=Zranges[ii],Rrange=Rranges[ii],
                        yrange=yrange,colorrange=colorrange,fehrange=fehrange)
        _overplot_model(data,xrange=xrange,yrange=yrange,fehrange=fehrange,
                        colorrange=colorrange)
        bovy_plot.bovy_end_print(os.path.join(args[0],'FeH_'+options.plottype+'_'+options.sample+'_'+options.metal+'_%i.' % ii + ext))
    return None
예제 #10
0
def triangleMAPs(savefilename,basename):
    with open(savefilename,'rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
        bf_g15= numpy.array(pickle.load(savefile))
        samples_g15= numpy.array(pickle.load(savefile))
        bf_zero= numpy.array(pickle.load(savefile))
        samples_zero= numpy.array(pickle.load(savefile))
    labels= []
    for jj in range(samples.shape[2]):
        labels.append(r"$\mathrm{param}\ %i$" % jj)
    maps= define_rcsample.MAPs()
    for ii, map in enumerate(maps.map()):
        if ii >= len(bf): break
        tfeh= numpy.nanmedian(map['FE_H'])
        tafe= numpy.nanmedian(map[define_rcsample._AFETAG])
        for tbf,tsamples,ext in zip([bf,bf_g15,bf_zero],
                                    [samples,samples_g15,samples_zero],
                                    ['fid','g15','zero']):
            try:
                triangle.corner(tsamples[ii,].T,quantiles=[0.16, 0.5, 0.84],
                                labels=labels,
                                show_titles=True,title_args={"fontsize": 12},
                                bins=21)
            except ValueError: pass
            else:
                bovy_plot.bovy_text(r'$[\mathrm{{Fe/H}}] = {feh:.1f},$'\
                                        .format(feh=tfeh)+'\n'
                                    +r'$[\alpha/\mathrm{{Fe}}] = {afe:.2f}$'\
                                        .format(afe=tafe),
                                    top_left=True,size=16.)
                bovy_plot.bovy_end_print(basename+"_%i_%s.png" % (ii,ext))
    return None
예제 #11
0
def plotAnIvezicDiff(dir):
    #Load An isochrones
    a= isodist.AnIsochrone()
    #Plot difference for a few metallicities
    fehs= [0.,-0.1,-0.2,-0.3,-0.5,-1.,-1.5]
    colors= ['b','c','g','y','orange','m','r']
    #Set up plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([-100.,-100.],[-100.,-100],'k,',
                        #xrange=[0.47,0.58],
                        xrange=[0.53,0.78],
                        yrange=[-0.25,.25],
                        xlabel=r'$g-r\ [\mathrm{mag}]$',
                        ylabel=r'$\mathrm{DM}_{\mathrm{An}}-\mathrm{DM}_{\mathrm{Ivezi\acute{c}}}\ [\mathrm{mag}]$')
    xlegend, ylegend, dy= 0.545, 0.2,-0.03
    for ii in range(len(fehs)):
        iso= a(numpy.log10(10.),feh=fehs[ii])
        #Get G dwarfs
        indx= (iso['g']-iso['r'] <= 0.75)*(iso['g']-iso['r'] >= 0.55)\
            *(iso['logg'] > 4.1)
        y= -1.*(iso['r'][indx]-_mr_gi(_gi_gr(iso['g'][indx]
                                             -iso['r'][indx]),fehs[ii]))
        bovy_plot.bovy_plot(iso['g'][indx]-iso['r'][indx],
                            y,
                            '-',color=colors[ii],
                            overplot=True)
        bovy_plot.bovy_text(xlegend,ylegend+ii*dy,
                            r'$[\mathrm{Fe/H]=%+4.1f}$' % fehs[ii],
                            color=colors[ii])
    bovy_plot.bovy_end_print(os.path.join(dir,'dm_an_ivezic.'+_EXT))
예제 #12
0
def plotIllustrative(plotfilename):
    #Make an illustrative plot of the effect of uncertainties on sigmaz
    bovy_plot.bovy_print()
    feh, afe= -0.15,0.125
    nzs= 1001
    zs= numpy.linspace(500.,2000.,nzs)
    sigs= numpy.zeros(nzs)+sigmaz(feh,afe)
    bovy_plot.bovy_plot(zs,sigs,'k-',
                        xlabel=r'$|Z|\ [\mathrm{pc}]$',
                        ylabel=r'$\sigma_z(Z)\ [\mathrm{km\ s}^{-1}]$',
                        xrange=[0.,2700.],
                        yrange=[0.,60.])
    dfeh, dafe= 0.2, 0.1
    sigs= sigmazObs(zs,feh,afe,dfeh,dafe)
    bovy_plot.bovy_plot(zs,sigs,'k--',overplot=True)
    dfeh, dafe= .4,.2
    sigs= sigmazObs(zs,feh,afe,dfeh,dafe)
    bovy_plot.bovy_plot(zs,sigs,'k-.',overplot=True)
    feh, afe= -0.65,0.375
    nzs= 1001
    zs= numpy.linspace(500.,2000.,nzs)
    sigs= numpy.zeros(nzs)+sigmaz(feh,afe)
    bovy_plot.bovy_plot(zs,sigs,'k-',overplot=True)
    dfeh, dafe= 0.2, 0.1
    sigs= sigmazObs(zs,feh,afe,dfeh,dafe)
    bovy_plot.bovy_plot(zs,sigs,'k--',overplot=True)
    dfeh, dafe= 0.4,0.2
    sigs= sigmazObs(zs,feh,afe,dfeh,dafe)
    bovy_plot.bovy_plot(zs,sigs,'k-.',overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
예제 #13
0
def plot_maphz(plotname):
    # Load the two fit
    with open('../mapfits/tribrokentwoexp.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
    maps= define_rcsample.MAPs()
    plotthisz1= numpy.zeros(len(bf))+numpy.nan
    plotthisz1e= numpy.zeros(len(bf))+numpy.nan
    plotthisz2= numpy.zeros(len(bf))+numpy.nan
    plotthisz2e= numpy.zeros(len(bf))+numpy.nan
    for ii, map in enumerate(maps.map()):
        hzindx= (True-numpy.isnan(samples[ii,4]))\
            *(True-numpy.isnan(samples[ii,5]))\
            *(densprofiles.ilogit(samples[ii,4]) > 0.15)
        tmed= numpy.median(1./samples[ii,1,hzindx])
        terr= numpy.std(1./samples[ii,1,hzindx])
        plotthisz1[ii]= tmed
        plotthisz1e[ii]= terr
        tmed= numpy.median(1./samples[ii,5,hzindx])
        terr= numpy.std(1./samples[ii,5,hzindx])
        plotthisz2[ii]= tmed
        plotthisz2e[ii]= terr
    plotthisz1[plotthisz1e/plotthisz1 > 0.5]= numpy.nan
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(plotthisz2*1000.,plotthisz1*1000.,'ko',
                        xrange=[0.,1200.],yrange=[0.,1200.],
                        xlabel=r'$2^\mathrm{nd}\ \mathrm{scale\ height\,(pc)}$',
                        ylabel=r'$1^\mathrm{st}\ \mathrm{scale\ height\,(pc)}$',zorder=2)
    bovy_plot.bovy_plot([0,1200],[0,1200],'k--',overplot=True,lw=2.)
    pyplot.errorbar(plotthisz2*1000.,plotthisz1*1000.,
                    yerr=plotthisz1e*1000.,
                    marker='o',color='k',ls='none',zorder=1)
    bovy_plot.bovy_end_print(plotname)
    return None
def checkAbundanceScatterClusters():
    # First read the cluster data
    cldata= read_clusterdata.read_caldata()
    # Read the allStar data to match
    # For each of the calibration open clusters, calculate the offset from the 
    # mean in our FEHTAG and AFETAG
    clusters= ['M71','N2158','N2420','N188','M67','N7789','N6819',
               'N6791']
    fehoffset= []
    afeoffset= []
    for cluster in clusters:
        tdata= cldata[cldata['CLUSTER'] == cluster.upper()]
        tdata= tdata[(tdata['TEFF'] < _TEFFMAX)\
                         *(tdata['TEFF'] > _TEFFMIN)\
                         *(tdata['LOGG'] < 3.5)]
        # Compute the average feh and afe and save the offsets
        medianfeh= numpy.median(tdata['FE_H'])
        medianafe= numpy.median(tdata[define_rcsample._AFETAG])
        fehoffset.extend(tdata['FE_H']-medianfeh)
        afeoffset.extend(tdata[define_rcsample._AFETAG]-medianafe)
        if cluster == 'M67': print medianfeh, medianafe, len(tdata)
    fehoffset= numpy.array(fehoffset)
    afeoffset= numpy.array(afeoffset)
    print 'FE_H scatter %g' % (numpy.nanstd(fehoffset[numpy.fabs(fehoffset) < 0.3]))
    print 'A_FE scatter %g' % (numpy.nanstd(afeoffset[numpy.fabs(afeoffset) < 0.3]))
    gindx= (numpy.fabs(fehoffset) < 0.3)*(numpy.fabs(afeoffset) < 0.3)
    print 'FE_H/A_FE correlation %g' % (numpy.mean(afeoffset[gindx]*fehoffset[gindx])/numpy.nanstd(fehoffset[numpy.fabs(fehoffset) < 0.3])/numpy.nanstd(afeoffset[numpy.fabs(afeoffset) < 0.3]))
    print 'FE_H robust scatter %g' % (1.4826*numpy.median(numpy.fabs(fehoffset)))
    print 'A_FE robust scatter %g' % (1.4826*numpy.median(numpy.fabs(afeoffset)))
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(fehoffset,range=[-0.3,0.3],bins=31,histtype='step')
    bovy_plot.bovy_hist(afeoffset,range=[-0.3,0.3],bins=31,histtype='step',
                        overplot=True)
    bovy_plot.bovy_end_print('test.png')
    return None
예제 #15
0
def plot_data_h_jk(location=None,
                   plotfilename=os.path.join(OUTDIR, 'data_h_jk.' + OUTEXT)):
    data = readVclosData()
    if not location is None:
        if location == 0:
            locs = set(data['LOCATION'])
            for l in locs:
                plot_data_h_jk(location=l,
                               plotfilename=os.path.join(
                                   OUTDIR, 'data_h_jk_%i.' % l + OUTEXT))
            return None
        data = data[(data['LOCATION'] == location)]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['J0MAG'] - data['K0MAG'],
                        data['H0MAG'],
                        'k,',
                        xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                        ylabel=r'$H_0\ [\mathrm{mag}]$',
                        xrange=[0.4, 1.4],
                        yrange=[5., 14.],
                        onedhists=True,
                        bins=31)
    #Overplot distance if wanted
    if _PLOTDISTANCE:
        iso = isomodel(imfmodel='lognormalChabrier2001', Z=0.019, expsfh=True)
        nds = 101
        ds = numpy.zeros((nds, nds))
        jks = numpy.linspace(0.5, 1.2, nds)
        hs = numpy.linspace(14., 5., nds)
        for ii in range(nds):
            for jj in range(nds):
                ds[ii, jj] = iso.peak(jks[ii], hs[jj])
        #Now contour this
        levels = [1., 3., 10., 30.]
        colors = '0.6'  #['0.5','0.5','0.5','k','k','k']
        CS = pyplot.contour(jks,
                            hs,
                            ds.T,
                            levels=levels,
                            colors=colors,
                            zorder=10.,
                            linewidths=2.)
        ys = [5.3, 6.7, 9.22, 11.7]
        for ii in range(len(levels)):
            bovy_plot.bovy_text(1.21,
                                ys[ii],
                                r'$%.0f\ \mathrm{kpc}$' % levels[ii],
                                fontsize=14.,
                                color='0.3')
        if False:
            pyplot.clabel(CS,
                          levels,
                          inline=1,
                          fmt='%.0f',
                          fontsize=14,
                          colors=colors,
                          zorder=10.)
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #16
0
def plotDMMetallicityColor(options,args):
    """Make a density plot of DM vs FeH and g-r"""
    if options.png: ext= 'png'
    else: ext= 'ps'
    if options.metal.lower() == 'rich':
        yrange=[-0.55,0.5]
        fehrange= _APOORFEHRANGE
    elif options.metal.lower() == 'poor':
        yrange=[-1.6,0.3]
        fehrange= _ARICHFEHRANGE
    xrange=[0.46,0.57]
    grmin, grmax= 0.48, 0.55
    colorrange=[0.48,0.55]
    #Set up arrays
    nfehs, ngrs= 201,201
    grs= numpy.linspace(xrange[0],xrange[1],nfehs)
    fehs= numpy.linspace(yrange[0],yrange[1],ngrs)
    plotthis= numpy.zeros((ngrs,nfehs))
    for ii in range(ngrs):
        for jj in range(nfehs):
            if grs[ii] < colorrange[0] \
                    or grs[ii] > colorrange[1] \
                    or fehs[jj] < fehrange[0] \
                    or fehs[jj] > fehrange[1]:
                plotthis[ii,jj]= numpy.nan
                continue
            plotthis[ii,jj]= segueSelect._mr_gi(segueSelect._gi_gr(grs[ii]),fehs[jj])
    if options.sample.lower() == 'g':
        if options.metal.lower() == 'rich':
            levels= [4.5,4.75,5.,5.25,5.5]
        else:
            levels= [5.25,5.5,5.75,6.,6.25]
    cntrlabelcolors= ['w' for ii in range(3)]
    cntrlabelcolors.extend(['k' for ii in range(2)])
    #nlevels= 6
    #levelsstart= int(20.*numpy.nanmin(plotthis))/20.
    #levelsd= int(20.*(numpy.nanmax(plotthis)-numpy.nanmin(plotthis)))/20.
    #levels= [levelsstart+ii/float(nlevels)*levelsd for ii in range(nlevels)]
    #Plot it
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',
                          xlabel=r'$g-r\ [\mathrm{mag}]$',
                          ylabel=r'$[\mathrm{Fe/H}]$',
                          zlabel=r'$M_r\ [\mathrm{mag}]$',
                          colorbar=True,
                          cmap=pyplot.cm.gist_gray,
                          contours=True,
                          levels=levels,
                          cntrcolors=cntrlabelcolors,
                          cntrlabel=True,
                          cntrlabelcolors=cntrlabelcolors,
                          cntrinline=True,
                          interpolation='nearest',
                          extent=[xrange[0],xrange[1],
                                  yrange[0],yrange[1]],
                          aspect=(xrange[1]-xrange[0])/\
                              (yrange[1]-yrange[0]),
                          shrink=.78)
    bovy_plot.bovy_end_print(os.path.join(args[0],'dm_FeH_gr_'+options.sample+'_'+options.metal+'.'+ext))
예제 #17
0
def plot_apogee_jkz(plotfilename,sample):
    if sample == 'disk':
        data= readData()
    elif sample == 'halo':
        data= readData(halo=True)
    elif sample == 'bulge':
        data= readData(bulge=True)
    ntotal= len(data)
    #logg cut
    data= data[(data['LOGG_AVG'] < 2.8)*(data['LOGG_AVG'] > 1.8)]
    npass= len(data)
    #Deredden
    aj= data['AK_WISE']*2.5
    ah= data['AK_WISE']*1.55
    j0= data['JMAG']-aj
    h0= data['HMAG']-ah
    k0= data['KMAG']-data['AK_WISE']
    #calculate Zs
    zsolar= 0.019
    z= isodist.FEH2Z(data['METALS_AVG'])/zsolar
    #Plot
    bovy_plot.bovy_print()
    if sample == 'bulge':
        bovy_plot.bovy_plot(j0-k0,z,'ko',
                            xrange=[0.5,0.75],
                            yrange=[0.,0.03/zsolar],
                            xlabel=r'$(J-K_s)_0$',
                            ylabel=r'$Z/Z_\odot$',ms=5.)
    else:
        bovy_plot.scatterplot(j0-k0,z,'k,',
                              xrange=[0.5,0.75],
                              yrange=[0.,0.03/zsolar],
                              xlabel=r'$(J-K_s)_0$',
                              ylabel=r'$Z/Z_\odot$',
                              bins=21)
    #Overplot cuts
    jks= numpy.linspace(0.5,0.75,1001)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks)/zsolar,
                        'k--',lw=2.,overplot=True)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks,upper=True)/zsolar,
                        'k--',lw=2.,overplot=True)
    #Data between the cuts
    indx= (j0-k0 < 0.75)*(j0-k0 > 0.5)\
                   *(z <= rcmodel.jkzcut(j0-k0,upper=True)/zsolar)\
                   *(z >= rcmodel.jkzcut(j0-k0)/zsolar)
#    j0= j0[indx]
#    h0= h0[indx]
#    k0= k0[indx]
#    z= z[indx]
#    bovy_plot.bovy_plot(j0-k0,z,'w.',
#                        overplot=True,
#                        mec='w',
#                        ms=.5)
    bovy_plot.bovy_text(r'$\mathrm{APOGEE\ ' + sample + '\ sample}$',
                        title=True)
    bovy_plot.bovy_text(r'$%i/%i/%i$' % (numpy.sum(indx),npass,ntotal),
                        bottom_right=True,size=14.)
    bovy_plot.bovy_end_print(plotfilename)
    return None                        
예제 #18
0
def plot_age(plotfilename,massfile,omegafile):
    if os.path.exists(massfile):
        savefile= open(massfile,'rb')
        mass= pickle.load(savefile)
        zs= pickle.load(savefile)
        lages= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("file %s has to exist ..." % massfile)
    if os.path.exists(omegafile):
        savefile= open(omegafile,'rb')
        omega= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("file %s has to exist ..." % omegafile)
    agezdist= omega/mass
    pz= numpy.exp(numpy.array([localzdist(z,zsolar=0.017) for z in zs]))
    pz/= numpy.sum(pz)
    page= 1.
    #Tile
    pz= numpy.tile(pz,(len(lages),1)).T
    #Build age pdfs
    postage= page*numpy.nansum(pz*agezdist,axis=0)/numpy.nansum(pz,axis=0)/10.**lages
    postage= postage[lages > numpy.log10(0.8)]
    postage/= numpy.nanmax(postage)
    #Interpolate
    lages= lages[lages > numpy.log10(0.8)]
    postage_spline= interpolate.InterpolatedUnivariateSpline(lages,
                                                             numpy.log(postage),
                                                             k=3)
    plages= numpy.linspace(0.8,10.,1001)
    plpostage= numpy.exp(postage_spline(numpy.log10(plages)))
    plpostage/= numpy.nansum(plpostage)*(plages[1]-plages[0])
    bovy_plot.bovy_print(fig_width=7.)
    yrange=[0.,0.4]
#    yrange=[0.,0.7]
    bovy_plot.bovy_plot(plages,plpostage,
                        'k-',lw=2.,
                        xlabel=r'$\mathrm{Age}\,(\mathrm{Gyr})$',
                        ylabel=r'$p(\mathrm{RC | population\ Age})$',
                        xrange=[0.,10.],
                        yrange=yrange,
                        zorder=10,loglog=False)
    #Baseline
    bovy_plot.bovy_plot(plages,1./9.2*numpy.ones(len(plages)),
                        '-',color='0.4',overplot=True,zorder=3,lw=2.)
    #Fit the dependence
    if _FIT:
        opt= optimize.fmin_powell(chi2,[-1.,0.,0.,0.,-1.,0.,0.,0.],#[-4.,0.,0.25,0.,0.,1.],
                                  args=(numpy.log10(plages),
                                        numpy.log(plpostage)))
        print opt
        bovy_plot.bovy_plot(plages,numpy.exp(_fit_func(opt,numpy.log10(plages))),
                            'r-',overplot=True,zorder=11)
        a= numpy.log10(plages)
        bovy_plot.bovy_plot(plages[a <= 0.23],numpy.exp(polyfit1(a[a <= 0.23])),'b-',overplot=True,zorder=12)
        bovy_plot.bovy_plot(plages[a > 0.23],numpy.exp(polyfit2(a[a > 0.23])),'b-',overplot=True,zorder=12)
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #19
0
def plot_jr(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp,tintJ=200,ntintJ=20000)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,0.88719443,
                      -0.47713334,0.12019596])
    bovy_plot.bovy_print(fig_width=6.)
    aAI.plot(*obs,type='jr',downsample=True)
    bovy_plot.bovy_end_print(plotfilename)
예제 #20
0
def plot_maprmax(savefilename, plotname):
    with open(savefilename, 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples = numpy.array(pickle.load(savefile))
        bf_g15 = numpy.array(pickle.load(savefile))
        samples_g15 = numpy.array(pickle.load(savefile))
        bf_zero = numpy.array(pickle.load(savefile))
        samples_zero = numpy.array(pickle.load(savefile))
    maps = define_rcsample.MAPs()
    plotthis = numpy.zeros(len(bf)) + numpy.nan
    for ii, map in enumerate(maps.map()):
        tmed = numpy.median(
            numpy.exp(samples[ii, 3])[True -
                                      numpy.isnan(numpy.exp(samples[ii, 3]))])
        if tmed < 5.:
            tmed = 0.
        plotthis[ii] = tmed
    bovy_plot.bovy_print()
    maps.plot(plotthis,
              vmin=5.,
              vmax=13.,
              minnstar=15,
              zlabel=r'$R_{\mathrm{peak}}\,(\mathrm{kpc})$',
              shrink=0.68,
              cmap='coolwarm_r')
    # Sequences
    haloc = define_rcsample.highalphalocus()
    bovy_plot.bovy_plot(haloc[:, 0],
                        haloc[:, 1],
                        '-',
                        color='0.75',
                        lw=2.5,
                        overplot=True)
    haloc = define_rcsample.lowalphalocus()
    haloc = haloc[(haloc[:, 0] > -0.55) * (haloc[:, 0] < 0.225)]
    bovy_plot.bovy_plot(haloc[:, 0],
                        haloc[:, 1],
                        '-',
                        color='0.75',
                        lw=2.5,
                        overplot=True)
    # Label
    #t= pyplot.text(-0.51,0.235,r'$\mathrm{single}$',
    #                size=16.,color='w')
    #t.set_bbox(dict(alpha=0.5,color=cm.coolwarm(0.),
    #                edgecolor='none'))
    #t= pyplot.text(-0.475,0.195,r'$\mathrm{exponential}$',
    #                size=16.,color='w')
    t = pyplot.text(-0.625,
                    0.195,
                    r'$R_{\mathrm{peak}} < 5\,\mathrm{kpc}$',
                    size=16.,
                    color='w')
    t.set_bbox(dict(alpha=0.5, color=cm.coolwarm_r(0.), edgecolor='none'))
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotname, dpi=300)
    return None
예제 #21
0
def plotGPSamples(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    #Restore fit
    if os.path.exists(args[0]):
        fitsfile = open(args[0], 'rb')
        params = pickle.load(fitsfile)
        type = pickle.load(fitsfile)
        band = pickle.load(fitsfile)
        try:
            mean = pickle.load(fitsfile)
        except EOFError:
            mean = 'zero'
        fitsfile.close()
    else:
        raise IOError("You need to specify the file that holds the fits")
    if options.star:
        dir = '../data/star/'
    elif options.nuvx:
        dir = '../data/nuvx/'
    elif options.nuvxall:
        dir = '../data/nuvx_all/'
    elif options.uvx:
        dir = '../data/uvx/'
    elif options.rrlyrae:
        dir = '../data/rrlyrae/'
    else:
        dir = '../data/s82qsos/'
    #Load object
    v = varqso.VarQso(os.path.join(dir, options.key))
    v.LCparams = params[options.key]
    v.LC = varqso.LCmodel(trainSet=v._build_trainset(band),
                          type=type,
                          mean=mean)
    v.LCtype = type
    v.LCmean = mean
    v.fitband = band
    if os.path.exists(options.savefilename):
        print "Reusing samples from previous sampling"
        savefile = open(options.savefilename, 'rb')
        samples = pickle.load(savefile)
        savefile.close()
        v.set_sampleGP(samples)
    else:
        v.sampleGP(nsamples=options.nsamples)
        samples = v.get_sampleGP()
        #Save
        savefile = open(options.savefilename, 'wb')
        pickle.dump(samples, savefile)
        savefile.close()
    #Now plot
    bovy_plot.bovy_print()
    v.plot_sampleGP(d1=options.d1, d2=options.d2, whitemax=options.whitemax)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
def plot_pdfs_l(plotfilename):
    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,
                  vsun=[0.,30.24*8.,0.],
                  tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                  multi=_NTRACKCHUNKS)
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    #Sample from sdf
    llbd= sdf.sample(n=40000,lb=True)
    tlbd= sdft.sample(n=50000,lb=True)
    b,e= numpy.histogram(llbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    lspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=1.)
    lls= numpy.linspace(t[0],t[-1],_NLS)
    lps= numpy.exp(lspl(lls))
    lps/= numpy.sum(lps)*(lls[1]-lls[0])*2.
    b,e= numpy.histogram(tlbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    tspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=0.5)
    tls= numpy.linspace(t[0],t[-1],_NLS)
    tps= numpy.exp(tspl(tls))
    tps/= numpy.sum(tps)*(tls[1]-tls[0])*2.
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    bovy_plot.bovy_plot(lls,lps,'k-',lw=1.5,
                        xlabel=r'$\mathrm{Galactic\ longitude}\,(\mathrm{deg})$',
                        ylabel=r'$p(l)$',
                        xrange=[65.,250.],
                        yrange=[0.,1.2*numpy.nanmax(numpy.hstack((lps,tps)))])
    bovy_plot.bovy_plot(tls,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    #Transform to (l,b)
    XYZ= bovy_coords.galcenrect_to_XYZ(data[:,1],data[:,3],data[:,2],Xsun=8.)
    lbd= bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2],degree=True)
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    lbd= lbd[indx,:]
    bovy_plot.bovy_hist(lbd[:,0],bins=40,range=[65.,250.],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
예제 #23
0
def plot_dust_gaia(dist, plotname):
    # Load the dust map
    green15map = dust.load_combined(dist, nest=True, nside_out=_NSIDE)
    dm = dust.dist2distmod(dist)
    green15map[green15map == healpy.UNSEEN] = -1.
    print "%i are NaN" % (numpy.sum(numpy.isnan(green15map)))
    #theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),nest=True)
    #print (numpy.pi/2.-theta)[numpy.isnan(green15map)]/numpy.pi*180.
    #print phi[numpy.isnan(green15map)]/numpy.pi*180.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,
                             min=0.,
                             max=round(10. * (20. - dm - 0.68)) / 10.,
                             format=r'$%g$',
                             cmap='gist_yarg',
                             title="",
                             unit='$A_G\,(\mathrm{mag})$')
    # Plot outline of Marshall et al.
    ls = numpy.linspace(-100.125, 100.125, 1001)
    healpy.visufunc.projplot(ls, ls * 0. - 10.125, 'k--', lw=1.2, lonlat=True)
    healpy.visufunc.projplot(ls, ls * 0. + 10.125, 'k--', lw=1.2, lonlat=True)
    bs = numpy.linspace(-10.125, 10.125, 1001)
    healpy.visufunc.projplot(bs * 0. - 100.125, bs, 'k--', lw=1.2, lonlat=True)
    healpy.visufunc.projplot(bs * 0. + 100.125, bs, 'k--', lw=1.2, lonlat=True)
    # Plot boundary of Green et al. map, dec > -30.
    ras = numpy.linspace(0., 360., 1001)
    decs = ras * 0. - 30.
    lbs = bovy_coords.radec_to_lb(ras, decs, degree=True)
    ls = lbs[:, 0]
    bs = lbs[:, 1]
    # rm those within Marshall et al.
    keepIndx = True - ((ls > 259.875) * (numpy.fabs(bs) < 10.125) +
                       (ls < 100.125) * (numpy.fabs(bs) < 10.125))
    ls = ls[keepIndx]
    bs = bs[keepIndx]
    healpy.visufunc.projplot(ls, bs, 'k-.', lw=1.2, lonlat=True)
    # Labels
    healpy.visufunc.projtext(350.,
                             -8.,
                             r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
                             lonlat=True,
                             size=13.)
    healpy.visufunc.projtext(10.,
                             -60.,
                             r'$\mathrm{Drimmel\ et\ al.\ (2003)}$',
                             lonlat=True,
                             size=13.)
    healpy.visufunc.projtext(160.,
                             40.,
                             r'$\mathrm{Green\ et\ al.\ (2015)}$',
                             lonlat=True,
                             size=13.)
    bovy_plot.bovy_end_print(plotname)
예제 #24
0
def determine_kxky_error():
    #Load fiducial bar model
    spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR)[1::2,1::2]
    #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR)[1::2,1::2]*0.85
    #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-7%s.sav' % _HIVRESSTR)[1::2,1::2]*0.25
    psd2d= bovy_psd.psd2d(spvlos)
    kmax= 1./_RCDX
    #Calculate maximum
    psd2d[psd2d.shape[0]/2-1:psd2d.shape[0]/2+2,psd2d.shape[1]/2-1:psd2d.shape[1]/2+2]= 0.
    tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape)
    tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2
    tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2
    print tmax0*kmax, tmax1*kmax
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xrange=[-kmax,kmax],
                          yrange=[-kmax,kmax],
                          xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$',
                          ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$')
    bovy_plot.bovy_end_print('/Users/bovy/Desktop/test.png')
    #Read the data for the noise
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
    data= data[indx]
    #Get residuals
    dx= _RCDX
    pix= pixelize_sample.pixelXY(data,
                                 xmin=_RCXMIN,xmax=_RCXMAX,
                                 ymin=_RCYMIN,ymax=_RCYMAX,
                                 dx=dx,dy=dx)
    resvunc= pix.plot('VHELIO_AVG',
                      func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                      returnz=True,justcalc=True)
    #Now do 1000 MC simulations to determine the error on kmax
    nmc= 1000
    kxmax= numpy.zeros(nmc)
    kymax= numpy.zeros(nmc)
    for ii in range(nmc):
        newresv= spvlos+numpy.random.normal(size=spvlos.shape)*resvunc/220.
        simpsd2d= bovy_psd.psd2d(newresv*220.)
        simpsd2d[simpsd2d.shape[0]/2-1:simpsd2d.shape[0]/2+2,simpsd2d.shape[1]/2-1:simpsd2d.shape[1]/2+2]= 0.
        tmax= numpy.unravel_index(numpy.argmax(simpsd2d),psd2d.shape)
        tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2
        tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2
        kmax= 1./_RCDX
        kxmax[ii]= tmax0*kmax
        kymax[ii]= tmax1*kmax
    print numpy.mean(kxmax), numpy.std(kxmax)
    print numpy.mean(kymax), numpy.std(kymax)
    return None
예제 #25
0
def simplePlot(location=4242,
               plotfile=None,
               predict=False,
               nv=11,
               dmax=10. / 8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data = readVclosData(**kwargs)
    data = data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range = [-200., 200.]
    hist, xvec, p = bovy_plot.bovy_hist(
        data['VHELIO'],
        range=range,
        bins=31,
        histtype='step',
        color='k',
        xlabel=
        r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs = numpy.linspace(range[0], range[1], nv)
        pred_dist = _calc_pred(pred_vs, location, numpy.mean(data['GLON']),
                               dmax)
        data_int = numpy.sum(hist) * (xvec[1] - xvec[0])
        pred_dist *= data_int / numpy.sum(pred_dist) / (pred_vs[1] -
                                                        pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,
                            pred_dist,
                            '-',
                            color='0.65',
                            overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location + '\n' +
                        r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,
                        size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
예제 #26
0
def plotGPSamples(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    #Restore fit
    if os.path.exists(args[0]):
        fitsfile= open(args[0],'rb')
        params= pickle.load(fitsfile)
        type= pickle.load(fitsfile)
        band= pickle.load(fitsfile)
        try:
            mean= pickle.load(fitsfile)
        except EOFError:
            mean= 'zero'
        fitsfile.close()
    else:
        raise IOError("You need to specify the file that holds the fits")
    if options.star:
        dir= '../data/star/'
    elif options.nuvx:
        dir= '../data/nuvx/'
    elif options.nuvxall:
        dir= '../data/nuvx_all/'
    elif options.uvx:
        dir= '../data/uvx/'
    elif options.rrlyrae:
        dir= '../data/rrlyrae/'
    else:
        dir= '../data/s82qsos/'
    #Load object
    v= varqso.VarQso(os.path.join(dir,options.key))
    v.LCparams= params[options.key]
    v.LC= varqso.LCmodel(trainSet=v._build_trainset(band),type=type,mean=mean)
    v.LCtype= type
    v.LCmean= mean
    v.fitband= band
    if os.path.exists(options.savefilename):
        print "Reusing samples from previous sampling"
        savefile= open(options.savefilename,'rb')
        samples= pickle.load(savefile)
        savefile.close()
        v.set_sampleGP(samples)
    else:
        v.sampleGP(nsamples=options.nsamples)
        samples= v.get_sampleGP()
        #Save
        savefile= open(options.savefilename,'wb')
        pickle.dump(samples,savefile)
        savefile.close()
    #Now plot
    bovy_plot.bovy_print()
    v.plot_sampleGP(d1=options.d1,d2=options.d2,whitemax=options.whitemax)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
예제 #27
0
def plot_dfcorrections(plotfilename):
    niters= [1,2,3,4,5,10,15,20,25]
    bovy_plot.bovy_print(fig_height=7.,fig_width=8.)
    ii= 0
    # Load DF
    pyplot.subplot(2,1,1)
    dfc= dehnendf(beta=0.,correct=True,niter=niters[ii])
    bovy_plot.bovy_plot(dfc._corr._rs,
                        numpy.log(dfc._corr._corrections[:,0]),
                        '-',gcf=True,color=cm.jet(1.),lw=2.,zorder=1,
                        xrange=[0.,5.],
                        yrange=[-0.25,0.25],
                        ylabel=r'$\ln \Sigma_{\mathrm{out}}(R)-\ln\Sigma_{\mathrm{DF}}(R)$')
    linthresh= 0.0001
    pyplot.yscale('symlog',linthreshy=linthresh)
    for ii,niter in enumerate(niters[1:]):
        dfcn= dehnendf(beta=0.,correct=True,niter=niter)
        dfcp= dehnendf(beta=0.,correct=True,niter=niter-1)
        bovy_plot.bovy_plot(dfc._corr._rs,
                            numpy.log(dfcn._corr._corrections[:,0])-numpy.log(dfcp._corr._corrections[:,0]),
                            '-',overplot=True,
                            color=cm.jet(1.-(ii+1)/float(len(niters))),lw=2.,
                            zorder=ii+2)
    pyplot.fill_between(numpy.linspace(0.,5.,2.),
                        -linthresh*numpy.ones(2),
                         linthresh*numpy.ones(2),color='0.9',
                         zorder=0)
    bovy_plot.bovy_text(4.,-0.00008,r'$\mathrm{linear\ scale}$',
                        backgroundcolor='w',size=16.)
    pyplot.subplot(2,1,2)
    bovy_plot.bovy_plot(dfc._corr._rs,
                        0.5*numpy.log(dfc._corr._corrections[:,1]),
                        '-',gcf=True,color=cm.jet(1.),lw=2.,zorder=1,
                        xrange=[0.,5.],
                        yrange=[-0.25,0.25],
                        xlabel=r'$R/R_0$',
                        ylabel=r'$\ln \sigma_{R,\mathrm{out}}(R)-\ln\sigma_{R,\mathrm{DF}}(R)$')
    pyplot.yscale('symlog',linthreshy=linthresh)
    for ii,niter in enumerate(niters[1:]):
        dfcn= dehnendf(beta=0.,correct=True,niter=niter)
        dfcp= dehnendf(beta=0.,correct=True,niter=niter-1)
        bovy_plot.bovy_plot(dfc._corr._rs,
                            numpy.log(dfcn._corr._corrections[:,1])-numpy.log(dfcp._corr._corrections[:,1]),
                            '-',overplot=True,
                            color=cm.jet(1.-(ii+1)/float(len(niters))),lw=2.,
                            zorder=ii+2)
    pyplot.fill_between(numpy.linspace(0.,5.,2.),
                        -linthresh*numpy.ones(2),
                         linthresh*numpy.ones(2),color='0.9',
                         zorder=0)
    bovy_plot.bovy_text(4.,-0.00008,r'$\mathrm{linear\ scale}$',
                        backgroundcolor='w',size=16.)
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #28
0
def plotCombinedPDF(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()
    #First calculate the derivative properties
    if not options.group is None:
        gafes, gfehs, legend= getMultiComparisonBins(options)
    else:
        legend= None
    if not options.multi is None:
        PDFs= multi.parallel_map((lambda x: calcAllPDFs(x,options,args)),
                                  range(npops),
                                  numcores=numpy.amin([options.multi,
                                                       npops,
                                                       multiprocessing.cpu_count()]))
    else:
        PDFs= []
        for ii in range(npops):
            PDFs.append(calcAllPDFs(ii,options,args))
    #Go through and combine
    combined_lnpdf= numpy.zeros((options.nrds,options.nfhs))
    for ii in range(npops):
        if not options.group is None:
            if numpy.amin((gfehs-fehs[ii])**2./0.1+(gafes-afes[ii])**2./0.0025) > 0.001:
                continue
        combined_lnpdf+= PDFs[ii]
    alogl= combined_lnpdf-numpy.nanmax(combined_lnpdf)
    #Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(numpy.exp(alogl).T,
                          origin='lower',cmap='gist_yarg',
                          interpolation='nearest',
                          xrange=[1.9,3.5],yrange=[-1./32.,1.+1./32.],
                          xlabel=r'$R_d\ (\mathrm{kpc})$',ylabel=r'$f_h$')
    if not legend is None:
        bovy_plot.bovy_text(legend,top_left=True,
                            size=14.)
    bovy_plot.bovy_end_print(options.outfilename)
    #Calculate and print derived properties
    derivProps= rawDerived(alogl,options,
                           vo=options.fixvc/_REFV0,zh=options.fixzh,
                           dlnvcdlnr=options.dlnvcdlnr)
    for key in derivProps.keys():
        if not '_err' in key:
            print key, derivProps[key], derivProps[key+'_err'], \
                derivProps[key]/derivProps[key+'_err'] 
    return None
예제 #29
0
def plotRbestvsRmean(savefilename,plotfilename):
    #Read surface densities
    #First read the surface densities
    if os.path.exists(savefilename):
        surffile= open(savefilename,'rb')
        surfrs= pickle.load(surffile)
        surfs= pickle.load(surffile)
        surferrs= 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)
    #Load g orbits
    orbitsfile= 'gOrbitsNew.sav'
    savefile= open(orbitsfile,'rb')
    orbits= pickle.load(savefile)
    savefile.close()
    #Cut to S/N, logg, and EBV
    indx= (orbits.sna > 15.)*(orbits.logga > 4.2)*(orbits.ebv < 0.3)
    orbits= orbits[indx]
    #Load the orbits into the pixel structure
    pix= pixelAfeFeh(orbits,dfeh=0.1,dafe=0.05)
    #Now calculate meanr
    rmean= numpy.zeros_like(surfrs)
    for ii in range(len(surfrs)):
        data= pix(fehs[ii],afes[ii])
        vals= data.densrmean*8.
        if False:#True:
            rmean[ii]= numpy.mean(vals)
        else:
            rmean[ii]= numpy.median(vals)
    #Plot
    indx= numpy.isnan(surfrs)
    indx[50]= True
    indx[57]= True
    indx= True - indx
    surfrs= surfrs[indx]
    rmean= rmean[indx]
    fehs= fehs[indx]
    afes= afes[indx]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(rmean,surfrs,c=afes,marker='o',scatter=True,
                        xlabel=r'$\mathrm{mean\ orbital\ radius\ of\ MAP}\,(\mathrm{kpc})$',
                        ylabel=r'$\mathrm{radius\ at\ which\ MAP\ measures}\ \Sigma_{1.1}\,(\mathrm{kpc})$',
                        xrange=[4.,10.],
                        yrange=[4.,10.],
                        edgecolor='none',zorder=10,s=50.)
    bovy_plot.bovy_plot([4.5,9.],[4.5,9.],'-',color='0.50',overplot=True,lw=1.)
    bovy_plot.bovy_end_print(plotfilename)
예제 #30
0
def plot_aagrid(plotfilename1,plotfilename2):
    #Setup orbit
    E, Lz= -1.25, 0.6
    o= Orbit([0.8,0.3,Lz/0.8,0.,numpy.sqrt(2.*(E-evalPot(0.8,0.,MWPotential2014)-(Lz/0.8)**2./2.-0.3**2./2.)),0.])
    delta= 0.434
    #Integrate the orbit, setup Staeckel already to calculate the period
    aAS= actionAngleStaeckel(pot=MWPotential2014,delta=delta,c=True)
    orbt= 2.*numpy.pi/aAS.actionsFreqs(o)[4]  
    norb= 5.
    nt= 501
    ts= numpy.linspace(0.,norb*orbt,nt)
    o.integrate(ts,MWPotential2014,method='symplec4_c')
    #First do adiabatic
    aAA= actionAngleAdiabatic(pot=MWPotential2014,gamma=1.,c=True)
    aAAG= actionAngleAdiabaticGrid(pot=MWPotential2014,gamma=1.,c=True,
                                   nR=31,nEz=31,nEr=51,nLz=51)
    jfa= aAA(o.R(ts),o.vR(ts),o.vT(ts),o.z(ts),o.vz(ts),o.phi(ts))
    jfag= aAAG(o.R(ts),o.vR(ts),o.vT(ts),o.z(ts),o.vz(ts),o.phi(ts))
    #First do adiabatic
    #aAS already setup
    aASG= actionAngleStaeckelGrid(pot=MWPotential2014,delta=delta,c=True,
                                  nE=51,npsi=51,nLz=51)
    jfs= aAS(o.R(ts),o.vR(ts),o.vT(ts),o.z(ts),o.vz(ts),o.phi(ts))
    jfsg= aASG(o.R(ts),o.vR(ts),o.vT(ts),o.z(ts),o.vz(ts),o.phi(ts))
    bovy_plot.bovy_print()
    line1= bovy_plot.bovy_plot(jfa[0],jfa[2],'r.',
                               xrange=[0.045,0.055],
                               yrange=[0.0075,0.011],
                               xlabel=r'$J_R$',ylabel=r'$J_z$',zorder=2)
    line2= bovy_plot.bovy_plot(jfag[0],jfag[2],'rx',overplot=True,zorder=1)
    bovy_plot.bovy_plot(jfs[0],jfs[2],'k,',overplot=True)
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{\texttt{actionAngleAdiabatic}}$',
                   r'$\mathrm{\texttt{actionAngleAdiabaticGrid}}$',),
                  loc='upper right',#bbox_to_anchor=(.91,.375),
                  numpoints=1,
                  prop={'size':14},
                  frameon=False)
    bovy_plot.bovy_end_print(plotfilename1)
    #Zoom of Staeckel
    line1= bovy_plot.bovy_plot(jfs[0],jfs[2],'k.',
                               xrange=[0.05025,0.05145],
                               yrange=[0.0086,0.00933],
                               xlabel=r'$J_R$',ylabel=r'$J_z$')
    line2= bovy_plot.bovy_plot(jfsg[0],jfsg[2],'kx',overplot=True)
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{\texttt{actionAngleStaeckel}}$',
                   r'$\mathrm{\texttt{actionAngleStaeckelGrid}}$',),
                  loc='upper right',#bbox_to_anchor=(.91,.375),
                  numpoints=1,
                  prop={'size':14},
                  frameon=False)
    bovy_plot.bovy_end_print(plotfilename2)
    return None
예제 #31
0
def plotPriorSurf(plotfilename):
    #Calculate the surface density profile for each trial potential, then plot the range
    if '.png' in plotfilename:
        savefilename= plotfilename.replace('.png','.sav')
    elif '.ps' in plotfilename:
        savefilename= plotfilename.replace('.ps','.sav')
    if not os.path.exists(savefilename):
        options= setup_options(None)
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        options.fitdvt= False
        rs= numpy.linspace(4.2,9.8,101)
        rds= numpy.linspace(2.,3.4,8)
        fhs= numpy.linspace(0.,1.,16)
        surfz= numpy.zeros((len(rs),len(rds)*len(fhs)))+numpy.nan
        ro= 1.
        vo= 230./220.
        dlnvcdlnr= 0.
        zh= 400.
        for jj in range(len(rds)):
            for kk in range(len(fhs)):
                #Setup potential to calculate stuff
                potparams= numpy.array([numpy.log(rds[jj]/8.),vo,numpy.log(zh/8000.),fhs[kk],dlnvcdlnr])
                try:
                    pot= setup_potential(potparams,options,0,returnrawpot=True)
                except RuntimeError:
                    continue
                for ii in range(len(rs)):
                    surfz[ii,jj*len(fhs)+kk]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(rs[ii]/8.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
        #Find minimum and maximum curves
        minsurfz= numpy.nanmin(surfz,axis=1)
        maxsurfz= numpy.nanmax(surfz,axis=1)
        #Save
        save_pickles(savefilename,rs,minsurfz,maxsurfz)
    else:
        savefile= open(savefilename,'rb')
        rs= pickle.load(savefile)
        minsurfz= pickle.load(savefile)
        maxsurfz= pickle.load(savefile)
        savefile.close()
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([numpy.nan],[numpy.nan],'ko',
                        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)
    pyplot.fill_between(rs,minsurfz,maxsurfz,
                        color='0.50')
    bovy_plot.bovy_text(8.,68.,r'$\odot$',size=16.,verticalalignment='center',
                        horizontalalignment='center')
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #32
0
def plotSkew(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    savefilename= args[0]
    if os.path.exists(savefilename):
        savefile= open(savefilename,'rb')
        skews= pickle.load(savefile)
        gaussskews= pickle.load(savefile)
        type= pickle.load(savefile)
        band= pickle.load(savefile)
        mean= pickle.load(savefile)
        taus= pickle.load(savefile)      
        savefile.close()
    else:
        parser.print_help()
        return
    #Accumulate
    keys= skews.keys()
    allskews= numpy.zeros((len(keys),len(taus)))
    allgaussskews= numpy.zeros((len(keys),gaussskews[keys[0]].shape[0],
                                len(taus)))
    for ii, key in enumerate(keys):
        allskews[ii,:]= -skews[key] #go to regular definition
        allgaussskews[ii,:]= -gaussskews[key]
    #Statistic
    q= 0.99
    statistic= numpy.median
    if not options.indx is None:
        print "indx option not allowed"
        return None
    indx= numpy.all(numpy.isnan(allskews),axis=1)
    allskews= allskews[True-indx,:]
    allgaussskews= allgaussskews[True-indx,:,:]
    #Median
    medianskew= statistic(allskews,axis=0)
    mediangaussskew= statistic(allgaussskews,axis=0)
    #Determine 1-sigma
    sigma= quantile(mediangaussskew,q=q)
    #Plot
    tauindx= 5
    print "Showing tau %f" % (taus[tauindx]*365.25)
    bovy_plot.bovy_print(fig_width=7.)
    bovy_plot.bovy_hist(allskews[:,tauindx],bins=31,
                        color='k',normed=True,histtype='step',
                        xlabel=r'$\mathrm{skew}(\tau = %i\ \mathrm{days})$' % (int(taus[tauindx]*365.25)))
    bovy_plot.bovy_plot([numpy.median(allskews[:,tauindx]),numpy.median(allskews[:,tauindx])],
                        [0.,10.],'k-',overplot=True)
    bovy_plot.bovy_plot([numpy.mean(allskews[:,tauindx]),numpy.mean(allskews[:,tauindx])],
                        [0.,10.],'k--',overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
def plot_distanceintegral(savename,plotname,rmcenter=False,
                          onlygreen=False):
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            area= pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                             numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                             nest=False)
        cosb= numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename,area)
    # Plot the power spectrum
    if True:
        psdx, psd= signal.periodogram(area*dust._GREEN15DISTS**3./numpy.sum(area*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                                      detrend=lambda x: x,scaling='spectrum')
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(psdx[1:],psd[1:],
                            'k-',loglog=True,
                            xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$P_k$',
                            xrange=[0.04,4.])
        bovy_plot.bovy_text(r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
                            bottom_left=True,size=16.)
        bovy_plot.bovy_end_print(plotname)               
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(dust._GREEN15DISTMODS,
                            area*dust._GREEN15DISTS**3.,
                            'k-',
                            xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    spl= interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                  area*dust._GREEN15DISTS**3.,
                                                  k=5)
    fthder= [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
    print "Simpson error= %g, volume= %g" % (0.5**4./180.*numpy.mean(numpy.fabs(fthder))/integrate.simps(area*dust._GREEN15DISTS**3.,dx=0.5),numpy.sum(area*dust._GREEN15DISTS**3.))
    return None
예제 #34
0
def plot_dustnearplane(plotname,green=False):
    if green: savefile= _SAVEFILE_GREEN
    else: savefile= _SAVEFILE_MARSHALL
    # Grid
    ls= numpy.linspace(15.,70.,_NL)
    bs= numpy.linspace(-2.,2.,_NB)
    if not os.path.exists(savefile):
        # Setup dust map
        if green:
            dmap= mwdust.Green15(filter='2MASS H')
        else:
            dmap= mwdust.Marshall06(filter='2MASS H')
        plotthis= numpy.empty((_NL,_NB))
        rad= 0.5 # deg
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                pa, ah= dmap.dust_vals_disk(ls[ii],bs[jj],7.,rad)
                plotthis[ii,jj]= numpy.sum(pa*ah)/numpy.sum(pa)
        save_pickles(savefile,plotthis)
    else:
        with open(savefile,'rb') as f:
            plotthis= pickle.load(f)
    # Now plot
    bovy_plot.bovy_print(fig_width=8.4,fig_height=4.)
    bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm,
#                          interpolation='nearest',
                          colorbar=True,shrink=0.45,
                          vmin=0.,vmax=2.-0.75*green,aspect=3.,
                          xrange=[ls[-1]+(ls[1]-ls[0])/2.,
                                  ls[0]-(ls[1]-ls[0])/2.],
                          yrange=[bs[0]-(bs[1]-bs[0])/2.,
                                  bs[-1]+(bs[1]-bs[0])/2.],
                          xlabel=r'$l\,\mathrm{(deg)}$',
                          ylabel=r'$b\,\mathrm{(deg)}$',
                          zlabel=r'$A_H\,(\mathrm{mag})$',
                          zorder=0)
    bovy_plot.bovy_text(r'$D = 7\,\mathrm{kpc}$',top_left=True,
                        color='w',size=16.)
    # Overplot fields
    glons= [34.,64.,27.]
    glats= [0.,0.,0.]
    colors= ['w','w','y']
    xs= numpy.linspace(-1.5,1.5,201)
    ys= numpy.sqrt(1.5**2.-xs**2.)
    for glon,glat,c in zip(glons,glats,colors):
        bovy_plot.bovy_plot(xs+glon,ys+glat,'-',overplot=True,zorder=1,lw=2.,
                            color=c)
        bovy_plot.bovy_plot(xs+glon,-ys+glat,'-',overplot=True,zorder=1,lw=2.,
                            color=c)
    bovy_plot.bovy_end_print(plotname)
    return None
예제 #35
0
def plotRdsz_single(ii,options,args):
    if True:
        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.' % ii
        newname+= spl[-1]
        savefile= open(newname,'rb')
        try:
            if not _NOTDONEYET:
                params= pickle.load(savefile)
                mlogl= pickle.load(savefile)
            logl= pickle.load(savefile)
        except:
            return None
        finally:
            savefile.close()
        if _NOTDONEYET:
            logl[(logl == 0.)]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        marglogl= numpy.zeros((logl.shape[0],logl.shape[6]))
        for jj in range(marglogl.shape[0]):
            for kk in range(marglogl.shape[1]):
                indx= True-numpy.isnan(logl[jj,0,0,:,:,:,kk,:,:,:,:].flatten())
                if numpy.sum(indx) > 0:
                    marglogl[jj,kk]= misc.logsumexp(logl[jj,0,0,:,:,:,kk,:,:,:,:].flatten()[indx])
                else:
                    marglogl[jj,kk]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        #Normalize
        alogl= marglogl-numpy.amax(marglogl)
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(numpy.exp(alogl).T,
                              origin='lower',cmap='gist_yarg',
                              interpolation='nearest',
                              xrange=[1.5,4.5],
                              yrange=[numpy.log(15./220.),numpy.log(60./220.)],
                              xlabel=r'$R_d$',
                              ylabel=r'$\ln \sigma_Z / 220\ \mathrm{km\,s}^{-1}$')
        #Plotname
        spl= options.outfilename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        bovy_plot.bovy_end_print(newname)
    return None
예제 #36
0
def plot_distanceintegral_final(plotname):
    # Reload full area
    with open('../savs/distInt.sav', 'rb') as savefile:
        area_full = pickle.load(savefile)
    # Reload full area w/o center
    with open('../savs/distIntRmcenter.sav', 'rb') as savefile:
        area_rmcenter = pickle.load(savefile)
    # Calculate PSD of each
    psdx_full, psd_full= \
        signal.periodogram(area_full*dust._GREEN15DISTS**3./numpy.sum(area_full*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                           detrend=lambda x: x,scaling='spectrum')
    psdx_rmcenter, psd_rmcenter= \
        signal.periodogram(area_rmcenter*dust._GREEN15DISTS**3./numpy.sum(area_rmcenter*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                           detrend=lambda x: x,scaling='spectrum')
    bovy_plot.bovy_print(fig_height=5.5)
    matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
    line1 = bovy_plot.bovy_plot(
        psdx_full[1:],
        numpy.sqrt(psd_full[1:]),
        'k-',
        loglog=True,
        xlabel=r'$\mathrm{distance\ resolution}\ k_\mu\,(\mathrm{mag}^{-1})$',
        ylabel=r'$\mathrm{effective\ volume\ error}\ \sqrt{P_k}$',
        xrange=[0.04, 20.],
        yrange=[10**-11., 5.])
    line2 = bovy_plot.bovy_plot(psdx_rmcenter[1:],
                                numpy.sqrt(psd_rmcenter[1:]),
                                'r-',
                                overplot=True)
    bovy_plot.bovy_plot([1., 10.], [6. * 10.**-4., 6. * 10.**-7.],
                        'k--',
                        overplot=True)
    bovy_plot.bovy_plot([1., 10.], [2. * 10.**-5., 2. * 10.**-10.],
                        'r--',
                        overplot=True)
    pyplot.legend(
        (line1[0], line2[0]),
        (r'$\mathrm{full\ sky}$',
         r'$\mathrm{excluding}\ |180^\circ-l| > 155^\circ, |b| < 25^\circ$'),
        loc='upper right',  #bbox_to_anchor=(.02,.02),
        numpoints=8,
        prop={'size': 14},
        frameon=False)
    bovy_plot.bovy_text(
        r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
        bottom_left=True,
        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
예제 #37
0
def testErrs(options,args):
    ndfehs, ndafes= 201,201
    dfehs= numpy.linspace(0.01,0.4,ndfehs)
    dafes= numpy.linspace(0.01,0.3,ndafes)
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        loglike= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        loglike= numpy.zeros((ndfehs,ndafes))
        ii, jj= 0, 0
    while ii < ndfehs:
        while jj < ndafes:
            sys.stdout.write('\r'+"Working on %i / %i" %(ii*ndafes+jj+1,ndafes*ndfehs))
            sys.stdout.flush()
            loglike[ii,jj]= errsLogLike(dfehs[ii],dafes[jj],options)
            jj+= 1
        ii+= 1
        jj= 0
        save_pickles(args[0],loglike,ii,jj)
    save_pickles(args[0],loglike,ii,jj)
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    if options.prior:
        prior= numpy.zeros((ndfehs,ndafes))
        for ii in range(ndfehs):
            prior[ii,:]= -0.5*(dafes-0.1)**2./0.1**2.-0.5*(dfehs[ii]-0.2)**2./0.1**2.
        loglike+= prior
    loglike-= maxentropy.logsumexp(loglike)
    loglike= numpy.exp(loglike)
    loglike/= numpy.sum(loglike)*(dfehs[1]-dfehs[0])*(dafes[1]-dafes[0])
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(loglike.T,origin='lower',
                          cmap='gist_yarg',
                          xlabel=r'\delta_{[\mathrm{Fe/H}]}',
                          ylabel=r'\delta_{[\alpha/\mathrm{Fe}]}',
                          xrange=[dfehs[0],dfehs[-1]],
                          yrange=[dafes[0],dafes[-1]],
                          contours=True,
                          cntrmass=True,
                          onedhists=True,
                          levels= special.erf(0.5*numpy.arange(1,4)))
    if options.prior:
        bovy_plot.bovy_text(r'$\mathrm{with\ Gaussian\ prior:}$'+
                            '\n'+r'$\delta_{[\mathrm{Fe/H}]}= 0.2 \pm 0.1$'
                            +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]}= 0.1 \pm 0.1$',
top_right=True)
    bovy_plot.bovy_end_print(options.plotfile)
예제 #38
0
파일: plotXD.py 프로젝트: ritabanc/qso-var
def plotXD(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    if os.path.exists(args[0]):
        savefile = open(args[0], 'rb')
        xamp = pickle.load(savefile)
        xmean = pickle.load(savefile)
        xcovar = pickle.load(savefile)
        savefile.close()
    else:
        print args[0] + " does not exist ..."
        print "Returning ..."
        return
    #Load XD object in xdtarget
    xdt = xdtarget.xdtarget(amp=xamp, mean=xmean, covar=xcovar)
    out = xdt.sample(nsample=options.nsamples)
    #Prepare for plotting
    if options.expd1: xs = nu.exp(out[:, options.d1])
    elif not options.divided1 is None:
        xs = out[:, options.d1] / options.divided1
    else:
        xs = out[:, options.d1]
    if options.expd2: ys = nu.exp(out[:, options.d2])
    elif not options.divided2 is None:
        ys = out[:, options.d2] / options.divided2
    else:
        ys = out[:, options.d2]
    if options.type == 'DRW':
        #plot logA, logA = 0
        if options.d1 == 0 and options.d2 == 1:
            #Convert to logA
            xs = (nu.log(2.) + xs + nu.log(1. - nu.exp(-1. / nu.exp(ys)))) / 2.
        elif options.d1 == 1 and options.d2 == 0:
            #Convert to logA
            ys = (nu.log(2.) + ys + nu.log(1. - nu.exp(-1. / nu.exp(xs)))) / 2.
        else:
            print "d1 and d2 have to be 0 or 1 (and not the same!) ..."
            print "Returning ..."
            return
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(xs,
                          ys,
                          'k,',
                          onedhists=True,
                          xrange=[options.xmin, options.xmax],
                          yrange=[options.ymin, options.ymax],
                          xlabel=options.xlabel,
                          ylabel=options.ylabel)
    bovy_plot.bovy_end_print(options.plotfilename)
예제 #39
0
def plot_distanceareaintegral(savename,
                              plotname,
                              rmcenter=False,
                              onlygreen=False):
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi = healpy.pixelfunc.pix2ang(
            _NSIDE,
            numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
            nest=False)
        cosb = numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceAreaIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename, area)
    # Plot the power spectrum
    area = numpy.array(area)
    if True:
        psdthis = ((area.T * dust._GREEN15DISTS**3.).T / numpy.sum(
            (area.T * dust._GREEN15DISTS**3.), axis=1))
        psdx, psd = signal.periodogram(
            psdthis,
            fs=1. / (dust._GREEN15DISTMODS[1] - dust._GREEN15DISTMODS[0]),
            detrend=lambda x: x,
            scaling='spectrum',
            axis=0)
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        healpy.visufunc.mollview(numpy.log10(psd[-2]),
                                 nest=False,
                                 xsize=4000,
                                 min=-10.,
                                 max=-3.,
                                 cmap='gist_yarg',
                                 title="")
        bovy_plot.bovy_end_print(plotname)
    return None
def checkAbundanceScatterClusters():
    # First read the cluster data
    cldata = read_clusterdata.read_caldata()
    # Read the allStar data to match
    # For each of the calibration open clusters, calculate the offset from the
    # mean in our FEHTAG and AFETAG
    clusters = [
        'M71', 'N2158', 'N2420', 'N188', 'M67', 'N7789', 'N6819', 'N6791'
    ]
    fehoffset = []
    afeoffset = []
    for cluster in clusters:
        tdata = cldata[cldata['CLUSTER'] == cluster.upper()]
        tdata= tdata[(tdata['TEFF'] < _TEFFMAX)\
                         *(tdata['TEFF'] > _TEFFMIN)\
                         *(tdata['LOGG'] < 3.5)]
        # Compute the average feh and afe and save the offsets
        medianfeh = numpy.median(tdata['FE_H'])
        medianafe = numpy.median(tdata[define_rcsample._AFETAG])
        fehoffset.extend(tdata['FE_H'] - medianfeh)
        afeoffset.extend(tdata[define_rcsample._AFETAG] - medianafe)
        if cluster == 'M67': print medianfeh, medianafe, len(tdata)
    fehoffset = numpy.array(fehoffset)
    afeoffset = numpy.array(afeoffset)
    print 'FE_H scatter %g' % (numpy.nanstd(
        fehoffset[numpy.fabs(fehoffset) < 0.3]))
    print 'A_FE scatter %g' % (numpy.nanstd(
        afeoffset[numpy.fabs(afeoffset) < 0.3]))
    gindx = (numpy.fabs(fehoffset) < 0.3) * (numpy.fabs(afeoffset) < 0.3)
    print 'FE_H/A_FE correlation %g' % (
        numpy.mean(afeoffset[gindx] * fehoffset[gindx]) /
        numpy.nanstd(fehoffset[numpy.fabs(fehoffset) < 0.3]) /
        numpy.nanstd(afeoffset[numpy.fabs(afeoffset) < 0.3]))
    print 'FE_H robust scatter %g' % (1.4826 *
                                      numpy.median(numpy.fabs(fehoffset)))
    print 'A_FE robust scatter %g' % (1.4826 *
                                      numpy.median(numpy.fabs(afeoffset)))
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(fehoffset, range=[-0.3, 0.3], bins=31, histtype='step')
    bovy_plot.bovy_hist(afeoffset,
                        range=[-0.3, 0.3],
                        bins=31,
                        histtype='step',
                        overplot=True)
    bovy_plot.bovy_end_print('test.png')
    return None
예제 #41
0
def plot_dustinfield(plotname, field, threshold=False):
    savefile = _SAVEFILE_MARSHALL
    savefile = savefile.replace('FIELD', '%i' % field)
    # Grid
    ls = numpy.linspace(-1.75, 1.75, _NL) + field
    bs = numpy.linspace(-1.75, 1.75, _NB)
    if not os.path.exists(savefile):
        # Setup dust map
        dmap = mwdust.Marshall06(filter='2MASS H')
        plotthis = numpy.empty((_NL, _NB))
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                plotthis[ii, jj] = dmap(ls[ii], bs[jj], 7.)
        save_pickles(savefile, plotthis)
    else:
        with open(savefile, 'rb') as f:
            plotthis = pickle.load(f)
    # Remove outside the field
    tls = numpy.tile(ls, (_NB, 1)).T
    tbs = numpy.tile(bs, (_NL, 1))
    plotthis[(tls - field)**2. + tbs**2. > 1.5**2.] = numpy.nan
    if threshold:
        plotthis[plotthis > 1.4] = numpy.nan
    # Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(
        plotthis[::-1].T,
        origin='lower',
        cmap=cm.coolwarm,
        interpolation='nearest',
        vmin=0.,
        vmax=2.,
        aspect=1.,
        xrange=[ls[-1] + (ls[1] - ls[0]) / 2., ls[0] - (ls[1] - ls[0]) / 2.],
        yrange=[bs[0] - (bs[1] - bs[0]) / 2., bs[-1] + (bs[1] - bs[0]) / 2.],
        xlabel=r'$l\,\mathrm{(deg)}$',
        ylabel=r'$b\,\mathrm{(deg)}$',
        zlabel=r'$A_H\,(\mathrm{mag})$',
        zorder=0)
    bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field,
                        top_left=True,
                        color='k',
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
예제 #42
0
def plot_maphz(plotname):
    # Load the two fit
    with open('../mapfits/tribrokentwoexp.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples = numpy.array(pickle.load(savefile))
    maps = define_rcsample.MAPs()
    plotthisz1 = numpy.zeros(len(bf)) + numpy.nan
    plotthisz1e = numpy.zeros(len(bf)) + numpy.nan
    plotthisz2 = numpy.zeros(len(bf)) + numpy.nan
    plotthisz2e = numpy.zeros(len(bf)) + numpy.nan
    for ii, map in enumerate(maps.map()):
        hzindx= (True-numpy.isnan(samples[ii,4]))\
            *(True-numpy.isnan(samples[ii,5]))\
            *(densprofiles.ilogit(samples[ii,4]) > 0.15)
        tmed = numpy.median(1. / samples[ii, 1, hzindx])
        terr = numpy.std(1. / samples[ii, 1, hzindx])
        plotthisz1[ii] = tmed
        plotthisz1e[ii] = terr
        tmed = numpy.median(1. / samples[ii, 5, hzindx])
        terr = numpy.std(1. / samples[ii, 5, hzindx])
        plotthisz2[ii] = tmed
        plotthisz2e[ii] = terr
    plotthisz1[plotthisz1e / plotthisz1 > 0.5] = numpy.nan
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(
        plotthisz2 * 1000.,
        plotthisz1 * 1000.,
        'ko',
        xrange=[0., 1200.],
        yrange=[0., 1200.],
        xlabel=r'$2^\mathrm{nd}\ \mathrm{scale\ height\,(pc)}$',
        ylabel=r'$1^\mathrm{st}\ \mathrm{scale\ height\,(pc)}$',
        zorder=2)
    bovy_plot.bovy_plot([0, 1200], [0, 1200], 'k--', overplot=True, lw=2.)
    pyplot.errorbar(plotthisz2 * 1000.,
                    plotthisz1 * 1000.,
                    yerr=plotthisz1e * 1000.,
                    marker='o',
                    color='k',
                    ls='none',
                    zorder=1)
    bovy_plot.bovy_end_print(plotname)
    return None
예제 #43
0
def plot_dustwapogee(plotname):
    # Load the dust map
    green15map = dust.load_green15(5., nest=True, nside_out=_NSIDE)
    green15map[green15map == healpy.UNSEEN] = -1.
    # plot it
    healpy.visufunc.mollview(green15map,
                             nest=True,
                             xsize=4000,
                             min=0.,
                             max=.8,
                             format=r'$%g$',
                             title='',
                             cmap='gist_yarg',
                             unit='$A_H\,(\mathrm{mag})$')
    # Load the RC data to get the fields
    data = define_rcsample.get_rcsample()
    loc_ids = numpy.array(list(set(data['LOCATION_ID'])))
    # Load the selection function, just to get the field centers
    apo = apogee.select.apogeeSelect(_justprocessobslog=True)
    theta = numpy.empty(len(loc_ids))
    phi = numpy.empty(len(loc_ids))
    for ii, loc_id in enumerate(loc_ids):
        tl, tb = apo.glonGlat(loc_id)
        theta[ii] = (90. - tb) / 180. * numpy.pi
        phi[ii] = tl / 180. * numpy.pi
    hib = numpy.fabs((numpy.pi / 2. - theta)) > (8. / 180. * numpy.pi)
    healpy.visufunc.projplot(theta[hib],
                             phi[hib],
                             'o',
                             ms=5.,
                             mfc='none',
                             mew=0.8,
                             mec='k')
    lowb = True - hib
    healpy.visufunc.projplot(theta[lowb],
                             phi[lowb],
                             'o',
                             ms=5.,
                             mfc='none',
                             mec='w',
                             mew=0.8)
    bovy_plot.bovy_end_print(plotname)
예제 #44
0
def plot_rotcurves(plotfilename):
    rs= numpy.linspace(3.5,16.,1001)
    #1: flat
    vo,ro= 0.92772766, 1.00939298
    vflat= rs**0.*vo*_REFV0
    #2: power-law
    vo, ro, beta= 0.92881531,  1.0009845, 0.00750639
    vpl= vo*(rs/_REFR0/ro)**beta*_REFV0
    #3: linear
    vo, ro, dvdr= 0.93050113,  1.00377579, 0.01625223
    vlinear= (vo+dvdr*(rs/_REFR0-1.))*_REFV0
    #4: quadratic
    vo, ro, dvdr, d2vdr2= 0.92954738,  1.00440273, 0.02909439,  0.25129582
    vquadratic= (vo+dvdr*(rs/_REFR0-1.)+d2vdr2*(rs/_REFR0-1.)**2.)*_REFV0
    #5: cubic
    vo, ro, dvdr, d2vdr2, d3vdr3=  0.9416574, 1.01691786, -0.10708624, -0.07733835,  0.42241186
    vcubic= (vo+dvdr*(rs/_REFR0-1.)+d2vdr2*(rs/_REFR0-1.)**2.\
                 +d3vdr3*(rs/_REFR0-1.)**3.)*_REFV0
    #Plot all
    bovy_plot.bovy_print(fig_width=8.)
    bovy_plot.bovy_plot(rs,vflat,'k-',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$V_c\ [\mathrm{km\ s}^{-1}]$',
                        xrange=[0.,20.],
                        yrange=[150.,300.])
    bovy_plot.bovy_plot(rs,vpl,'k--',overplot=True)
    bovy_plot.bovy_plot(rs,vlinear,'k-.',overplot=True)
    bovy_plot.bovy_plot(rs,vquadratic,'k:',overplot=True)
    bovy_plot.bovy_plot(rs,vcubic,'k-.',overplot=True,color='red')
    if _PLOTM31:
        #Read file
        m31data= numpy.loadtxt('../data/m31.dat',comments='#')
        rm31= m31data[:,0]
        vcm31= m31data[:,1]
        bovy_plot.bovy_plot(rm31,vcm31,'ks',overplot=True,mfc='none',mew=2.)
        bovy_plot.bovy_text(17.,260.,r'$\mathrm{M31}$',size=14.)
        indx= (rm31 > 15.2)*(rm31 <= 16.8)
        bovy_plot.bovy_plot([17.,rm31[indx]],[260.,vcm31[indx]],'k-',
                            overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #45
0
def plot_spatial_broad(plotname):
    # Load subsamples, plot
    load_funcs = [
        define_rcsample.get_lowlowsample, define_rcsample.get_highalphasample,
        define_rcsample.get_solarsample, define_rcsample.get_highfehsample
    ]
    names = ['lowlow', 'highalpha', 'solar', 'highfeh']
    labels = [
        r'$\mathrm{low\ [Fe/H]}$', r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
        r'$\mathrm{solar}$', r'$\mathrm{high\ [Fe/H]}$'
    ]
    for ii in range(4):
        data = load_funcs[ii]()
        if ii == 1:
            ylabel = r'$Z\,(\mathrm{kpc})$'
        else:
            ylabel = ' '
        bovy_plot.bovy_print(axes_labelsize=24,
                             text_fontsize=24,
                             xtick_labelsize=24,
                             ytick_labelsize=24)
        bovy_plot.bovy_plot(data['RC_GALR_H'],
                            data['RC_GALZ_H'],
                            'k.',
                            ms=2.,
                            xrange=[0., 16.],
                            yrange=[-3., 3.],
                            xlabel=r'$R\,(\mathrm{kpc})$',
                            ylabel=ylabel,
                            onedhists=True,
                            bins=31)
        if ii != 1:
            bovy_plot.bovy_text(labels[ii], top_left=True, size=24)
        else:
            bovy_plot.bovy_text(labels[ii], bottom_left=True, size=24)
        bovy_plot.bovy_end_print(plotname.replace('SAMPLE', names[ii]))
    return None
예제 #46
0
def plot_data_feh(location=0,
                  plotfilename=os.path.join(OUTDIR, 'data_h_jk.' + OUTEXT)):
    data = readVclosData()
    #Good feh
    data = data[(data['FEH'] != -9999.00)]
    if not location is None:
        if location == 0:
            locs = set(data['LOCATION'])
            for l in locs:
                plot_data_feh(location=l,
                              plotfilename=os.path.join(
                                  OUTDIR, 'data_feh_%i.' % l + OUTEXT))
            return None
        data = data[(data['LOCATION'] == location)]
    meanfeh = numpy.mean(data['FEH'])
    sigfeh = numpy.std(data['FEH'])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data['FEH'],
                        xlabel=r'$[\mathrm{Fe/H}]$',
                        xrange=[meanfeh - 1., meanfeh + 1],
                        bins=16)
    bovy_plot.bovy_text(r'$\sigma = %.2f$' % sigfeh, top_right=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
예제 #47
0
def triangleMAPs(savefilename, basename):
    with open(savefilename, 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples = numpy.array(pickle.load(savefile))
        bf_g15 = numpy.array(pickle.load(savefile))
        samples_g15 = numpy.array(pickle.load(savefile))
        bf_zero = numpy.array(pickle.load(savefile))
        samples_zero = numpy.array(pickle.load(savefile))
    labels = []
    for jj in range(samples.shape[2]):
        labels.append(r"$\mathrm{param}\ %i$" % jj)
    maps = define_rcsample.MAPs()
    for ii, map in enumerate(maps.map()):
        if ii >= len(bf): break
        tfeh = numpy.nanmedian(map['FE_H'])
        tafe = numpy.nanmedian(map[define_rcsample._AFETAG])
        for tbf, tsamples, ext in zip([bf, bf_g15, bf_zero],
                                      [samples, samples_g15, samples_zero],
                                      ['fid', 'g15', 'zero']):
            try:
                triangle.corner(tsamples[ii, ].T,
                                quantiles=[0.16, 0.5, 0.84],
                                labels=labels,
                                show_titles=True,
                                title_args={"fontsize": 12},
                                bins=21)
            except ValueError:
                pass
            else:
                bovy_plot.bovy_text(r'$[\mathrm{{Fe/H}}] = {feh:.1f},$'\
                                        .format(feh=tfeh)+'\n'
                                    +r'$[\alpha/\mathrm{{Fe}}] = {afe:.2f}$'\
                                        .format(afe=tafe),
                                    top_left=True,size=16.)
                bovy_plot.bovy_end_print(basename + "_%i_%s.png" % (ii, ext))
    return None
def plot_mapflare(plotname):
    with open('../mapfits/tribrokenexpflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp = numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexpinvlinflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp_invlin = numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexplinflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples_brexp_lin = numpy.array(pickle.load(savefile))
    plotmaps = [19, 26, 32, 39, 45]
    bovy_plot.bovy_print(fig_width=8., fig_height=9. * 3.99 / 8.98)
    maps = define_rcsample.MAPs()
    cmap = cm.coolwarm
    overplot = False
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        # Create all flaring profiles
        #Rmin= numpy.sort(map['RC_GALR_H'])[int(round(0.005*len(map)))]
        #Rmax= numpy.sort(map['RC_GALR_H'])[numpy.amin([len(map)-1,int(round(0.995*len(map)))])]
        Rs = numpy.linspace(4., 14., 1001)
        samples = samples_brexp[ii, :, ::_SKIP]
        samples_invlin = samples_brexp_invlin[ii, :, ::_SKIP]
        samples_lin = samples_brexp_lin[ii, :, ::_SKIP]
        nsamples = len(samples[0])
        tRs = numpy.tile(Rs, (nsamples, 1)).T
        ldp = numpy.empty((len(Rs), nsamples))
        ldp = samples[1] * numpy.exp(samples[4] * (tRs - densprofiles._R0))
        ldp_invlin= samples_invlin[1]\
            *(1.+samples_invlin[4]*(tRs-densprofiles._R0)*(numpy.exp(1.)-1.))
        ldp_lin= samples_lin[1]\
            /(1.-(tRs-densprofiles._R0)*samples_lin[4]*(numpy.exp(1.)-1.))
        ldp = 1000. / ldp  # make it hz instead of its inverse
        ldp_invlin = 1000. / ldp_invlin
        ldp_lin = 1000. / ldp_lin
        # Label and relative normalization
        tfeh = round(numpy.median(map['FE_H']) * 20.) / 20.
        if tfeh == 0.25: tfeh = 0.3
        if tfeh == -0.0: tfeh = 0.0
        offset = 10.**(-6. * (tfeh + 0.1)) - 0.4
        if tfeh < -0.1: offset /= 1.5
        if tfeh < -0.2: offset /= 1.15
        print ii, tfeh, len(map), offset
        bovy_plot.bovy_plot(
            Rs,
            numpy.median(ldp, axis=1) * offset,
            '-',
            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05),
            lw=2.,
            overplot=overplot,
            ylabel=r'$h_Z\,(\mathrm{pc})\times\mathrm{constant}$',
            xrange=[0., 16.],
            yrange=[10.**2., 10**5.99],
            zorder=10 + ii,
            semilogy=True)
        #skipped because the median for the other profiles are indistinguishable for that with exponential flaring
        """
            pyplot.fill_between(Rs,
                                numpy.median(ldp_lin,axis=1)*offset,
                                numpy.median(ldp_invlin,axis=1)*offset,
                                color='0.65',
                                lw=0.,zorder=ii-1)
        """
        pyplot.fill_between(
            Rs,
            numpy.sort(ldp, axis=1)[:, int(round(_SIGNIF * nsamples))] *
            offset,
            numpy.sort(ldp, axis=1)[:,
                                    int(round(
                                        (1. - _SIGNIF) * nsamples))] * offset,
            color=cmap((tfeh + 0.5) / 0.4),
            lw=0.,
            zorder=ii)
        line, = pyplot.plot(Rs,
                            Rs * 0. + 300. * offset,
                            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05),
                            ls='--',
                            lw=2. * 0.8,
                            zorder=ii + 5)
        line.set_dashes([8, 6])
        overplot = True
        if ii == 19:
            bovy_plot.bovy_text(2.,
                                10.**5.6,
                                r'$[\mathrm{Fe/H}]$',
                                size=16.,
                                color='k')
        bovy_plot.bovy_text(2.,
                            numpy.median(ldp, axis=1)[0] * offset,
                            r'$%+.1f$' % tfeh,
                            size=16.,
                            color=cmap((tfeh + 0.5) * 0.95 / 0.5 + 0.05))
    bovy_plot.bovy_text(10.,
                        10.**5.6,
                        r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
예제 #49
0
plt.subplot(2, 3, 6)
bovy_plot.bovy_plot(numpy.linspace(0., 1., nstep) * nstep * step,
                    numpy.sum(Q, axis=1),
                    lw=3.,
                    loglog=True,
                    xlabel=r'$t$',
                    ylabel=r'$\chi^2$',
                    gcf=True,
                    yrange=[1., 10**7.0])
#gca().yaxis.set_major_formatter(FuncFormatter(
#                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
#gca().xaxis.set_major_formatter(FuncFormatter(
#                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
plt.tight_layout()
if Add_perturbation == True:
    bovy_plot.bovy_end_print('m2m_results_perturbed_mock.jpg')
else:
    bovy_plot.bovy_end_print('m2m_results_stable_mock.jpg')

### Save the results in a file
if Add_perturbation == True:
    savefilename = 'm2m_results_perturbed_mock.sav'
else:
    savefilename = 'm2m_results_stable_mock.sav'
save_pickles(savefilename,w_out,omega_out,xnm_out,z_m2m,vz_m2m,zsun_true,
             vzsun_true,data_dicts,z_mock,vz_mock,v_obs,v_obs_noise, \
             w_init,h_m2m,omega_m2m,xnm_m2m,zsun_m2m,\
             dens_init,v2_init,v_init,\
             h_obs,xnm_true,omegadm_true,totmass_true,zh_true,sigma_true,
             nstep,step,tdyn,skipomega,skipxnm,dttdyn,eps,Q,wevol,windx)
예제 #50
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
예제 #51
0
def snapshotToMovie(snap, filename, *args, **kwargs):
    """
    NAME:

       snapshotToMovie

    PURPOSE:

       turn a list of snapshots into a movie

    INPUT:

       snap - the snapshots (list)

       filename - name of the file to save the movie to

       framerate= in fps

       bitrate= ?
       
       thumbnail=False : create thumbnail image (filename-extension+.jpg)

       thumbsize= size of thumbnail
       
       +Snapshot.plot args and kwargs

    OUTPUT:
    
       movie is saved to file

    DEPENDENCIES:

       this procedure uses ffmpeg and convert

    BUGS:
    
       matplotlib's 'Agg' backend has a memory leak that prevents it from 
       creating hundred's of figures. It is recommended to call
       
       import matplotlib
       matplotlib.use('PDF')

       at the beginning of the movie creating script as the PDF backend does 
       not have the same memory leak.

    HISTORY:

       2011-02-06 - Written - Bovy (NYU)

    """
    if kwargs.has_key('tmpdir'):
        tmpdir = kwargs['tmpdir']
        kwargs.pop('tmpdir')
    else:
        tmpdir = '/tmp'
    if kwargs.has_key('framerate'):
        framerate = kwargs['framerate']
        kwargs.pop('framerate')
    else:
        framerate = 25
    if kwargs.has_key('bitrate'):
        bitrate = kwargs['bitrate']
        kwargs.pop('bitrate')
    else:
        bitrate = 1000
    if kwargs.has_key('thumbnail') and kwargs['thumbnail']:
        thumbnail = True
        kwargs.pop('thumbnail')
    elif kwargs.has_key('thumbnail'):
        kwargs.pop('thumbnail')
        thumbnail = False
    else:
        thumbnail = False
    if kwargs.has_key('thumbsize'):
        thumbsize = kwargs['thumbsize']
    else:
        thumbsize = 300
    #Create all of the files
    tempdir = tempfile.mkdtemp(dir=tmpdir)  #Temporary directory
    tmpfiles = []
    nsnap = len(snap)
    file_length = int(m.ceil(m.log10(nsnap)))
    #Determine good xrange BOVY TO DO
    if not kwargs.has_key('xrange'):
        pass
    if not kwargs.has_key('yrange'):
        pass
    for ii in range(nsnap):
        tmpfiles.append(os.path.join(tempdir, str(ii).zfill(file_length)))
        bovy_plot.bovy_print()
        snap[ii].plot(*args, **kwargs)
        bovy_plot.bovy_end_print(tmpfiles[ii] + '.pdf')
        #Convert to jpeg
        try:
            subprocess.check_call(
                ['convert', tmpfiles[ii] + '.pdf', tmpfiles[ii] + '.jpg'])
        except subprocess.CalledProcessError:
            print("'convert' failed")
            raise subprocess.CalledProcessError
    #turn them into a movie
    try:
        subprocess.check_call([
            'ffmpeg', '-r',
            str(framerate), '-b',
            str(bitrate), '-i',
            os.path.join(tempdir, '%' + '0%id.jpg' % file_length), '-y',
            filename
        ])
        if thumbnail:
            thumbnameTemp = re.split(r'\.', filename)
            thumbnameTemp = thumbnameTemp[0:len(thumbnameTemp) - 1]
            thumbname = ''
            for t in thumbnameTemp:
                thumbname += t
            thumbname += '.jpg'
            subprocess.check_call([
                'ffmpeg', '-itsoffset', '-4', '-y', '-i', filename, '-vcodec',
                'mjpeg', '-vframes', '1', '-an', '-f', 'rawvideo', '-s',
                '%ix%i' % (thumbsize, thumbsize), thumbname
            ])
    except subprocess.CalledProcessError:
        print("'ffmpeg' failed")
        _cleanupMovieTempdir(tempdir)
        raise subprocess.CalledProcessError
    finally:
        _cleanupMovieTempdir(tempdir)
예제 #52
0
def singleBandSampleExample(
        datafilename='../data/SDSSJ203817.37+003029.8.fits',
        band='g',
        nsamples=1000,
        basefilename='SDSSJ203817.37+003029.8'):
    """
    NAME:
       singleBandSampleExample
    PURPOSE:
       Sample an example of a power-law structure function GP covariance 
       function to an SDSS quasar
    INPUT:
       datafilename
       band - band to fit
       nsamples - number of samples to use
       basefilename
    OUTPUT:
    HISTORY:
       2010-08-08 - Written - Bovy (NYU)
    """
    nu.random.seed(1)
    #Get data
    file = fu.table_fields(datafilename)
    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)
    mjd_r = nu.array(file.mjd_r) / 365.25
    r = nu.array(file.r)
    err_r = nu.array(file.err_r)
    mjd_i = nu.array(file.mjd_i) / 365.25
    i = nu.array(file.i)
    err_i = nu.array(file.err_i)

    mask = (mjd_g != 0) * (g < 20.6) * (g > 19.7)
    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)

    i = i[mask]
    i -= nu.mean(i)
    err_i = err_i[mask]
    mjd_i = mjd_i[mask]
    mjd_i -= nu.amin(mjd_i)
    meanErr_i = nu.mean(err_i)

    savefilename = basefilename + '.sav'
    if os.path.exists(savefilename):
        savefile = open(savefilename, 'rb')
        gammas = pickle.load(savefile)
        if 'gr' in basefilename:
            logGammas = pickle.load(savefile)
            gammagrs = pickle.load(savefile)
            logGammagrs = pickle.load(savefile)
        else:
            logAs = pickle.load(savefile)
        out = pickle.load(savefile)
        savefile.close()
    else:
        if 'gri' in basefilename:
            raise NotImplementedError
            from powerlawSFgr import covarFunc
            params = {
                'logGamma': array([-7.79009776]),
                'logGammagr': array([-28.0487848]),
                'gamma': array([0.45918053]),
                'gammagr': array([0.21333858])
            }
            SF = covarFunc(**params)
            listx = [(t, 'g') for t in mjd_g]
            listx.extend([(t, 'r') for t in mjd_r])
            listx.extend([(t, 'i') for t in mjd_i])
            listy = [m for m in g]
            listy.extend([m for m in r])
            listy.extend([m for m in i])
            listy = nu.array(listy)
            noise = [m for m in err_g]
            noise.extend([m for m in err_r])
            noise.extend([m for m in err_i])
            noise = nu.array(noise)
            trainSet = trainingSet(listx=listx, listy=listy, noise=noise)
        elif 'gr' in basefilename:
            raise NotImplementedError
            from powerlawSFgr import covarFunc
            params = {
                'logGamma': array([-7.79009776]),
                'logGammagr': array([-28.0487848]),
                'gamma': array([0.45918053]),
                'gammagr': array([0.21333858])
            }
            SF = covarFunc(**params)
            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)
        else:
            from gp.powerlawSF import covarFunc
            trainSet = trainingSet(listx=mjd_g, listy=g, noise=err_g)
            params = [0., 0.]
            SF = covarFunc(gamma=.2, A=0.000524)  #Power
            #SF= covarFunc(a=.0001,l=.001) #OU

        #Train
        print "Training ..."
        outcovarFunc = trainGP(trainSet, SF, useDerivs=False)

        print "Best-fit:"
        print outcovarFunc._dict

        print "Sampling ..."
        out = sampleGP(trainSet,
                       outcovarFunc,
                       nsamples=nsamples,
                       step=[0.2 for ii in range(len(params))])

        gammas = nu.array([o._dict['gamma'] for o in out]).reshape(len(out))
        if 'gr' in basefilename:
            gammagrs = nu.array([o._dict['gammagr']
                                 for o in out]).reshape(len(out))
            logGammas = nu.array([o._dict['logGamma']
                                  for o in out]).reshape(len(out))
            logGammagrs = nu.array([o._dict['logGammagr']
                                    for o in out]).reshape(len(out))
        else:
            logAs = nu.array([o._dict['logA'] for o in out]).reshape(len(out))
            print nu.mean(logAs), nu.sqrt(nu.var(logAs))
        print nu.mean(gammas), nu.sqrt(nu.var(gammas))

        #Save
        savefile = open(savefilename, 'wb')
        pickle.dump(gammas, savefile)
        if 'gr' in basefilename:
            pickle.dump(logGammas, savefile)
            pickle.dump(gammagrs, savefile)
            pickle.dump(logGammagrs, savefile)
        else:
            pickle.dump(logAs, savefile)
        pickle.dump(out, savefile)
        savefile.close()

    #if not 'gr' in basefilename:
    #    logGammas= logAs/gammas

    #Plot
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(logAs / 2.,
                          gammas,
                          'k,',
                          ylabel=r'$\gamma$',
                          xlabel=r'\log A',
                          xrange=[-9.21 / 2., 0.],
                          yrange=[0., 1.25],
                          bins=50,
                          onedhists=True)
    bovy_plot.bovy_end_print(basefilename + '_sample_2d.png')
예제 #53
0
def plot_mapsurfdens(plotname):
    with open('../mapfits/tribrokenexpflare.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples_brexp= numpy.array(pickle.load(savefile))
    plotmaps= [19,26,32,39,45]
    bovy_plot.bovy_print(fig_width=8.,fig_height=3.)
    maps= define_rcsample.MAPs()
    cmap= cm.coolwarm
    overplot= False
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        # Create all density profiles
        Rs= numpy.linspace(4.,14.,1001)
        samples= samples_brexp[ii,:,::_SKIP]
        nsamples= len(samples[0])
        tRs= numpy.tile(Rs,(nsamples,1)).T
        ldp= numpy.empty((len(Rs),nsamples))
        Rb= numpy.tile(numpy.exp(samples[3]),(len(Rs),1))
        ihRin= numpy.tile(samples[0],(len(Rs),1))
        ihRout= numpy.tile(samples[2],(len(Rs),1))
        # Rb >= R0
        leRb= (tRs <= Rb)*(Rb >= densprofiles._R0)
        ldp[leRb]= ihRin[leRb]*(tRs[leRb]-densprofiles._R0)
        gtRb= (tRs > Rb)*(Rb >= densprofiles._R0)
        ldp[gtRb]= -ihRout[gtRb]*(tRs[gtRb]-densprofiles._R0)\
            +ihRout[gtRb]*(Rb[gtRb]-densprofiles._R0)\
            +ihRin[gtRb]*(Rb[gtRb]-densprofiles._R0)
        # Rb < R0, normalize outer at R0
        leRb= (tRs <= Rb)*(Rb < densprofiles._R0)
        ldp[leRb]= ihRin[leRb]*(tRs[leRb]-densprofiles._R0)\
            -ihRout[leRb]*(Rb[leRb]-densprofiles._R0)\
            -ihRin[leRb]*(Rb[leRb]-densprofiles._R0)
        gtRb= (tRs > Rb)*(Rb < densprofiles._R0)
        ldp[gtRb]= -ihRout[gtRb]*(tRs[gtRb]-densprofiles._R0)
        # Label and relative normalization
        tfeh= round(numpy.median(map['FE_H'])*20.)/20.
        if tfeh == 0.25: tfeh= 0.3
        if tfeh == -0.1: tfeh= -0.1
        print ii, tfeh, len(map)
        anorm= 10**(-10.*(-tfeh-0.5))
        #if (-tfeh-0.4) > 0.3: anorm= 10**(-12.*(-tfeh+0.4)) 
        if (-tfeh-0.5) == -0.2: anorm= 10**(-11.*(-tfeh-0.5))
        anorm= 1./anorm # re-order
        anorm/= 3.
        norm= numpy.exp(numpy.median(ldp,axis=1))[numpy.argmin(numpy.fabs(Rs-densprofiles._R0))]/anorm
        bovy_plot.bovy_plot(Rs,numpy.exp(numpy.median(ldp,axis=1))/norm,
                            '-',
                            color=cmap((tfeh+0.5)*0.95/0.5+0.05),
                            lw=2.,overplot=overplot,
                            ylabel=r'$\Sigma(R)\times\mathrm{constant}$',
                            xrange=[0.,16.],
                            yrange=[0.000001,90.],
                            semilogy=True)
        pyplot.fill_between(Rs,
                            numpy.exp(numpy.sort(ldp,axis=1)[:,int(round(_SIGNIF*nsamples))])/norm,
                            numpy.exp(numpy.sort(ldp,axis=1)[:,int(round((1.-_SIGNIF)*nsamples))])/norm,
                            color=cmap((tfeh+0.5)/0.4),
                            lw=0.)
        overplot= True
        if ii == 19:
            bovy_plot.bovy_text(2.,
                                10.**1.,
                                r'$[\mathrm{Fe/H}]$',size=16.,color='k')
        bovy_plot.bovy_text(2.,(numpy.exp(numpy.median(ldp,axis=1))/norm)[0],
                            r'$%+.1f$' % tfeh,size=16.,
                            color=cmap((tfeh+0.5)*0.95/0.5+0.05))
    bovy_plot.bovy_text(10.,10.**1.,
                        r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                        size=16.)
    pyplot.gca().tick_params(axis='y',which='minor',left='off',right='off')
    bovy_plot.bovy_end_print(plotname)
예제 #54
0
def plot_vpecvo(filename, plotfilename):
    if not os.path.exists(filename):
        raise IOError("given filename does not exist")
    savefile = open(filename, 'rb')
    params = pickle.load(savefile)
    savefile.close()
    vos = numpy.array([s[0] for s in params]) * _REFV0
    ros = numpy.array([s[1] for s in params]) * _REFR0
    if _ROTCURVE == 'flat':
        vpec = numpy.array([s[7] for s in params
                            ]) * _PMSGRA * ros - vos  #7 w/ dwarf
        vpecR = numpy.array([s[6] for s in params]) * _VRSUN  #6 w/ dwarf
    elif _ROTCURVE == 'powerlaw' or _ROTCURVE == 'linear':
        vpec = numpy.array([s[8] for s in params
                            ]) * _PMSGRA * ros - vos  #7 w/ dwarf
        vpecR = numpy.array([s[7] for s in params]) * _VRSUN  #6 w/ dwarf
    bovy_plot.bovy_print()
    levels = list(special.erf(0.5 * numpy.arange(1, 4)))
    levels.append(1.01)  #HACK to not plot outliers
    axScatter, axHistx, axHisty = bovy_plot.scatterplot(
        vpecR,  #vos/ros+vpec/ros,
        vpec,
        'k,',
        levels=levels,
        xlabel=r'$V_{R,\odot}\ [\mathrm{km\ s}^{-1}]$',
        ylabel=r'$V_{\phi,\odot}-V_c\ [\mathrm{km\ s}^{-1}]$',
        bins=31,
        xrange=[-15., 0.],
        yrange=[0., 35.],
        contours=True,
        cntrcolors='k',
        onedhists=True,
        cmap='gist_yarg',
        retAxes=True)
    #SBD10 value
    bovy_plot.bovy_plot([-20., 40.], [12.24, 12.24],
                        '--',
                        color='0.5',
                        overplot=True)
    bovy_plot.bovy_text(-4., 12.7, r'$\mathrm{SBD10}$')
    axHisty.plot([0., 100.], [12.24, 12.24], '--', color='0.5')
    bovy_plot.bovy_plot([_VRSUN, _VRSUN], [-100., 100.],
                        '--',
                        color='0.5',
                        overplot=True)
    bovy_plot.bovy_text(_VRSUN - .75, 7., r'$\mathrm{SBD10}$', rotation=90.)
    axHistx.plot([_VRSUN, _VRSUN], [0., 100.], '--', color='0.5')
    #Reid / Brunthaler
    #bovy_plot.bovy_plot([_PMSGRA,_PMSGRA],[-10.,100.],
    #                    '--',color='0.5',overplot=True)
    #axHistx.plot([_PMSGRA,_PMSGRA],[0.,100.],'--',color='0.5')
    #bovy_plot.bovy_text(29.4,5.,r'$\mathrm{RB04}$')

    #Inset, closed orbit at the Sun
    lp = LogarithmicHaloPotential(normalize=1.)
    ep = EllipticalDiskPotential(phib=numpy.pi / 2.,
                                 p=0.,
                                 tform=-100.,
                                 tsteady=-100.,
                                 twophio=14. / 220.)  #0.072725)
    o = Orbit([1., 0., 1. + 14. / 220., 0.])
    oc = Orbit([1., 0., 1., 0.])
    ts = numpy.linspace(0., 4. * numpy.pi, 1001)
    o.integrate(ts, [lp, ep])
    print o.e(analytic=True, pot=lp)
    oc.integrate(ts, lp)
    left, bottom, width, height = 0.45, 0.45, 0.25, 0.25
    axInset = pyplot.axes([left, bottom, width, height])
    pyplot.sca(axInset)
    pyplot.plot(o._orb.orbit[:, 0] * numpy.cos(o._orb.orbit[:, 3]),
                o._orb.orbit[:, 0] * numpy.sin(o._orb.orbit[:, 3]), 'k-')
    pyplot.plot(oc._orb.orbit[:, 0] * numpy.cos(oc._orb.orbit[:, 3]),
                oc._orb.orbit[:, 0] * numpy.sin(oc._orb.orbit[:, 3]),
                '--',
                color='0.6')
    pyplot.xlim(-1.5, 1.5)
    pyplot.ylim(-1.5, 1.5)
    #pyplot.xlabel(r'$x / R_0$')
    #pyplot.ylabel(r'$y / R_0$')
    nullfmt = NullFormatter()  # no labels
    axInset.xaxis.set_major_formatter(nullfmt)
    axInset.yaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotfilename)
예제 #55
0
def test_windows(options):
    elems = [
        'C', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'S', 'K', 'Ca', 'Ti', 'V', 'Mn',
        'Fe', 'Ni', 'Ce', 'Co', 'Cr', 'Cu', 'Ge', 'Nd', 'P', 'Rb', 'Y'
    ]
    if options.savefilename is None or \
            not os.path.exists(options.savefilename):
        # Set default linelist for Turbospectrum or MOOG
        if options.linelist is None and options.moog:
            linelist = 'moog.201312161124.vac'
        elif options.linelist is None:
            linelist = 'turbospec.201312161124'
        else:
            linelist = options.linelist
        # set up a model atmosphere for the requested atmospheric parameters
        if options.arcturus:
            options.teff = 4286.
            options.logg = 1.66
            options.metals = -0.52
            options.am = 0.4
            options.cm = 0.09
            options.vm = 1.7
        atm = atlas9.Atlas9Atmosphere(teff=options.teff,
                                      logg=options.logg,
                                      metals=options.metals,
                                      am=options.am,
                                      cm=options.cm)
        # create baseline
        if options.moog:
            baseline= \
                apogee.modelspec.moog.synth(modelatm=atm,
                                            linelist=linelist,
                                            lsf='all',cont='aspcap',
                                            vmacro=6.,isotopes='arcturus',
                                            vmicro=options.vm)
        else:
            baseline= \
                apogee.modelspec.turbospec.synth(modelatm=atm,
                                                 linelist=linelist,
                                                 lsf='all',cont='aspcap',
                                                 vmacro=6.,isotopes='arcturus',
                                                 vmicro=options.vm)
        # Loop through elements
        elem_synspec = {}
        # Run through once to simulate all differences
        for elem in elems:
            # First check that this element has windows
            elemPath = apwindow.path(elem, dr=options.dr)
            if not os.path.exists(elemPath): continue
            # Simulate deltaAbu up and down
            print "Working on %s" % (elem.capitalize())
            abu = [atomic_number(elem), -options.deltaAbu, options.deltaAbu]
            if options.moog:
                synspec= \
                    apogee.modelspec.moog.synth(abu,
                                                modelatm=atm,
                                                linelist=linelist,
                                                lsf='all',cont='aspcap',
                                                vmacro=6.,
                                                isotopes='arcturus',
                                                vmicro=options.vm)
            else:
                synspec= \
                    apogee.modelspec.turbospec.synth(abu,
                                                     modelatm=atm,
                                                     linelist=linelist,
                                                     lsf='all',cont='aspcap',
                                                     vmacro=6.,
                                                     isotopes='arcturus',
                                                     vmicro=options.vm)
            elem_synspec[elem] = synspec
        if not options.savefilename is None:
            save_pickles(options.savefilename, baseline, elem_synspec)
    else:
        with open(options.savefilename, 'rb') as savefile:
            baseline = pickle.load(savefile)
            elem_synspec = pickle.load(savefile)
    # Now run through the different elements again and plot windows for each
    # with elements that vary significantly
    colors = sns.color_palette("colorblind")
    plotelems = [
        elem if not elem in ['C', 'N', 'O', 'Fe'] else '%s1' % elem
        for elem in elems
    ]
    plotelems.extend(['C2', 'N2', 'O2', 'Fe2'])
    for pelem in plotelems:
        if '1' in pelem or '2' in pelem: elem = pelem[:-1]
        else: elem = pelem
        if not elem in elem_synspec: continue
        # Figure out which elements have significant variations in these
        # windows and always plot the element that should vary
        elemIndx = apwindow.tophat(elem, dr=options.dr)
        elemWeights = apwindow.read(elem, dr=options.dr)
        elemWeights /= numpy.nansum(elemWeights)
        # Start with the element in question
        splot.windows(1. + options.amplify *
                      (elem_synspec[elem][0] - baseline[0]),
                      pelem,
                      color=colors[0],
                      yrange=[0., 1.4],
                      plot_weights=True,
                      zorder=len(elems))
        splot.windows(1. + options.amplify *
                      (elem_synspec[elem][1] - baseline[0]),
                      pelem,
                      color=colors[0],
                      overplot=True,
                      zorder=len(elems))
        elem_shown = [elem]
        # Run through the rest to figure out the order
        elemVar = numpy.zeros(len(elems))
        for ii, altElem in enumerate(elems):
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            elemVar[ii] = 0.5 * numpy.nansum(
                (elem_synspec[altElem][0] - baseline[0])**2. * elemWeights)
            elemVar[ii] += 0.5 * numpy.nansum(
                (elem_synspec[altElem][1] - baseline[0])**2. * elemWeights)
        jj = 0
        sortindx = numpy.argsort(elemVar)[::-1]
        for altElem in numpy.array(elems)[sortindx]:
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            if numpy.fabs(\
                numpy.nanmax([(elem_synspec[altElem][0]-baseline[0])[elemIndx],
                            (elem_synspec[altElem][1]-baseline[0])[elemIndx]]))\
                            > options.varthreshold:
                jj += 1
                if jj >= len(colors): jj = len(colors) - 1
                elem_shown.append(altElem)
                splot.windows(1. + options.amplify *
                              (elem_synspec[altElem][0] - baseline[0]),
                              pelem,
                              color=colors[jj],
                              overplot=True,
                              zorder=len(elems) - jj)
                splot.windows(1. + options.amplify *
                              (elem_synspec[altElem][1] - baseline[0]),
                              pelem,
                              color=colors[jj],
                              overplot=True,
                              zorder=len(elems) - jj)
        t = pyplot.gca().transData
        fig = pyplot.gcf()
        for s, c in zip(elem_shown, colors[:jj + 1]):
            xc = 0.05
            if elem == 'K' or elem == 'Ce' or elem == 'Ge' or elem == 'Nd' \
                    or elem == 'Rb':
                xc = apwindow.waveregions(elem, dr=options.dr,
                                          pad=3)[0][0] - 15000. + 1.
            text = pyplot.text(xc,
                               1.2,
                               " " + (r"$\mathrm{%s}$" % s) + " ",
                               color=c,
                               transform=t,
                               size=16.,
                               backgroundcolor='w')
            text.draw(fig.canvas.get_renderer())
            ex = text.get_window_extent()
            t = transforms.offset_copy(text._transform,
                                       x=1.5 * ex.width,
                                       units='dots')
        # Save
        bovy_plot.bovy_end_print(options.plotfilename.replace('ELEM', pelem))
    return None
예제 #56
0
def plot_rotcurve_samples(options=None, args=None):
    """Plot sample rotation curves"""
    options = set_options(options)
    params = numpy.random.permutation(load_samples(args[0]))
    rotcurves = []
    rs = numpy.linspace(3.5, 16., 1001)
    add = 0
    if options.nooutliermean: add -= 1
    if not options.dwarf: add -= 1
    for ii in range(options.nsamples):
        if options.rotcurve.lower() == 'flat':
            thisrc = params[ii][0] * rs**0. * _REFV0
        elif options.rotcurve.lower() == 'powerlaw':
            thisrc = params[ii][0] * (
                rs / _REFR0 / params[ii][1])**params[ii][6 + add] * _REFV0
        elif options.rotcurve.lower() == 'linear':
            thisrc = (params[ii][0] + params[ii][6 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.)) * _REFV0
        elif options.rotcurve.lower() == 'quadratic':
            thisrc = (params[ii][0] + params[ii][6 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.) +
                      params[ii][7 + add] *
                      (rs / _REFR0 / params[ii][1] - 1)**2.) * _REFV0
        elif options.rotcurve.lower() == 'cubic':
            thisrc = (params[ii][0] + params[ii][6 + add] *
                      (rs / _REFR0 / params[ii][1] - 1) + params[ii][7 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.)**2. +
                      params[ii][8 + add] *
                      (rs / _REFR0 / params[ii][1] - 1.)**3.) * _REFV0
        rotcurves.append(thisrc)
    bovy_plot.bovy_print(fig_width=8.)
    ii = 0
    bovy_plot.bovy_plot(rs,
                        rotcurves[ii],
                        '-',
                        color='0.65',
                        xlabel=r'$R\ [\mathrm{kpc}]$',
                        ylabel=r'$V_c\ [\mathrm{km\ s}^{-1}]$',
                        xrange=[0., 20.],
                        yrange=[150., 300.])
    for ii in range(1, options.nsamples):
        bovy_plot.bovy_plot(rs,
                            rotcurves[ii],
                            '-',
                            color='0.65',
                            overplot=True,
                            alpha=0.1)
    if _PLOTM31:
        #Read file
        m31data = numpy.loadtxt('../data/m31.dat', comments='#')
        rm31 = m31data[:, 0]
        vcm31 = m31data[:, 1]
        bovy_plot.bovy_plot(rm31,
                            vcm31,
                            'ks',
                            overplot=True,
                            mfc='none',
                            mew=2.)
        bovy_plot.bovy_text(17., 260., r'$\mathrm{M31}$', size=14.)
        indx = (rm31 > 15.2) * (rm31 <= 16.8)
        bovy_plot.bovy_plot([17., rm31[indx]], [260., vcm31[indx]],
                            'k-',
                            overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
예제 #57
0
plt.subplot(2,3,3)
bovy_plot.bovy_plot(numpy.linspace(0.,1.,nstep)*nstep*step,xnm_out,'-',
                    color=sns.color_palette()[0],
                    yrange=[0.,xnm_m2m*2.0],
                    semilogx=True,xlabel=r'$\mathrm{orbits}$',ylabel=r'$X_{nm}(t)$',gcf=True)
# axhline(xnm_true,ls='--',color='0.65',lw=2.,zorder=0)
#gca().xaxis.set_major_formatter(FuncFormatter(
#                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
# for ii in range(len(wevol)):
#    bovy_plot.bovy_plot(numpy.linspace(0.,1.,nstep)*nstep*step,wevol[ii,0],'-',
#                        color=cm.viridis(z_m2m[windx][ii]/0.3),
#                        yrange=[-0.2/len(z_m2m),numpy.amax(wevol)*1.1],
#                        semilogx=True,xlabel=r'$t$',ylabel=r'$w(t)$',gcf=True,overplot=ii>0)
#gca().xaxis.set_major_formatter(FuncFormatter(
#                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))

# Xi^2
plt.subplot(2,3,6)
bovy_plot.bovy_plot(numpy.linspace(0.,1.,nstep)*nstep*step,numpy.sum(Q,axis=1),lw=3.,
                   loglog=True,xlabel=r'$t$',ylabel=r'$\chi^2$',gcf=True,
                   yrange=[1.,10**7.0])
#gca().yaxis.set_major_formatter(FuncFormatter(
#                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
#gca().xaxis.set_major_formatter(FuncFormatter(
#                lambda y,pos: (r'${{:.{:1d}f}}$'.format(int(numpy.maximum(-numpy.log10(y),0)))).format(y)))
plt.tight_layout()
bovy_plot.bovy_end_print('m2m_results.jpg')



예제 #58
0
def plot_distanceintegral_fewfields(savename, plotname, apogee=False):
    #ls and bs of the patches
    ls = [280., 30., 12., 37.5, 90., 127.5, 30., 60., 20., -20., -40.]
    bs = [45., 4., 2., 0., 0., 0., 0., 0., 0., 0., 0.]
    radius = 1.49
    locs = [4214, 4244, 4378, 4312, 4242, 4318, 4240, 4241]  # for apogee
    # If we are doing APOGEE selection, load the APOGEE selection function
    if apogee:
        selectFile = '../savs/selfunc-nospdata.sav'
        if os.path.exists(selectFile):
            with open(selectFile, 'rb') as savefile:
                apo = pickle.load(savefile)
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
            if apogee:
                area_cdens = pickle.load(savefile)
    else:
        if not apogee:
            # For samping over the absolute magnitude distribution
            iso = gaia_rc.load_iso()
            Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # Loop through each distance slice
        area = numpy.zeros((len(ls), len(dust._GREEN15DISTS)))
        if apogee:
            area_cdens = numpy.zeros((len(ls), len(dust._GREEN15DISTS)))
        for ii, dist in enumerate(dust._GREEN15DISTS):
            print "Working on distance %i: %f" % (ii, dist)
            G0 = 0.68 + dust.dist2distmod(dist)
            H0 = -1.49 + dust.dist2distmod(dist)
            # Load the dust map
            combinedmap = dust.load_combined(dist,
                                             nest=False,
                                             nside_out=_NSIDE)
            # Loop through a few patches
            theta, phi = healpy.pixelfunc.pix2ang(
                _NSIDE,
                numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                nest=False)
            cosb = numpy.sin(theta)
            for ff, (ll, bb) in enumerate(zip(ls, bs)):
                if ff >= len(ls) - 3 * apogee: break
                vec = healpy.pixelfunc.ang2vec((90. - bb) * _DEGTORAD,
                                               ll * _DEGTORAD)
                ipixs = healpy.query_disc(_NSIDE,
                                          vec,
                                          radius * _DEGTORAD,
                                          inclusive=False,
                                          nest=False)
                ipixIndx = numpy.in1d(numpy.arange(
                    healpy.pixelfunc.nside2npix(_NSIDE)),
                                      ipixs,
                                      assume_unique=True)
                # Calculate the density
                densmap = densprofiles.expdisk(phi[ipixIndx],
                                               numpy.pi / 2. - theta[ipixIndx],
                                               dist * numpy.ones(len(ipixs)),
                                               glon=True,
                                               params=[1. / 3., 1. / 0.3])
                combinedmask = numpy.zeros(len(ipixs))
                tcombinedmap = combinedmap[ipixIndx]
                if apogee:
                    # Loop through the three cohorts
                    for c in ['short', 'medium', 'long']:
                        hmin = apo.Hmin(locs[ff], cohort=c)
                        hmax = apo.Hmax(locs[ff], cohort=c)
                        combinedmask+= ((tcombinedmap > (hmin-H0))\
                                            *(tcombinedmap < (hmax-H0))).astype('float')*apo(locs[ff],hmin+0.01)
                else:
                    for jj in range(_NGSAMPLES):
                        combinedmask+= ((tcombinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                            *(tcombinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
                combinedmask /= _NGSAMPLES
                # Compute cross correlation
                area[ff,ii]= float(numpy.sum(cosb[ipixIndx]*densmap\
                                                 *combinedmask))
                if apogee:
                    # Also store the approximation that the density is constant
                    cdens = densprofiles.expdisk(ll * _DEGTORAD,
                                                 bb * _DEGTORAD,
                                                 dist,
                                                 glon=True,
                                                 params=[1. / 3., 1. / 0.3])
                    area_cdens[ff,ii]= float(numpy.sum(cosb[ipixIndx]*cdens\
                                                           *combinedmask))
        if apogee:
            save_pickles(savename, area, area_cdens)
        else:
            save_pickles(savename, area)
    # Plot the power spectrum
    if True:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        colors = [
            'b', 'g', 'r', 'c', 'gold', 'm', 'k', 'orange', 'y', 'b', 'g'
        ]
        lss = ['-', '-', '-', '-', '-', '-', '-', '-', '-', '--', '--']
        for ff in range(len(ls)):
            if ff >= len(ls) - 3 * apogee: break
            psdx, psd = signal.periodogram(
                area[ff] * dust._GREEN15DISTS**3. /
                numpy.sum(area[ff] * dust._GREEN15DISTS**3.),
                fs=1. / (dust._GREEN15DISTMODS[1] - dust._GREEN15DISTMODS[0]),
                detrend=lambda x: x,
                scaling='spectrum')
            bovy_plot.bovy_plot(psdx[1:],
                                psd[1:],
                                '-',
                                loglog=True,
                                xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                                ylabel=r'$P_k$',
                                xrange=[0.04, 4.],
                                color=colors[ff],
                                ls=lss[ff],
                                overplot=ff > 0)
            if ff == 0:
                bovy_plot.bovy_text(
                    r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
                    bottom_left=True,
                    size=16.)
        bovy_plot.bovy_end_print(plotname)
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        for ff in range(len(ls)):
            if ff >= len(ls) - 3 * apogee: break
            bovy_plot.bovy_plot(
                dust._GREEN15DISTMODS,
                area[ff] * dust._GREEN15DISTS**3.,
                'k-',
                xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
                ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    for ff in range(len(ls)):
        if ff >= len(ls) - 3 * apogee: break
        spl = interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                       area[ff] *
                                                       dust._GREEN15DISTS**3.,
                                                       k=5)
        fthder = [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
        print "Simpson error (%f,%f)= %g, volume = %g" % (
            ls[ff], bs[ff], 0.5**4. / 180. * numpy.mean(numpy.fabs(fthder)) /
            integrate.simps(area[ff] * dust._GREEN15DISTS**3., dx=0.5),
            numpy.sum(area[ff] * dust._GREEN15DISTS**3.))
    return None
예제 #59
0
def plotFits(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    params = []
    for filename in args:
        if os.path.exists(filename):
            savefile = open(filename, 'rb')
            if options.kmeansOut:
                thisparams = pickle.load(savefile)
                thisDict = {}
                for kk in range(len(thisparams)):
                    thisDict[str(kk)] = thisparams[kk]
                params.append(thisDict)
            else:
                params.append(pickle.load(savefile))
            savefile.close()
        else:
            print filename + " does not exist ..."
            print "Returning ..."
            return
    if options.plottype == 'Ag':
        ys = nu.array([p['gamma']
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logA'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [0., 1.25]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'As':
        ys = nu.array([p['s'] - 1.
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logA'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [-0.9, 0.4]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$s_{' + options.band + r'}$'
    if options.plottype == 'gs':
        ys = nu.array([p['s'] - 1.
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = nu.array([p['gamma'] for p in params[0].values()]).reshape(
            len(params[0])) / 2.
        xrange = [0., 1.2]
        yrange = [-0.9, 0.4]
        xlabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power-law\ index)}$'
        ylabel = r'$s_{' + options.band + r'}$'
    elif options.plottype == 'AA':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['logA'] / 2.)
                xs.append(params[0][key]['logA'] / 2.)
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [-9.21 / 2., 0.]
        yrange = xrange
        xlabel = r'$\log A_' + options.band[
            0] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A_' + options.band[
            1] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabelnounits = r'$\log A_' + options.band[0] + r'$'
        ylabelnounits = r'$\log A_' + options.band[1] + r'$'
    elif options.plottype == 'AAz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xtmp = qsos[qsoDict[key]].z
            except KeyError:
                continue
            try:
                ytmp = params[1][key]['logA'] / 2.
            except KeyError:
                continue
            ys.append(params[0][key]['logA'] / 2 - ytmp)
            xs.append(xtmp)
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        yrange = [-1., 1.]
        xrange = [0., 5.5]
        ylabel = r'$\log A_r/A_g\ \mathrm{(amplitudes\ at\ 1\ yr)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'gg':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['gamma'])
                xs.append(params[0][key]['gamma'])
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [0., 1.15]
        yrange = xrange
        xlabel = r'$\gamma_' + options.band[
            0] + r'\ \mathrm{(power\ law\ exponent)}$'
        ylabel = r'$\gamma_' + options.band[
            1] + r'\ \mathrm{(power\ law\ exponent)}$'
        xlabelnounits = r'$\gamma_' + options.band[0] + r'$'
        ylabelnounits = r'$\gamma_' + options.band[1] + r'$'
    elif options.plottype == 'Acgc':
        ys = nu.array([p['gammagr']
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logAgr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [0., 1.25]
        xlabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'Acg':
        ys = nu.array([p['gamma']
                       for p in params[0].values()]).reshape(len(params[0]))
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logAgr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [0., 1.25]
        xlabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'AcAc':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['logAgr'] / 2.)
                xs.append(params[0][key]['logAgr'] / 2.)
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [-9.21 / 2., 0.]
        yrange = xrange
        xlabel = r'$\log A^c_' + options.band[
            0] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^c_' + options.band[
            1] + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabelnounits = r'$\log A^c_' + options.band[0] + r'$'
        ylabelnounits = r'$\log A^c_' + options.band[1] + r'$'
    elif options.plottype == 'gcgc':
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                ys.append(params[1][key]['gammagr'])
                xs.append(params[0][key]['gammagr'])
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        xrange = [0., 1.15]
        yrange = xrange
        xlabel = r'$\gamma^c_' + options.band[
            0] + r'\ \mathrm{(power\ law\ exponent)}$'
        ylabel = r'$\gamma^c_' + options.band[
            1] + r'\ \mathrm{(power\ law\ exponent)}$'
        xlabelnounits = r'$\gamma^c_' + options.band[0] + r'$'
        ylabelnounits = r'$\gamma^c_' + options.band[1] + r'$'
    elif options.plottype == 'AAc':
        if options.type == 'powerlawSFratios':
            xs = nu.array([p['logAr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
            ys = nu.array([p['logAri'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        else:
            xs = nu.array([p['logA'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
            ys = nu.array([p['logAgr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [-9.21 / 2., 0.]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
    elif options.plottype == 'ggc':
        if len(params) == 2:
            xs, ys = [], []
            for key in params[0].keys():
                try:
                    ys.append(params[1][key]['gammagr'])
                    xs.append(params[0][key]['gamma'])
                except KeyError:
                    continue
            xs = nu.array(xs).reshape(len(xs))
            ys = nu.array(ys).reshape(len(ys))
        else:
            xs = nu.array([p['gamma'] for p in params[0].values()
                           ]).reshape(len(params[0]))
            ys = nu.array([p['gammagr'] for p in params[0].values()]).reshape(
                len(params[0])) / 2.
        xrange = [0., 1.25]
        yrange = xrange
        xlabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
    elif options.plottype == 'Ai':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].mags[3])
            except KeyError:
                continue
            if options.type == 'powerlawSFratios':
                ys.append(params[0][key]['logAr'])
            else:
                ys.append(params[0][key]['logA'])
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [15.0, 21.3]
        ylabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'gi':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gamma'])
            xs.append(qsos[qsoDict[key]].mags[3])
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [15.0, 21.3]
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'Az':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].z)
            except KeyError:
                continue
            if options.type == 'powerlawSFratios':
                ys.append(params[0][key]['logAr'])
            else:
                ys.append(params[0][key]['logA'])
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [0., 5.5]
        ylabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'sz':  #for KS11
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].z)
            except KeyError:
                continue
            if len(params) == 2:
                try:
                    ys.append(params[0][key]['s'] / params[1][key]['s'])
                except KeyError:
                    xs.pop()
                    continue
            else:
                ys.append(params[0][key]['s'])
        ys = nu.array(ys) - 1.
        xs = nu.array(xs)
        yrange = [-1.1, 0.4]
        xrange = [0., 5.5]
        ylabel = r'$s_{' + options.band + r'}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'scatterz':  #for KS11
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            try:
                xs.append(qsos[qsoDict[key]].z)
            except KeyError:
                continue
            ys.append(params[0][key]['logsigma'])
        ys = nu.array(ys) - 1.
        xs = nu.array(xs)
        yrange = [-10, 0.]
        xrange = [0., 5.5]
        ylabel = r'$\sigma^2_{' + options.band + r'}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'ss':
        ys, xs = [], []
        if options.band2 is None:
            for key in params[0].keys():
                try:
                    ys.append(params[1][key]['s'][0] - 1.)
                except KeyError:
                    continue
                xs.append(params[0][key]['s'][0] - 1.)
        else:
            for key in params[0].keys():
                try:
                    ys.append(params[1][key]['s' + options.band2][0] - 1.)
                except KeyError:
                    continue
                xs.append(params[0][key]['s' + options.band][0] - 1.)
        xs = nu.array(xs)
        ys = nu.array(ys)
        xrange = [-0.9, 0.4]
        yrange = [-0.9, 0.4]
        if options.band2 is None:
            xlabel = r'$s$'
            ylabel = r'$s$'
        else:
            xlabel = r'$s_{' + options.band + r'}$'
            ylabel = r'$s_{' + options.band2 + r'}$'
        ylabelnounits = ylabel
        xlabelnounits = xlabel
    elif options.plottype == 'gz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gamma'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [0., 5.5]
        ylabel = r'$\gamma_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'Aci':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['logAgr'])
            xs.append(qsos[qsoDict[key]].mags[3])
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [15.0, 21.3]
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'gci':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gammagr'])
            xs.append(qsos[qsoDict[key]].mags[3])
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [15.0, 21.3]
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$i_0\ [\mathrm{mag}]$'
    elif options.plottype == 'loglike2':
        ys = []
        xs = []
        for key in params[0].keys():
            if not params[1].has_key(key): continue
            ys.append(params[1][key]['loglike'])
            xs.append(params[0][key]['loglike'])
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 200.]
        xrange = [0., 200.]
        ylabel = r'$\log L_{\mathrm{DRW}}\ \mathrm{in}\ ' + options.band[
            0] + r'$'
        xlabel = r'$\log L_{\mathrm{PL}}\ \mathrm{in}\ ' + options.band[
            0] + r'$'
    elif options.plottype == 'loglike3z':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            if not params[1].has_key(key): continue
            ys.append(params[1][key]['loglike'] - params[0][key]['loglike'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [-15., 15.]
        xrange = [0., 5.5]
        ylabel = r'$\log L_{\mathrm{DRW}}\ \mathrm{in}\ ' + options.band[
            0] + r' - \log L_{\mathrm{PL}}\ \mathrm{in}\ ' + options.band[
                0] + r'$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'Acz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['logAgr'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys) / 2.
        xs = nu.array(xs)
        yrange = [-9.21 / 2., 0.]
        xrange = [0., 5.5]
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'gcz':
        qsos = open_qsos()
        qsoDict = {}
        ii = 0
        for qso in qsos:
            qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
            ii += 1
        ys = []
        xs = []
        for key in params[0].keys():
            ys.append(params[0][key]['gammagr'])
            xs.append(qsos[qsoDict[key]].z)
        ys = nu.array(ys)
        xs = nu.array(xs)
        yrange = [0., 1.25]
        xrange = [0., 5.5]
        ylabel = r'$\gamma^c_{' + options.band + r'}\ \mathrm{(power\ law\ exponent)}$'
        xlabel = r'$z\ (\mathrm{redshift})$'
    elif options.plottype == 'AsAc':  #files: g, Ac, KS11
        xs = []
        ys = []
        if not options.imax is None:
            qsos = open_qsos()
            qsos = qsos[(qsos.mags[:, 3] < options.imax)]
            qsoDict = {}
            ii = 0
            for qso in qsos:
                qsoDict[qso.oname.strip().replace(' ', '') + '.fit'] = ii
                ii += 1
        for key in params[0].keys():
            if not key in qsoDict.keys(): continue
            try:
                if options.type == 'powerlawSFratios':
                    Ac = params[1][key]['logAri'] / 2. + 0.14
                    A = params[0][key]['logA'] / 2.
                else:
                    Ac = params[1][key]['logAgr'] / 2.
                    A = params[0][key]['logA'] / 2.
                s = params[2][key]['s']
                ys.append(Ac)
                xs.append(A + nu.log(1. - s))
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(ys))
        xrange = [-9.21 / 2., 0.]
        yrange = [-9.21 / 2., 0.]
        xlabel = r'$\log [ (1-s ) A_{' + options.band + r'}]\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^c_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
    elif options.plottype == 'st':  #DRW
        ys = nu.array([p['logl']
                       for p in params[0].values()]).reshape(len(params[0]))
        ys /= nu.log(10.)
        ys += nu.log10(365.)
        xs = nu.array([p['loga2']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs /= nu.log(10.)
        xs += nu.log10(2.) - ys
        #print nu.amin(ys), nu.amax(ys)
        xrange = [-6., 0.]
        yrange = [-.5, 3.5]
        xlabel = r'$\log_{10} \sigma^2_{' + options.band + r'}\ \mathrm{(short-timescale\ variance)}$'
        ylabel = r'$\log_{10} \tau_{' + options.band + r'}\ \mathrm{(damping\ timescale\ in\ days)}$'
    elif options.plottype == 'a2l':  #DRW
        ys = nu.array([p['logl']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = nu.array([p['loga2']
                       for p in params[0].values()]).reshape(len(params[0]))
        xrange = [-2.5, 0.]
        yrange = [-10., 4.]
        xlabel = r'$\log a^2_{' + options.band + r'}\ \mathrm{(variance)}$'
        ylabel = r'$\log \tau_{' + options.band + r'}\ \mathrm{(damping\ timescale\ in\ yr)}$'
    elif options.plottype == 'Al':  #DRW
        ys = nu.array([p['logl']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = nu.array([p['loga2']
                       for p in params[0].values()]).reshape(len(params[0]))
        xs = (nu.log(2.) + xs + nu.log(1. - nu.exp(-1. / nu.exp(ys)))) / 2.
        xrange = [-9.21 / 2., 0.]
        yrange = [-10., 4.]
        xlabel = r'$\log A_{' + options.band + r'}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log \tau_{' + options.band + r'}\ \mathrm{(damping\ timescale\ in\ yr)}$'
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(xs,
                          ys,
                          'k,',
                          onedhists=True,
                          yrange=yrange,
                          xrange=xrange,
                          bins=30,
                          xlabel=xlabel,
                          ylabel=ylabel)
    if options.plottype == 'AA' or options.plottype == 'gg' \
           or options.plottype == 'loglike2' \
           or options.plottype == 'AsAc' \
           or options.plottype == 'ss' \
           or options.plottype == 'AcAc':
        bovy_plot.bovy_plot(nu.array(xrange),
                            nu.array(xrange),
                            '0.5',
                            overplot=True)
    #also fit if desired
    if options.linearfit:
        indx= (xs > xrange[0])*(xs < xrange[1])\
            *(ys > yrange[0])*(ys < yrange[1])
        b = _fit_linear(xs[indx],
                        ys[indx],
                        removeoutliers=options.removeoutliers)
        bovy_plot.bovy_plot(nu.array(xrange),
                            nu.array(xrange) + b,
                            '0.25',
                            overplot=True)
        bovy_plot.bovy_text(ylabelnounits + r'$ = $' + xlabelnounits +
                            r'$ %4.2f$' % b,
                            bottom_right=True,
                            color='0.25')
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
예제 #60
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')