Пример #1
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))
Пример #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 plot_rcdistancecomparison(plotfilename):
    # Get the sample
    rcdata = define_rcsample.get_rcsample()
    # Now plot the differece
    bovy_plot.bovy_print()
    levels = special.erf(numpy.arange(1, 3) / numpy.sqrt(2.))
    bovy_plot.scatterplot(
        rcdata['RC_DIST'],
        (rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
        conditional=True,
        levels=levels,
        linestyle='none',
        color='k',
        marker=',',
        xrange=[0., 7.49],
        yrange=[-0.075, 0.075],
        xlabel=r'$M_{K_s}\!-\!\mathrm{based\ distance\,(kpc)}$',
        ylabel=
        r'$\mathrm{Fractional\ difference\ of}\ M_H\ \mathrm{vs.}\ M_{K_s}$',
        onedhistx=True,
        bins=31)
    bovy_plot.bovy_plot([0., 10.], [0., 0.],
                        '--',
                        lw=2.,
                        color='0.75',
                        overplot=True)
    # Plot lowess
    lowess = sm.nonparametric.lowess
    z = lowess((rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
               rcdata['RC_DIST'],
               frac=.3)
    bovy_plot.bovy_plot(z[:, 0], z[:, 1], 'w--', lw=2., overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def 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
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]
Пример #6
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)
Пример #7
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
Пример #8
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))
Пример #9
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)
Пример #10
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)
Пример #11
0
def plot_vr(plotfilename):
    #Read the APOGEE-RC data and pixelate it
    #APOGEE-RC
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    data= data[indx]
    #Get velocity field
    xmin, xmax= 5.5, 13.5
    dx= 1.
    pix= pixelize_sample.pixelXY(data,
                                 xmin=xmin,xmax=xmax,
                                 ymin=-dx/2.,ymax=dx/2.,
                                 dx=dx,dy=dx)
#                                 dx=_RCDX,dy=_RCDX)
    vr= pix.plot(lambda x: dvlosgal(x),
                 returnz=True,justcalc=True)
    vrunc= pix.plot(lambda x: dvlosgal(x),
                    func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                    returnz=True,justcalc=True)
    sr= pix.plot(lambda x: dvlosgal(x),
                 func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x))),
                 returnz=True,justcalc=True)
    srunc= pix.plot(lambda x: dvlosgal(x),
                    func=disperror,
                    returnz=True,justcalc=True)
    #print numpy.median(vr.flatten()[numpy.array([True,True,False,True,True,True,True,True,True],dtype='bool')])
    print vr.flatten()
    print vrunc.flatten()
    print sr.flatten()
    print srunc.flatten()
    rs= numpy.arange(xmin+dx/2.,xmax-dx/2.+0.00001,dx)
    print rs
    bovy_plot.bovy_print()
    srAxes= pyplot.axes([0.1,0.5,0.8,0.4])
    vrAxes= pyplot.axes([0.1,0.1,0.8,0.4])
    pyplot.sca(srAxes)
    pyplot.errorbar(rs,sr.flatten(),yerr=srunc.flatten(),
                    marker='o',ls='none',ms=6.,color='k')
    pyplot.xlim(0.,15.)
    pyplot.ylim(9.5,49.)
    #srAxes.set_yscale('log')
    bovy_plot._add_ticks(yticks=False)
    bovy_plot._add_axislabels(r'$ $',
                              r'$\sigma_R\,(\mathrm{km\,s}^{-1})$')
    nullfmt   = NullFormatter()         # no labels
    srAxes.xaxis.set_major_formatter(nullfmt)
    pyplot.sca(vrAxes)
    pyplot.errorbar(rs,vr.flatten(),yerr=vrunc.flatten(),
                    marker='o',ls='none',ms=6.,color='k')
    pyplot.plot([0.,20.],numpy.median(vr.flatten())*numpy.ones(2),'k--')
    bovy_plot._add_ticks()
    pyplot.xlim(0.,15.)
    pyplot.ylim(-14.,14.)
    bovy_plot._add_axislabels(r'$R\,(\mathrm{kpc})$',
                              r'$\langle V_R\rangle\,(\mathrm{km\,s}^{-1})$')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Пример #12
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
Пример #13
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                        
Пример #14
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))
Пример #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 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
Пример #17
0
    def plot_dJ(self,indx=-1):
        bovy_plot.bovy_print(axes_labelsize=17.,text_fontsize=12.,xtick_labelsize=15.,ytick_labelsize=15.)

        plt.figure(figsize=(7,6))
        plt.xlabel(r'$z\,\,(kpc)$')
        plt.ylabel(r'$v_z\,\,(km/s)$')
        plt.imshow(self.deltaJ[:,:,indx].T,aspect='auto',extent=[-self.zmax,self.zmax,-self.vmax,self.vmax])
        plt.colorbar()
Пример #18
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)
Пример #19
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
Пример #20
0
    def plot_orbit(self,mint=0,maxt=None):
        if maxt==None:
            maxt=len(self.tt)
        bovy_plot.bovy_print(axes_labelsize=17.,text_fontsize=12.,xtick_labelsize=15.,ytick_labelsize=15.)

        plt.figure(figsize=(14,7))
        plt.xlabel(r'$time\,\,(Gyr)$')
        plt.ylabel(r'$z\,\,(kpc)$')
        plt.plot(self.tt[mint:maxt],np.array(self.discOrb.x(self.tt[mint:maxt])).T)
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)
Пример #22
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
Пример #23
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
Пример #24
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)
Пример #25
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
Пример #26
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
Пример #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 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
Пример #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 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
Пример #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 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
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 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)
Пример #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 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)
Пример #38
0
def plot_maphz(plotname):
    # Load the three fits
    with open('../mapfits/tribrokenexpflare.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexp.sav','rb') as savefile:
        bfnf= numpy.array(pickle.load(savefile))
        samplesnf= numpy.array(pickle.load(savefile))
    with open('../mapfits/tribrokenexpfixedflare.sav','rb') as savefile:
        bfff= numpy.array(pickle.load(savefile))
        samplesff= numpy.array(pickle.load(savefile))
    maps= define_rcsample.MAPs()
    plotthisz= numpy.zeros(len(bf))+numpy.nan
    plotthisze= numpy.zeros(len(bf))+numpy.nan
    for ii, map in enumerate(maps.map()):
        if numpy.median(numpy.exp(samples[ii,3])[True-numpy.isnan(numpy.exp(samples[ii,3]))]) < 5.:
            tmed= numpy.median((1./samplesnf[ii,1])[True-numpy.isnan(1./samplesnf[ii,1])])
            terr= numpy.std((1./samplesnf[ii,1])[True-numpy.isnan(1./samplesnf[ii,1])])
        else:
            tmed= numpy.median((1./samplesff[ii,1])[True-numpy.isnan(1./samplesff[ii,1])])
            terr= numpy.std((1./samplesff[ii,1])[True-numpy.isnan(1./samplesff[ii,1])])
        plotthisz[ii]= tmed
        plotthisze[ii]= terr
    plotthisz[plotthisze/plotthisz > 0.2]= numpy.nan
    bovy_plot.bovy_print()
    maps.plot(plotthisz*1000.,
              vmin=200.,vmax=1000.,
              minnstar=15,
              zlabel=r'$h_Z\,(\mathrm{pc})$',
              shrink=0.655)
    # 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.set_bbox(dict(alpha=0.5,color=cm.coolwarm(0.),
    #                edgecolor='none'))
    pyplot.tight_layout()
    bovy_plot.bovy_end_print(plotname,dpi=300)
    return None
Пример #39
0
def plot_seguem10(plotfilename):
    savefile= open('../potential-fits/fitall_10ksamples_derived_whalomass.sav','rb')
    data= pickle.load(savefile)
    savefile.close()
    mh= numpy.array([x[8] for x in data])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(mh,range=[0.,10.],
                        bins=71,histtype='step',color='k',
                        xlabel=r'$M_{\mathrm{halo}}(<10\,\mathrm{kpc})\,(10^{10}\,M_\odot)$',
                        normed=True)
    xs= numpy.linspace(0.,10.,1001)
    bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi*numpy.var(mh[True-numpy.isnan(mh)]))*numpy.exp(-0.5*(xs-numpy.mean(mh[True-numpy.isnan(mh)]))**2./numpy.var(mh[True-numpy.isnan(mh)])),
                        'k-',lw=2,overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
Пример #40
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
Пример #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
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
Пример #43
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
Пример #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
def main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit MWPotential with Double-Exponential Disk Script Function.

    Parameters
    ----------
    args : list, optional
        an optional single argument that holds the sys.argv list,
        except for the script name (e.g., argv[1:])

    """
    if opts is not None and args is None:
        pass
    else:
        parser = make_parser()
        opts = parser.parse_args(args)

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

    # -------------------------------------------------------------------------
    # Using an exponential disk instead of a Miyamoto-Nagai disk

    # -----------------------
    # $c=1$:

    plt.figure(figsize=(16, 5))
    p_exp = mw_pot.fit(
        fitc=False,
        c=1.0,
        dblexp=True,
        plots=fpath + "Clemens-c_1.pdf",
    )

    # -----------------------
    # $c=0.5$:

    plt.figure(figsize=(16, 5))
    p_exp = mw_pot.fit(
        fitc=False,
        c=0.5,
        dblexp=True,
        plots=fpath + "Clemens-c_0p5.pdf",
    )

    # -----------------------
    # $c=1.5$:

    plt.figure(figsize=(16, 5))
    p_exp = mw_pot.fit(
        fitc=False,
        c=1.5,
        dblexp=True,
        plots=fpath + "Clemens-c_1p5.pdf",
    )

    # -----------------------
    # leave c free

    plt.figure(figsize=(16, 5))
    p_exp_cfree = mw_pot.fit(
        fitc=True,
        c=None,
        dblexp=True,
        plots=fpath + "Clemens-c_free.pdf",
    )

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

    bf_savefilename = opath + "mwpot14varyc-dblexp-bf.pkl"
    if os.path.exists(bf_savefilename):
        with open(bf_savefilename, "rb") as savefile:
            cs = pickle.load(savefile)
            bf_params = pickle.load(savefile)
    else:
        cs = np.arange(0.5, 4.1, 0.1)
        bf_params = []
        for c in tqdm(cs):
            dum = mw_pot.fit(
                fitc=False,
                c=c,
                dblexp=True,
                plots=fpath + "mwpot14varyc-dblexp-bf-fit.pdf",
            )
            bf_params.append(dum[0])
        save_pickles(bf_savefilename, cs, bf_params)

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

    samples_savefilename = opath + "mwpot14varyc-dblexp-samples.pkl"
    if os.path.exists(samples_savefilename):
        with open(samples_savefilename, "rb") as savefile:
            s = pickle.load(savefile)
    else:
        s = mw_pot.sample(
            nsamples=100000,
            params=p_exp_cfree[0],
            fitc=True,
            c=None,
            plots=fpath + "mwpot14varyc-dblexp-samples.pdf",
            dblexp=True,
        )
        save_pickles(samples_savefilename, s)

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

    plt.figure()
    mw_pot.plot_samples(
        s,
        True,
        False,
        savefig=fpath + "varyc-dblexp-samples-corner.pdf",
    )

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

    plt.figure()
    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=15.0,
        ytick_labelsize=15.0,
    )
    su.plot_mcmc_c(
        s,
        False,
        cs,
        bf_params,
        savefig=fpath + "varyc-dblexp-samples-dependence.pdf",
    )

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

    plt.figure(figsize=(4, 4))
    dum = bovy_plot.bovy_hist(
        s[7],
        bins=36,
        histtype="step",
        lw=2.0,
        xlabel=r"$c/a$",
        xrange=[0.0, 4.0],
        normed=True,
    )
    sortedc = np.array(sorted(s[7]))
    plt.title("2.5%% and 0.5%% lower limits: %.2f, %.2f" % (
        sortedc[int(np.floor(0.025 * len(sortedc)))],
        sortedc[int(np.floor(0.005 * len(sortedc)))],
    ))
    plt.savefig(fpath + "varyc-dblexp-samples-shape_hist.pdf")

    # -----------------------
    # Also fitting $R_0$ and $V_c(R_0)$

    plt.figure(figsize=(16, 5))
    p_exp_cfree_voro = mw_pot.fit(
        fitc=True,
        c=None,
        dblexp=True,
        fitvoro=True,
        plots=fpath + "fitvoro-samples.pdf",
    )

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

    samples_savefilename = opath + "mwpot14varyc-dblexp-fitvoro-samples.pkl"
    if os.path.exists(samples_savefilename):
        with open(samples_savefilename, "rb") as savefile:
            s = pickle.load(savefile)
    else:
        s = mw_pot.sample(
            nsamples=100000,
            params=p_exp_cfree_voro[0],
            fitc=True,
            c=None,
            plots=fpath + "mwpot14varyc-dblexp-fitvoro-samples.pdf",
            dblexp=True,
            fitvoro=True,
        )
        save_pickles(samples_savefilename, s)

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

    plt.figure()
    mw_pot.plot_samples(
        s,
        True,
        True,
        savefig=fpath + "varyc-dblexp-fitvoro-samples-corner.pdf",
    )

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

    plt.figure()
    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=15.0,
        ytick_labelsize=15.0,
    )
    su.plot_mcmc_c(
        s,
        True,
        cs,
        bf_params,
        savefig=fpath + "varyc-dblexp-fitvoro-samples-dependence.pdf",
    )

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

    plt.figure(figsize=(4, 4))
    dum = bovy_plot.bovy_hist(
        s[9],
        bins=36,
        histtype="step",
        lw=2.0,
        xlabel=r"$c/a$",
        xrange=[0.0, 4.0],
        normed=True,
    )
    sortedc = np.array(sorted(s[9]))
    plt.title("2.5%% and 0.5%% lower limits: %.2f, %.2f" % (
        sortedc[int(np.floor(0.025 * len(sortedc)))],
        sortedc[int(np.floor(0.005 * len(sortedc)))],
    ))
    plt.savefig(fpath + "varyc-dblexp-fitvoro-samples-samples-shape_hist.pdf")

    # -----------------------
    # Also adding in a gas disk (and still also fitting $R_0$ and $V_c(R_0)$)

    plt.figure(figsize=(16, 5))
    p_exp_cfree_voro_wgas = mw_pot.fit(
        fitc=True,
        c=None,
        dblexp=True,
        fitvoro=True,
        addgas=True,
        plots=fpath + "varyc-dblexp-fitvoro-addgas.pdf",
    )

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

    samples_savefilename = "mwpot14varyc-dblexp-fitvoro-addgas-samples.pkl"
    if os.path.exists(samples_savefilename):
        with open(samples_savefilename, "rb") as savefile:
            s = pickle.load(savefile)
    else:
        s = mw_pot.sample_multi(
            nsamples=100000,
            params=p_exp_cfree_voro_wgas[0],
            fitc=True,
            c=None,
            plots=fpath + "mwpot14varyc-dblexp-fitvoro-addgas-samples.pdf",
            dblexp=True,
            fitvoro=True,
            addgas=True,
        )
        save_pickles(samples_savefilename, s)

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

    plt.figure()
    mw_pot.plot_samples(
        s,
        True,
        True,
        savefig=fpath + "varyc-dblexp-fitvoro-addgas-samples-corner.pdf",
    )

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

    plt.figure()
    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=15.0,
        ytick_labelsize=15.0,
    )
    su.plot_mcmc_c(
        s,
        True,
        cs,
        bf_params,
        savefig=fpath + "varyc-dblexp-fitvoro-addgas-samples-dependence.pdf",
    )

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

    plt.figure(figsize=(4, 4))
    dum = bovy_plot.bovy_hist(
        s[9],
        bins=36,
        histtype="step",
        lw=2.0,
        xlabel=r"$c/a$",
        xrange=[0.0, 4.0],
        normed=True,
    )
    sortedc = np.array(sorted(s[9]))
    plt.title("2.5%% and 0.5%% lower limits: %.2f, %.2f" % (
        sortedc[int(np.floor(0.025 * len(sortedc)))],
        sortedc[int(np.floor(0.005 * len(sortedc)))],
    ))
    plt.savefig(fpath + "varyc-dblexp-fitvoro-addgas-samples-shape_hist.pdf")
Пример #48
0
__author__ = "Jeremy J Webb"
__all__ = [
    "starplot",
    "skyplot",
]

import matplotlib.pyplot as plt
import numpy as np
from galpy.util import bovy_plot
import seaborn as sns
import os
from scipy.ndimage import gaussian_filter
import matplotlib.colors as colors

bovy_plot.bovy_print(axes_labelsize=18.0,
                     xtick_labelsize=14.0,
                     ytick_labelsize=14.0)
current_palette = sns.color_palette()


def _scatter(x,
             y,
             z=None,
             xlabel="",
             ylabel="",
             legend=False,
             title="",
             xlim=None,
             ylim=None,
             scale=True,
             filename=None,
Пример #49
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
Пример #50
0
def waveregions(*args, **kwargs):
    """
    NAME:
       waveregions
    PURPOSE:
       plot selected regions of the spectrum in one row
    INPUT:
       Either:
          (a) wavelength, spectrum (\AA,spectrum units)
          (b) spectrum (assumed on standard APOGEE re-sampled wavelength grid)
          (c) location ID, APOGEE ID (default loads aspcapStar, loads extension ext(=1); apStar=True loads apStar spectrum)
    KEYWORDS:
       File loading:
          ext= (1) extension to load
          apStar= (False) if True, load the apStar spectrum
          apStarIndx= (1) index in the apStar spectrum to load
       Chunks position:
          startlams, endlams= start and end wavelength in \AA of the various chunks (takes precedence over startindxs, endindxs)
          startindxs, endindxs= star and end index in the wavelength array of the various chunks
       Plotting-specific keywords
          labelLines= (True) label some lines
          noMolecLines= (False) don't label the molecules
          cleanZero= (True) replace <= zero entries with NaN
          labelID= A string ID that will be placed in the top-left corner
          labelTeff, labellogg, labelmetals, labelafe= parameter labels that will be placed in the top-right corner
          noxlabel= (False) if True, don't label the x axis
          pyplot.plot args and kwargs
    OUTPUT:
       plot to output
       The final axes allow one to put additional labels on the plot, e.g., for adding the APOGEE ID:
       bovy_plot.bovy_text(r'$\mathrm{%s}$' % '2M02420597+0837017',top_left=True)       
       Note that an ID (e.g., the apogee ID) and Teff, logg, metallicity, and alpha-enhancement labels can be added using the keywords label* above
    HISTORY:
       2015-01-18 - Written (based on older code) - Bovy (IAS)
    """
    # Grab non-pyplot.plot kwargs
    apStar = kwargs.pop('apStar', False)
    labelLines = kwargs.pop('labelLines', not 'overplot' in kwargs)
    noMolecLines = kwargs.pop('noMolecLines', False)
    cleanZero = kwargs.pop('cleanZero', True)
    noxticks = kwargs.pop('_noxticks', False)
    noxlabel = kwargs.pop('noxlabel', False)
    noskipdiags = kwargs.pop('_noskipdiags', False)
    labelwav = kwargs.pop('_labelwav', False)
    plotw = kwargs.pop('_plotw', None)
    markLines = kwargs.pop('markLines', False)
    markwav = kwargs.pop('_markwav', None)
    # Labels
    labelID = kwargs.pop('labelID', None)
    labelTeff = kwargs.pop('labelTeff', None)
    labellogg = kwargs.pop('labellogg', None)
    labelmetals = kwargs.pop('labelmetals', None)
    labelafe = kwargs.pop('labelafe', None)
    # Clean bad lines
    if cleanZero:
        args[1][args[1] <= 0.] = numpy.nan
    # Chunk parameters
    if 'startlams' in kwargs:
        # Turn startlams into a startindxs and similar for endlams
        startlams = kwargs.pop('startlams')
        endlams = kwargs.pop('endlams')
        startindxs = []
        endindxs = []
        for ii in range(len(startlams)):
            startindxs.append(numpy.argmin(numpy.fabs(startlams[ii] -
                                                      args[0])))
            endindxs.append(numpy.argmin(numpy.fabs(endlams[ii] - args[0])))
    else:
        startindxs = kwargs.pop('startindxs',
                                [322, 1794, 2707, 3850, 4740, 5820, 7185])
        endindxs = kwargs.pop('endindxs',
                              [590, 1940, 2857, 4025, 5070, 5955, 7400])
    nregions = len(startindxs)
    # Calculate the width of the plot
    dx= numpy.array([args[0][numpy.amin([len(args[0])-1,endindxs[ii]])]\
                         -args[0][numpy.amax([0,startindxs[ii]-1])] \
                         for ii in range(nregions)],
                    dtype='float')
    # Adjust 0 (and -1) to start (end) a little further
    startendskip = kwargs.pop('_startendskip', _STARTENDSKIP)
    dx[0]= args[0][numpy.amin([len(args[0])-1,endindxs[0]])]\
        -args[0][numpy.amax([0,startindxs[0]-startendskip])]
    dx[-1]= args[0][numpy.amin([len(args[0])-1,endindxs[-1]+startendskip])]\
        -args[0][numpy.amax([0,startindxs[-1]-1])]
    if nregions == 1:  #special case
        dx= [args[0][numpy.amin([len(args[0])-1,endindxs[0]+startendskip])]\
                 -args[0][numpy.amax([0,startindxs[0]-startendskip])]]
    # Determine a good step for the tickmarks
    tickStepTmp = numpy.log10(numpy.sum(dx) / 10.) % 1
    if tickStepTmp > numpy.log10(1.5) and tickStepTmp < numpy.log10(3.5):
        tickStep = 2. * 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    elif tickStepTmp > numpy.log10(3.5) and tickStepTmp < numpy.log10(7.5):
        tickStep = 5. * 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    else:
        tickStep = 10.**int(numpy.log10(numpy.sum(dx) / 10.))
    dx /= numpy.sum(dx)
    if noxticks:
        totdx = 0.825
    else:
        totdx = 0.85
    skipdx = kwargs.pop('skipdx', 0.015)
    dx *= (totdx - (nregions - 1) * skipdx)
    # Setup plot
    overplot = kwargs.pop('overplot', False)
    if not overplot:
        bovy_plot.bovy_print(fig_width=kwargs.pop('fig_width', 8.4),
                             fig_height=kwargs.pop('fig_height', 2.5),
                             axes_labelsize=16,
                             text_fontsize=14,
                             legend_fontsize=12,
                             xtick_labelsize=12,
                             ytick_labelsize=12)
        pyplot.figure()
    if overplot:
        yrange = numpy.array(pyplot.gca().get_ylim())
        kwargs.pop('yrange', None)  # pop if there
    elif apStar:
        yrange = kwargs.pop('yrange', [0., 1.1 * numpy.nanmax(args[1])])
    else:
        yrange = kwargs.pop('yrange', [0.2, 1.2])
    # Deal with the label
    if apStar:
        ylabel = kwargs.pop(
            'ylabel',
            r'$f_\lambda(\lambda)\,(10^{-17}\,\mathrm{erg\, s}^{-1}\,\mathrm{cm}^{-2}\,\AA^{-1})$'
        )
    else:
        ylabel = kwargs.pop('ylabel', r'$f/f_c(\lambda)$')
    kwargs['zorder'] = kwargs.get('zorder', 10)
    for ii in range(nregions):
        # Setup the axes
        if ii == 0:
            left, bottom, width, height = 0.1 + (
                0.85 - totdx) * 2., 0.125, dx[ii], 0.8
        else:
            left, bottom, width, height= 0.1+(0.85-totdx)*2.+numpy.cumsum(dx)[ii-1]+skipdx*ii,\
                0.125, dx[ii], 0.8
        thisax = pyplot.axes([left, bottom, width, height])
        fig = pyplot.gcf()
        fig.sca(thisax)
        startindx, endindx = startindxs[ii], endindxs[ii]
        if ii == 0 and nregions == 1:
            xrange = [
                args[0][numpy.amax([0, startindx - startendskip])] -
                _LAMBDASUB, args[0][numpy.amin(
                    [len(args[0]) - 1, endindx + startendskip])] - _LAMBDASUB
            ]
        elif ii == 0:
            xrange = [
                args[0][numpy.amax([0, startindx - startendskip])] -
                _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx])] - _LAMBDASUB
            ]
        elif ii == (nregions - 1):
            xrange = [
                args[0][numpy.amax([0, startindx - 1])] - _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx + startendskip
                                    ])] - _LAMBDASUB
            ]
        else:
            xrange = [
                args[0][numpy.amax([0, startindx - 1])] - _LAMBDASUB,
                args[0][numpy.amin([len(args[0]) - 1, endindx])] - _LAMBDASUB
            ]
        thisax.plot(args[0][startindx:endindx] - _LAMBDASUB,
                    args[1][startindx:endindx], *args[2:], **kwargs)
        if not plotw is None:
            thisax.plot(args[0][startindx:endindx] - _LAMBDASUB,
                        plotw[startindx:endindx],
                        '-',
                        lw=2.,
                        color='0.65',
                        zorder=1)
        thisax.set_xlim(xrange[0], xrange[1])
        thisax.set_ylim(yrange[0], yrange[1])
        if noxticks:
            nullfmtx = NullFormatter()  # no labels, assume 1\AA
            thisax.xaxis.set_major_formatter(nullfmtx)
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(2.))
        else:
            thisax.xaxis.set_major_locator(ticker.MultipleLocator(tickStep))
        bovy_plot._add_ticks(xticks=True - noxticks)
        if ii > 0:
            nullfmt = NullFormatter()  # no labels
            thisax.yaxis.set_major_formatter(nullfmt)
        elif not overplot:
            pyplot.ylabel(ylabel)
        # Remove spines between different wavelength regions
        if ii == 0 and not nregions == 1:
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(right=False, which='both')
        elif ii == (nregions - 1) and not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False, which='both')
        elif not nregions == 1:
            thisax.spines['left'].set_visible(False)
            thisax.spines['right'].set_visible(False)
            thisax.tick_params(labelleft='off')
            thisax.tick_params(left=False, which='both')
            thisax.tick_params(right=False, which='both')
        # Plot cut-out markers
        cutOutkwargs = dict(transform=thisax.transAxes,
                            color='k',
                            clip_on=False)
        if not noskipdiags:
            d = .015  # how big to make the diagonal lines in axes coordinates
            slope = 1. / (dx[ii] + 0.2 * skipdx) / 3.
            if ii == 0 and not nregions == 1:
                thisax.plot((1 - slope * d, 1 + slope * d), (-d, +d),
                            **cutOutkwargs)
                thisax.plot((1 - slope * d, 1 + slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
            elif ii == (nregions - 1) and not nregions == 1:
                thisax.plot((-slope * d, +slope * d), (-d, +d), **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
            elif not nregions == 1:
                thisax.plot((1 - slope * d, 1 + slope * d), (-d, +d),
                            **cutOutkwargs)
                thisax.plot((1 - slope * d, 1 + slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (-d, +d), **cutOutkwargs)
                thisax.plot((-slope * d, +slope * d), (1 - d, 1 + d),
                            **cutOutkwargs)
        else:  #plot gray bands
            cutOutkwargs['color'] = '0.5'
            thisax.fill_between((1., 1. + skipdx), (0., 0.), (1., 1.),
                                **cutOutkwargs)
        # Label the lines
        if labelLines:
            _label_all_lines(args[0][startindx], args[0][endindx], thisax,
                             args[0], args[1], noMolecLines)
        # Mark the lines
        if markLines:
            _mark_lines(markwav, args[0][startindx], args[0][endindx], thisax,
                        args[0], args[1])
        # Label the largest round wavelength in angstrom for windows
        if labelwav:
            bovy_plot.bovy_text(
                2 * numpy.floor((xrange[1] - (nregions > 15)) / 2.),
                yrange[0] + 0.05 * (yrange[1] - yrange[0]),
                r'$\lambda\kern 0.1em%i,%03i$' %
                (15 + int(numpy.floor(xrange[1] / 1000.)),
                 int(2. * numpy.floor(
                     (xrange[1] - (nregions > 15)) / 2.) % 1000.)),
                horizontalalignment='center',
                verticalalignment='bottom',
                rotation='vertical',
                fontsize=10.)
    # Add the x-axis label
    if not nregions == 1:
        thisax = pyplot.axes([0.1 + (0.85 - totdx) * 2., 0.125, totdx, 0.8])
        pyplot.gcf().sca(thisax)
        thisax.set_ylim(yrange[0], yrange[1])
        thisax.spines['left'].set_visible(False)
        thisax.spines['right'].set_visible(False)
        thisax.spines['bottom'].set_visible(False)
        thisax.spines['top'].set_visible(False)
        thisax.tick_params(labelleft='off')
        thisax.tick_params(left=False, which='both')
        thisax.tick_params(right=False, which='both')
        thisax.tick_params(labelbottom='off')
        thisax.tick_params(bottom=False, which='both')
        thisax.tick_params(top=False, which='both')
    if not overplot and not noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda-%i,000\,(\AA)$' %
                          (int(_LAMBDASUB / 1000.)),
                          labelpad=10 - (nregions == 1) * 10)
    elif not overplot and noxticks and not noxlabel:
        thisax.set_xlabel(r'$\lambda\,(\AA)$',
                          labelpad=3 - (nregions == 1) * 3)
    if not nregions == 1:
        thisax.set_zorder(-1)
        # Start another axis object for later labeling
        thisax = pyplot.axes([0.1 + (0.85 - totdx) * 2., 0.125, totdx, 0.8])
        pyplot.gcf().sca(thisax)
        thisax.patch.set_facecolor('None')
        thisax.set_zorder(10)
    # Labels
    if not labelID is None:
        bovy_plot.bovy_text(r'$\mathrm{%s}$' % labelID,
                            top_left=True,
                            fontsize=10)
    if not labelTeff is None or not labellogg is None \
            or not labelmetals is None or not labelafe is None:
        nParamLabels= int(not labelTeff is None)\
            +int(not labellogg is None)\
            +int(not labelmetals is None)\
            +int(not labelafe is None)
        # Label parameters
        paramStr = ''
        if not labelTeff is None:
            paramStr += r'T_\mathrm{eff}= %i\,\mathrm{K}' % (int(labelTeff))
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labellogg is None:
            paramStr += r'\log g= %.1f' % labellogg
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labelmetals is None:
            paramStr += r'[\mathrm{M/H}]= %.2f' % labelmetals
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        if not labelafe is None:
            paramStr += r'[\alpha/\mathrm{M}]= %.2f' % labelafe
            nParamLabels -= 1
            if nParamLabels > 0:
                paramStr += ',\ '
        bovy_plot.bovy_text(r'$%s$' % paramStr, top_right=True, fontsize=10)
    return None
Пример #51
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
Пример #52
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)
Пример #53
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')
Пример #54
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)
Пример #55
0
tdyn = zh_init / sigma_init
print(' initial zh, tdyn =', zh_init, tdyn)
# DM density
omega_m2m = omegadm_true * 1.5
print('Initial omega, Xnm and sigma =', omega_m2m, xnm_m2m, sigma_init)

z_m2m, vz_m2m, w_init = wendym2m.sample_sech2(sigma_init,
                                              totmass_init,
                                              n=n_m2m)
z_out = numpy.linspace(zmin, zmax, 101)
dens_init = xnm_m2m * hom2m.compute_dens(
    z_m2m, zsun_true, z_out, h_m2m, w=w_init)
v2_init = hom2m.compute_v2(z_m2m, vz_m2m, zsun_true, z_out, h_m2m, w=w_init)
v_init = hom2m.compute_v(z_m2m, vz_m2m, zsun_true, z_out, h_m2m, w=w_init)
bovy_plot.bovy_print(axes_labelsize=17.,
                     text_fontsize=12.,
                     xtick_labelsize=15.,
                     ytick_labelsize=15.)

### adiabatically add omega to the initial model
g = wendypy.nbody(z_m2m, vz_m2m, w_init, dttdyn * tdyn, approx=True, nleap=1)
nt = 4000
print('Addiabatically adding omega, nt=', nt)
zt = numpy.empty((n_m2m, nt + 1))
vzt = numpy.empty((n_m2m, nt + 1))
# Et = numpy.empty((nt+1))
zt[:, 0] = z_m2m
vzt[:, 0] = vz_m2m
# Et[0] = wendy.energy(z_init, vz_init, m_init)
# increasing omega
nstep_omega = 1000
if nstep_omega > nt:
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)
Пример #57
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
Пример #58
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
Пример #59
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)
Пример #60
0
def elements(elem, *args, **kwargs):
    """
    NAME:
       elements
    PURPOSE:
       make a plot of measurements of the elemental abundances vs. atomic number
    INPUT:
       elem - dictionary with elemental abundances relative to H
       wrtFe= (True) if True, plot elements wrt Fe on the left Y
       inclwrtH= (True) if True, indicate what X/H is on the right Y
       bovy_plot.bovy_plot args and kwargs
    OUTPUT:
       plot to output
    HISTORY:
       2015-03-10 - Written - Bovy (IAS)
    """
    # Process the input dictionary
    xs = []
    names = []
    ys = []
    wrtFe = kwargs.pop('wrtFe', True)
    for el in elem:
        try:
            xs.append(atomic_number(el))
        except KeyError:  # ignore things that aren't known elements
            continue
        names.append(r'$\mathrm{%s}$' % el.lower().capitalize())
        try:
            if not wrtFe: raise KeyError
            ys.append(elem[el] - elem['Fe'])
        except KeyError:
            ys.append(elem[el])
            wrtFe = False
    xs = numpy.array(xs, dtype='int')
    ys = numpy.array(ys)
    names = numpy.array(names)
    # sort
    sindx = numpy.argsort(xs)
    xs = xs[sindx]
    ys = ys[sindx]
    names = names[sindx]
    # add second y axis?
    inclwrtH = kwargs.pop('inclwrtH', True)
    if wrtFe:
        feh = elem['Fe']
        ylabel = kwargs.pop('ylabel', r'$[\mathrm{X/Fe}]$')
    else:
        ylabel = kwargs.pop('ylabel', r'$[\mathrm{X/H}]$')
    if not kwargs.get('overplot', False):
        bovy_plot.bovy_print(fig_width=7., fig_height=4.)
    basezorder = kwargs.pop('zorder', 0)
    yrange = kwargs.pop('yrange', [-0.5, 0.5])
    ls = kwargs.pop('ls', '-')
    lw = kwargs.pop('lw', 0.25)
    bovy_plot.bovy_plot(xs,
                        ys,
                        *args,
                        ylabel=ylabel,
                        xrange=[4, numpy.amax(xs) + 2],
                        yrange=yrange,
                        zorder=2 + basezorder,
                        ls=ls,
                        lw=lw,
                        **kwargs)
    pyplot.xticks(list(xs), names)
    pyplot.tick_params(axis='x', labelsize=11.)
    if wrtFe and inclwrtH:
        bovy_plot.bovy_plot([4, numpy.amax(xs) + 2], [0., 0.],
                            '-',
                            lw=2.,
                            color='0.65',
                            overplot=True,
                            zorder=basezorder)
        ax = pyplot.gca()
        ax2 = ax.twinx()
        ax2.set_ylim(yrange[0] + feh, yrange[1] + feh)
        ax2.set_ylabel(r'$[\mathrm{X/H}]$')
        pyplot.sca(ax2)
        bovy_plot._add_ticks(yticks=True, xticks=False)
    return None