Пример #1
0
def plot_rcdistancecomparison(plotfilename):
    # Get the sample
    rcdata = define_rcsample.get_rcsample()
    # Now plot the differece
    bovy_plot.bovy_print()
    levels = special.erf(numpy.arange(1, 3) / numpy.sqrt(2.))
    bovy_plot.scatterplot(
        rcdata['RC_DIST'],
        (rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
        conditional=True,
        levels=levels,
        linestyle='none',
        color='k',
        marker=',',
        xrange=[0., 7.49],
        yrange=[-0.075, 0.075],
        xlabel=r'$M_{K_s}\!-\!\mathrm{based\ distance\,(kpc)}$',
        ylabel=
        r'$\mathrm{Fractional\ difference\ of}\ M_H\ \mathrm{vs.}\ M_{K_s}$',
        onedhistx=True,
        bins=31)
    bovy_plot.bovy_plot([0., 10.], [0., 0.],
                        '--',
                        lw=2.,
                        color='0.75',
                        overplot=True)
    # Plot lowess
    lowess = sm.nonparametric.lowess
    z = lowess((rcdata['RC_DIST_H'] - rcdata['RC_DIST']) / rcdata['RC_DIST'],
               rcdata['RC_DIST'],
               frac=.3)
    bovy_plot.bovy_plot(z[:, 0], z[:, 1], 'w--', lw=2., overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Пример #2
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                        
Пример #3
0
def _plotMRZ_single(XYZ,R,data,options,args,all=True,overplot=True,xrange=None,
                    Zrange=None,Rrange=None,yrange=None,colorrange=None,
                    fehrange=None):
    if all:
        bovy_plot.scatterplot(data.dered_g-data.dered_r,
                              data.feh,
                              'k,',
                              bins=21,
                              xrange=xrange,
                              yrange=yrange,
                              xlabel=r'$g-r\ [\mathrm{mag}]$',
                              ylabel=r'$[\mathrm{Fe/H}]$',
                              onedhists=True)
        platestr= '\mathrm{all\ plates}'
        bovy_plot.bovy_text(r'$'+platestr+'$'
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            len(data.feh),top_right=True,size=16)
    else:
        #Cut to range
        indx= (numpy.fabs(XYZ[:,2]) > Zrange[0])\
        *(numpy.fabs(XYZ[:,2]) <= Zrange[1])\
        *(R > Rrange[0])\
        *(R <= Rrange[1])
        thisdata= data[indx]
        if len(thisdata) > 1500:
            bovy_plot.scatterplot(thisdata.dered_g-thisdata.dered_r,
                                  thisdata.feh,
                                  'k,',
                                  bins=21,
                                  xrange=xrange,
                                  yrange=yrange,
                                  xlabel=r'$g-r\ [\mathrm{mag}]$',
                                  ylabel=r'$[\mathrm{Fe/H}]$',
                                  onedhists=True)
        else:
            bovy_plot.bovy_plot(thisdata.dered_g-thisdata.dered_r,
                                thisdata.feh,
                                'k,',
                                bins=21,
                                xrange=xrange,
                                yrange=yrange,
                                xlabel=r'$g-r\ [\mathrm{mag}]$',
                                ylabel=r'$[\mathrm{Fe/H}]$',
                                onedhists=True)
        if options.plottype.lower() == 'r':
            lbstr= r'$%i < R / \mathrm{kpc} \leq %i$' % (int(Rrange[0]),int(Rrange[1]))
        else:
            lbstr= r'$%i < |Z| / \mathrm{pc} \leq %i$' % (int(1000*Zrange[0]),int(1000*Zrange[1]))
        bovy_plot.bovy_text(r'$%i \ \ \mathrm{stars}$' % 
                            len(thisdata.feh)
                            +'\n'+
                            lbstr,top_right=True,size=16)
    return None
Пример #4
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)
Пример #5
0
def afeh(options,args):
    """Plot the [alpha/Fe] vs. [Fe/H] distribution of the sample"""
    if options.png: ext= 'png'
    else: ext= 'ps'
    #Load data
    XYZ,vxvyvz,cov_vxvyvz,data= readData(metal='allall',
                                         sample=options.sample)
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(data.feh,data.afe,'k,',
                          xrange=[-2.,0.5],
                          yrange=[-0.1,0.6],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=r'$[\alpha/\mathrm{Fe}]$',
                          onedhists=True)
    #Overplot cuts, metal-rich
    lw=1.3
    bovy_plot.bovy_plot(_APOORFEHRANGE,[_APOORAFERANGE[0],_APOORAFERANGE[0]],
                         'k--',overplot=True,lw=lw)
    bovy_plot.bovy_plot(_APOORFEHRANGE,[_APOORAFERANGE[1],_APOORAFERANGE[1]],
                        'k--',overplot=True,lw=lw)
    bovy_plot.bovy_plot([_APOORFEHRANGE[0],_APOORFEHRANGE[0]],_APOORAFERANGE,
                        'k--',overplot=True,lw=lw)
    bovy_plot.bovy_plot([_APOORFEHRANGE[1],_APOORFEHRANGE[1]],_APOORAFERANGE,
                        'k--',overplot=True,lw=lw)
    #metal-poor
    bovy_plot.bovy_plot(_ARICHFEHRANGE,[_ARICHAFERANGE[0],_ARICHAFERANGE[0]],
                         'k--',overplot=True,lw=lw)
    bovy_plot.bovy_plot(_ARICHFEHRANGE,[_ARICHAFERANGE[1],_ARICHAFERANGE[1]],
                        'k--',overplot=True,lw=lw)
    bovy_plot.bovy_plot([_ARICHFEHRANGE[0],_ARICHFEHRANGE[0]],_ARICHAFERANGE,
                        'k--',overplot=True,lw=lw)
    bovy_plot.bovy_plot([_ARICHFEHRANGE[1],_ARICHFEHRANGE[1]],_ARICHAFERANGE,
                        'k--',overplot=True,lw=lw)
    #metal-richrich
    bovy_plot.bovy_plot([-0.6,-0.6],_APOORAFERANGE,'k:',overplot=True,lw=lw)
    bovy_plot.bovy_plot([-0.3,-0.3],_APOORAFERANGE,'k:',overplot=True,lw=lw)
    bovy_plot.bovy_plot([-0.6,-0.3],[_APOORAFERANGE[0],_APOORAFERANGE[0]],
                        'k:',overplot=True,lw=lw)
    bovy_plot.bovy_plot([-0.6,-0.3],[_APOORAFERANGE[0],_APOORAFERANGE[0]],
                        'k:',overplot=True,lw=lw)
    bovy_plot.bovy_plot([-0.6,-0.3],[_APOORAFERANGE[1],_APOORAFERANGE[1]],
                        'k:',overplot=True,lw=lw)
    #metal-poorpoor
    bovy_plot.bovy_plot([-0.7,-0.7],_ARICHAFERANGE,
                        'k:',overplot=True,lw=lw)
    bovy_plot.bovy_end_print(os.path.join(args[0],options.type+'_'
                                          +options.sample+'_'+
                                          options.metal+'.'+ext))
Пример #6
0
def _plotMC_single(data,options,args,all=False,overplot=False,xrange=None,
                   yrange=None,platels=None,platebs=None,
                   rmin=None,rmax=None,grmin=None,grmax=None,
                   rx=None,ry=None,fehrange=None,colorrange=None):
    if all:
        bovy_plot.scatterplot(data.dered_g-data.dered_r,
                              data.feh,
                              'k,',
                              bins=21,
                              xrange=xrange,
                              yrange=yrange,
                              xlabel=r'$g-r\ [\mathrm{mag}]$',
                              ylabel=r'$[\mathrm{Fe/H}]$',
                              onedhists=True)
        platestr= '\mathrm{all\ plates}'
        bovy_plot.bovy_text(r'$'+platestr+'$'
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            len(data.feh),top_right=True,size=16)
    else:
        bovy_plot.bovy_plot(data.dered_g-data.dered_r,
                              data.feh,
                              'k,',
                              bins=21,
                              xrange=xrange,
                              yrange=yrange,
                              xlabel=r'$g-r\ [\mathrm{mag}]$',
                              ylabel=r'$[\mathrm{Fe/H}]$',
                              onedhists=True)
        platestr= '%i\ \mathrm{plates}' % len(set(list(data.plate)))
        lbstr= '$l = %i^\circ \pm %i^\circ$' % (
            int(numpy.mean(platels)),int(numpy.std(platels)))+'\n'\
            +'$b = %i^\circ\pm%i^\circ$' % (int(numpy.mean(platebs)),
                                            int(numpy.std(platebs)))
        bovy_plot.bovy_text(r'$'+platestr+'$'
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            len(data.feh)
                            +'\n'+
                            lbstr,top_right=True,size=16)
        _add_coordinset(rx=rx,ry=ry,platels=platels,platebs=platebs,
                        feh=numpy.mean(data.feh),
                        rmin=rmin,rmax=rmax,
                        grmin=grmin,grmax=grmin)
Пример #7
0
    def scatterplot(self,d1,d2,*args,**kwargs):
        """
        NAME:
        
           scatterplot

        PURPOSE:

           make a scatterplot of the data

        INPUT:

           d1, d2 - x and y dimension to plot

           hoggscatter - if True, hogg_scatterplot

           +bovy_plot.plot or bovy_plot.scatterplot args and kwargs

        OUTPUT:

           plot to output device

        HISTORY:

           2010-08-09 - Written - Bovy (NYU)

        """
        if kwargs.has_key('hoggscatter'):
            hoggscatter= kwargs['hoggscatter']
            kwargs.pop('hoggscatter')
        else:
            hoggscatter= False
        if not kwargs.has_key('xlabel'):
            kwargs['xlabel']= str(d1)
        if not kwargs.has_key('ylabel'):
            kwargs['ylabel']= str(d2)
        if hoggscatter:
            if hasattr(self,'weight'):
                kwargs['weights']= self.weight
            bovy_plot.scatterplot(self.a[:,d1],self.a[:,d2],
                                  *args,**kwargs)
        else:
            bovy_plot.bovy_plot(self.a[:,d1],self.a[:,d2],
                                *args,**kwargs)
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 main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit Combination Pal5 and GD1 to MW Potential 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

    # -----------------------
    # Adding in the force measurements from Pal 5 *and* GD-1; also fitting
    # $R_0$ and $V_c(R_0)$

    plt.figure(figsize=(16, 5))
    p_b15_pal5gd1_voro = mw_pot.fit(
        fitc=True,
        c=None,
        addpal5=True,
        addgd1=True,
        fitvoro=True,
        mc16=True,
        plots=fpath + "fit.pdf",
    )

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

    samples_savefilename = opath + "mwpot14varyc-fitvoro-pal5gd1-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_b15_pal5gd1_voro[0],
            fitc=True,
            c=None,
            plots=fpath + "mwpot14varyc-fitvoro-pal5gd1-samples.pdf",
            mc16=True,
            addpal5=True,
            addgd1=True,
            fitvoro=True,
        )
        save_pickles(samples_savefilename, s)

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

    plt.figure()
    mw_pot.plot_samples(
        s,
        True,
        True,
        addpal5=True,
        addgd1=True,
        savefig=fpath + "mwpot14varyc-fitvoro-pal5gd1-samples-corner.pdf",
    )

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

    bf_savefilename = opath + "mwpot14varyc-bf.pkl"  # should already exist
    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,
                plots=fpath + "mwpot14varyc-bf-fit.pdf",
            )
            bf_params.append(dum[0])
        save_pickles(bf_savefilename, cs, bf_params)

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

    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 + "mwpot14varyc-bf-combo_pal5_gd1-dependence.pdf",
    )
    if save_figures:
        plt.savefig(
            os.path.join(
                os.getenv("PAPERSDIR"),
                "2016-mwhalo-shape",
                "mwpot14-varyc-wp5g1.pdf",
            ),
            bbox_inches="tight",
        )

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

    plt.figure(figsize=(4, 4))
    cindx = 9
    dum = bovy_plot.bovy_hist(
        s[cindx],
        bins=36,
        histtype="step",
        lw=2.0,
        xlabel=r"$c/a$",
        xrange=[0.5, 1.5],
        normed=True,
    )
    plt.savefig(fpath + "mwpot14varyc-bf-combo_pal5_gd1-shape_hist.pdf")

    with open(opath + "fit_potential_combo-pal5-gd1.txt", "w") as file:
        sortedc = np.array(sorted(s[cindx][-50000:]))
        file.write("2.5%% and 0.5%% lower limits: %.3f, %.3f" % (
            sortedc[int(np.floor(0.025 * len(sortedc)))],
            sortedc[int(np.floor(0.005 * len(sortedc)))],
        ))
        file.write("2.5%% and 0.5%% upper limits: %.3f, %.3f" % (
            sortedc[int(np.floor(0.975 * len(sortedc)))],
            sortedc[int(np.floor(0.995 * len(sortedc)))],
        ))
        file.write("Median, 68%% confidence: %.3f, %.3f, %.3f" % (
            np.median(sortedc),
            sortedc[int(np.floor(0.16 * len(sortedc)))],
            sortedc[int(np.floor(0.84 * len(sortedc)))],
        ))
        file.write("Mean, std. dev.: %.2f,%.2f" % (
            np.mean(sortedc),
            np.std(sortedc),
        ))

    # -----------------------
    # What is the constraint on the mass of the halo?

    tR = 20.0 / REFR0
    skip = 1
    hmass = []
    for sa in tqdm(s.T[::skip]):
        pot = mw_pot.setup_potential(
            sa,
            sa[-1],
            True,
            False,
            REFR0 * sa[8],
            REFV0 * sa[7],
            fitvoro=True,
        )
        hmass.append(-integrate.quad(
            lambda x: tR**2.0 * potential.evaluaterforces(
                pot[2], tR * x, tR * np.sqrt(1.0 - x**2.0), phi=0.0),
            0.0,
            1.0,
        )[0] * bovy_conversion.mass_in_1010msol(REFV0, REFR0) / 10.0)
    hmass = np.array(hmass)

    with open(opath + "fit_potential_combo-pal5-gd1.txt",
              "a") as file:  # append

        file.write("\nMass Constraints:")

        sortedhm = np.array(sorted(hmass))
        file.write("2.5%% and 0.5%% lower limits: %.2f, %.2f" % (
            sortedhm[int(np.floor(0.025 * len(sortedhm)))],
            sortedhm[int(np.floor(0.005 * len(sortedhm)))],
        ))
        file.write("2.5%% and 0.5%% upper limits: %.2f, %.2f" % (
            sortedhm[int(np.floor(0.975 * len(sortedhm)))],
            sortedhm[int(np.floor(0.995 * len(sortedhm)))],
        ))
        file.write("Median, 68%% confidence: %.2f, %.2f, %.2f" % (
            np.median(sortedhm),
            sortedhm[int(np.floor(0.16 * len(sortedhm)))],
            sortedhm[int(np.floor(0.84 * len(sortedhm)))],
        ))

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

    bovy_plot.scatterplot(
        hmass,
        s[-1, ::skip],
        "k,",
        onedhists=True,
        bins=31,
        xrange=[0.5, 1.5],
        yrange=[0.5, 1.5],
        xlabel=r"$M_{\mathrm{halo}} (r<20\,\mathrm{kpc})\,(M_\odot)$",
        ylabel=r"$c/a$",
    )
    plt.savefig(fpath + "scatterplot.pdf")
Пример #10
0
def plot_afefeh(plotfilename):
    # Load the data
    data = define_rcsample.get_rcsample()
    # Plot the data
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(data[define_rcsample._FEHTAG],
                          data[define_rcsample._AFETAG],
                          'k.',
                          ms=.8,
                          levels=special.erf(
                              numpy.arange(1, 2) / numpy.sqrt(2.)),
                          xrange=[-1., 0.4],
                          yrange=[-0.15, 0.35],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=define_rcsample._AFELABEL)
    # Overplot sub-samples
    # low alpha, low feh
    lowfeh = define_rcsample._lowlow_lowfeh(0.)
    highfeh = define_rcsample._lowlow_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._lowlow_lowafe(lowfeh),
        define_rcsample._lowlow_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._lowlow_lowafe(highfeh),
        define_rcsample._lowlow_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._lowlow_lowafe(lowfeh),
        define_rcsample._lowlow_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._lowlow_highafe(lowfeh),
        define_rcsample._lowlow_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # high alpha
    lowfeh = define_rcsample._highalpha_lowfeh(0.)
    highfeh = define_rcsample._highalpha_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._highalpha_lowafe(lowfeh),
        define_rcsample._highalpha_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._highalpha_lowafe(highfeh),
        define_rcsample._highalpha_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highalpha_lowafe(lowfeh),
        define_rcsample._highalpha_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highalpha_highafe(lowfeh),
        define_rcsample._highalpha_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # solar
    lowfeh = define_rcsample._solar_lowfeh(0.)
    highfeh = define_rcsample._solar_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._solar_lowafe(lowfeh),
        define_rcsample._solar_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._solar_lowafe(highfeh),
        define_rcsample._solar_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._solar_lowafe(lowfeh),
        define_rcsample._solar_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._solar_highafe(lowfeh),
        define_rcsample._solar_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # high [Fe/H]
    lowfeh = define_rcsample._highfeh_lowfeh(0.)
    highfeh = define_rcsample._highfeh_highfeh(0.)
    pyplot.plot([lowfeh, lowfeh], [
        define_rcsample._highfeh_lowafe(lowfeh),
        define_rcsample._highfeh_highafe(lowfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([highfeh, highfeh], [
        define_rcsample._highfeh_lowafe(highfeh),
        define_rcsample._highfeh_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highfeh_lowafe(lowfeh),
        define_rcsample._highfeh_lowafe(highfeh)
    ],
                'k--',
                lw=2.)
    pyplot.plot([lowfeh, highfeh], [
        define_rcsample._highfeh_highafe(lowfeh),
        define_rcsample._highfeh_highafe(highfeh)
    ],
                'k--',
                lw=2.)
    # Label them
    bovy_plot.bovy_text(-0.4,
                        0.265,
                        r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
                        size=15.,
                        backgroundcolor='w')
    bovy_plot.bovy_text(-0.975,
                        0.05,
                        r'$\mathrm{low\ [Fe/H]}$',
                        size=15.,
                        backgroundcolor='w')
    bovy_plot.bovy_text(0.,
                        -0.125,
                        r'$\mathrm{high\ [Fe/H]}$',
                        size=15.,
                        backgroundcolor='w')
    bovy_plot.bovy_text(-0.225,
                        -0.125,
                        r'$\mathrm{solar}$',
                        size=15.,
                        backgroundcolor='w')
    # Loci
    if False:
        haloc = define_rcsample.highalphalocus()
        bovy_plot.bovy_plot(haloc[:, 0],
                            haloc[:, 1],
                            'k-',
                            lw=2.,
                            overplot=True)
        haloc = define_rcsample.lowalphalocus()
        bovy_plot.bovy_plot(haloc[:, 0],
                            haloc[:, 1],
                            'k-',
                            lw=2.,
                            overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Пример #11
0
def plotActionData(options,args):
    #Read the data
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Setup error mc integration
    options.nmcerr= 1#in case this isn't set correctly
    raw, errstuff= setup_err_mc(raw,options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    #print numpy.argmin((fehs+0.25)**2.+(afes-0.175)**2.)
    #Setup potential
    params= numpy.array([-1.33663190049,0.998420232634,-3.49031638164,0.31949840593,-1.63965169376])
    try:
        pot= setup_potential(params,options,0)#Assume that the potential parameters come from a file with a single set of df parameters first
    except RuntimeError: #if this set of parameters gives a nonsense potential
        raise
    ro= 1.
    vo= params[1]
    aA= setup_aA(pot,options)
    jr, lz, jz= [], [], []
    #Get data ready
    params= [None,None,None,None,None,None,params[0],params[1],params[2],params[3],params[4]]
    for indx in range(len(fehs)):
        if numpy.log(monoAbundanceMW.hr(fehs[indx],afes[indx],k=(options.sample.lower() == 'k'))/8.) > -0.5 :
            continue
        R,vR,vT,z,vz,e,ee,eee= prepare_coordinates(params,indx,fehs,afes,binned,
                                          errstuff,
                                          options,1)
        tjr, tlz, tjz= aA(R.flatten(),vR.flatten(),vT.flatten(),z.flatten(),vz.flatten())
        jr.extend(list(tjr))
        lz.extend(list(tlz))
        jz.extend(list(tjz))
    #Now plot
    jr= numpy.array(jr).flatten()*ro*vo*_REFR0*_REFV0
    lz= numpy.array(lz).flatten()*ro*vo*_REFR0*_REFV0
    jz= numpy.array(jz).flatten()*ro*vo*_REFR0*_REFV0
    bovy_plot.bovy_print()
    levels= special.erf(numpy.sqrt(0.5)*numpy.arange(1,3))
    levels= list(levels)
    levels.append(1.01)
    print len(jr)
    if options.type.lower() == 'lzjr':
        axScatter, axHistx,axHisty= bovy_plot.scatterplot(lz/220.,jr/220.,',',
                              xlabel=r'$L_z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              ylabel=r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              xrange=[0.,3600./220.],
                              yrange=[0.,500./220.],
                              onedhists=True,
                              bins=41,
                              levels=levels,retAxes=True)
        axScatter.set_xlim(0.,3600./220.)
        axScatter.set_ylim(0.,500./220.)
        axScatter.set_xlabel(r'$L_z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axScatter.set_ylabel(r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axHistx.set_xlim( axScatter.get_xlim() )
        axHisty.set_ylim( axScatter.get_ylim() )
        #Calculate locus of 6 kpc pericenter
        nlzs= 1001
        plzs= numpy.linspace(0.,6./8.,nlzs)
        pjrs= numpy.zeros(nlzs)
        for ii in range(nlzs):
            pjrs[ii]= aA(6./8.,0.,plzs[ii]/6.*8.,0.,0.)[0]*ro*vo*_REFR0*_REFV0
        bovy_plot.bovy_plot(plzs*ro*vo*_REFR0*_REFV0/220.,
                            pjrs/220.,'k--',overplot=True)
        plzs= numpy.linspace(11./8.,2.,nlzs)
        pjrs= numpy.zeros(nlzs)
        for ii in range(nlzs):
            pjrs[ii]= aA(11./8.,0.,plzs[ii]/11.*8.,0.,0.)[0]*ro*vo*_REFR0*_REFV0
        bovy_plot.bovy_plot(plzs*ro*vo*_REFR0*_REFV0/220.,
                            pjrs/220.,'k--',overplot=True)
    elif options.type.lower() == 'jrjz':
        axScatter, axHistx, axHisty= bovy_plot.scatterplot(jr/220.,jz/220.,color='k',marker=',',ls='none',
                              xlabel=r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              ylabel=r'$J_Z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$',
                              xrange=[0.,500./220.],
                              yrange=[0.,250./220.],
                              bins=41,
                              onedhists=True,
                              levels=levels,
                                                           retAxes=True)
        axScatter.set_xlim(0.,500./220.)
        axScatter.set_ylim(0.,250./220.)
        axScatter.set_ylabel(r'$J_Z\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axScatter.set_xlabel(r'$J_R\ (220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$')
        axHistx.set_xlim( axScatter.get_xlim() )
        axHisty.set_ylim( axScatter.get_ylim() )
    #if options.sample == 'g':
    #    bovy_plot.bovy_text(r'$\mathrm{G\!-\!type\ dwarfs}$',top_right=True,size=16.)
    #elif options.sample == 'k':
    #    bovy_plot.bovy_text(r'$\mathrm{K\!-\!type\ dwarfs}$',top_right=True,size=16.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Пример #12
0
def plotVelPDFs(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile1
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
    if os.path.exists(args[1]):#Load savefile
        savefile= open(args[1],'rb')
        densfits= pickle.load(savefile)
        savefile.close()
    #Uncertainties are in savefile3 and 4
    if len(args) > 3 and os.path.exists(args[3]):
        savefile= open(args[3],'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
        denserrors= True
    else:
        denssamples= None
        denserrors= False
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
        velerrors= True
    else:
        velsamples= None            
        velerrors= False
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'zfunc' \
            or options.type.lower() == 'afefeh':
        plotthis= []
        errors= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    if options.kde: allsamples= []
    sausageFehAfe= [options.feh,options.afe]#-0.15,0.075]#[[-0.85,0.425],[-0.45,0.275],[-0.15,0.075]]
    if options.subtype.lower() == 'sausage':
        sausageSamples= []
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if not (numpy.fabs(tightbinned.feh(ii)-sausageFehAfe[0])< 0.01 and numpy.fabs(tightbinned.afe(jj) - sausageFehAfe[1]) < 0.01):
                continue
            thisdensfit= densfits[afeindx+fehindx*binned.npixafe()]
            thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            if options.velmodel.lower() == 'hwr':
                thisplot=[tightbinned.feh(ii),
                              tightbinned.afe(jj),
                              numpy.exp(thisvelfit[1]),
                              numpy.exp(thisvelfit[4]),
                              len(data),
                              thisvelfit[2],
                              thisvelfit[3]]
                #Als find min and max z for this data bin, and median
                zsorted= sorted(numpy.fabs(data.zc+_ZSUN))
                zmin= zsorted[int(numpy.ceil(0.16*len(zsorted)))]
                zmax= zsorted[int(numpy.floor(0.84*len(zsorted)))]
                thisplot.extend([zmin,zmax,numpy.mean(numpy.fabs(data.zc+_ZSUN))])
                #Errors
                if velerrors:
                    thesesamples= velsamples[afeindx+fehindx*binned.npixafe()]
                break
    #Now plot
    if options.type.lower() == 'slopequad':
        plotx= numpy.array([thesesamples[ii][3] for ii in range(len(thesesamples))])
        ploty= numpy.array([thesesamples[ii][2] for ii in range(len(thesesamples))])
        xrange= [-10.,10.]
        yrange= [-20.,20.]
        xlabel=r'$\frac{\mathrm{d}^2 \sigma_z}{\mathrm{d} z^2}(z_{1/2})\ [\mathrm{km}\ \mathrm{s}^{-1}\ \mathrm{kpc}^{-2}]$'
        ylabel=r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type.lower() == 'slopehsm':
        ploty= numpy.array([thesesamples[ii][2] for ii in range(len(thesesamples))])
        plotx= numpy.exp(-numpy.array([thesesamples[ii][4] for ii in range(len(thesesamples))]))
        xrange= [0.,0.3]
        yrange= [-20.,20.]
        xlabel=r'$h^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
        ylabel=r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type.lower() == 'slopesz':
        ploty= numpy.array([thesesamples[ii][2] for ii in range(len(thesesamples))])
        plotx= numpy.exp(numpy.array([thesesamples[ii][1] for ii in range(len(thesesamples))]))
        xrange= [0.,60.]
        yrange= [-20.,20.]
        xlabel=r'$\sigma_z(z_{1/2}) [\mathrm{km\ s}^{-1}$'
        ylabel=r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type.lower() == 'szhsm':
        plotx= numpy.exp(-numpy.array([thesesamples[ii][4] for ii in range(len(thesesamples))]))
        ploty= numpy.exp(numpy.array([thesesamples[ii][1] for ii in range(len(thesesamples))]))
        yrange= [0.,60.]
        xrange= [0.,0.3]
        xlabel=r'$h^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
        ylabel=r'$\sigma_z(z_{1/2}) [\mathrm{km\ s}^{-1}$'
    bovy_plot.bovy_print()
    axScatter, axHistx, axHisty= bovy_plot.scatterplot(plotx,ploty,'k,',
                                                       onedhists=True,
                                                       bins=31,
                                                       xlabel=xlabel,ylabel=ylabel,
                                                       xrange=xrange,
                                                       onedhistynormed=True,
                                                       yrange=yrange,
                                                       retAxes=True)
    if options.type.lower() == 'slopequad':
        #Also add `quadratic term = 0' to vertical histogram
        ploty= ploty[(numpy.fabs(plotx) < 0.5)]
        histy, edges, patches= axHisty.hist(ploty,
                                            bins=51,
                                            orientation='horizontal',
                                            weights=numpy.ones(len(ploty))/float(len(ploty))/2.,
                                            histtype='step',
                                            range=sorted(yrange),
                                            color='0.6',
                                            lw=2.)
    #Label
    bovy_plot.bovy_text(r'$[\mathrm{Fe/H}]\ =\ %.2f$' % options.feh
                        +'\n'
                        +r'$[\alpha/\mathrm{Fe}]\ =\ %.3f$' % options.afe,
                        top_right=True,
                        size=18)                     
    bovy_plot.bovy_end_print(options.plotfile)
Пример #13
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
def main(args: Optional[list] = None, opts: Optional[Namespace] = None):
    """Fit MWPotential2014 Script Function.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    plt.figure(figsize=(6, 4))
    dum = bovy_plot.bovy_hist(
        apal5s, range=[0.0, 10.0], lw=2.0, bins=51, histtype="step", normed=True,
    )
    plt.savefig("figures/kuepper_samples_prior.pdf")
    plt.close()
Пример #15
0
def plot_fehafe(basefilename):
    #First read the sample
    data= apread.rcsample()
    data= data[data['SNR'] >= 70.]
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #R and z ranges to plot
    Rmins= [5.,7.,9.]
    Rmaxs= [7.,9.,11.]
    zmins= [0.,0.5,1.]
    zmaxs= [0.5,1.,2.]
    nRbins= len(Rmins)
    nzbins= len(zmins)
    for ii in range(nRbins):
        for jj in range(nzbins):
            #Cut data to relevant range
            tindx= (data['RC_GALR'] > Rmins[ii])\
                *(data['RC_GALR'] <= Rmaxs[ii])\
                *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\
                *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj])
            tdata= data[tindx]
            bovy_plot.bovy_print()
            if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX:
                bovy_plot.scatterplot(tdata['METALS'],
                                      tdata['ALPHAFE'],
                                      'k.',
                                      levels=[0.68,.90],
                                      #special.erf(numpy.arange(1,3)/numpy.sqrt(2.)),
                                      xrange=[-1.2,0.7],
                                      yrange=[-0.12,0.42],
                                      xlabel=r'$[\mathrm{Fe/H}]$',
                                      ylabel=r'$[\alpha/\mathrm{H}]$',
                                      onedhists=True,bins=31,onedhistsbins=21)
            else:
                axScatter,axHistx, axHisty=\
                    bovy_plot.bovy_plot(tdata['METALS'],
                                        tdata['ALPHAFE'],
                                        'k.',
                                        xrange=[-1.2,0.7],
                                        yrange=[-0.12,0.42],
                                        xlabel=r'$[\mathrm{Fe/H}]$',
                                        ylabel=r'$[\alpha/\mathrm{H}]$',
                                        onedhists=True,bins=21)
            if _ADDBOVYRIX:
                add_bovy_rix(axScatter,Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])
            if not _NOLINE:
                #Overplot ridge line
                bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)],
                                    '-',lw=2.,color='y',overplot=True)
            bovy_plot.bovy_text(r'$%i < R / \mathrm{kpc} \leq %i$' % (Rmins[ii],Rmaxs[ii]) +'\n'+r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]),
                                    top_left=True,size=16.)
            bovy_plot.bovy_end_print(basefilename+'_%iR%i_%.1fz%.1f.' % (Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])+_EXT)
    #Plot z bins only
    zmins= [0.,0.5,1.,2.]
    zmaxs= [0.5,1.,2.,4.]
    nzbins= len(zmins)
    for jj in range(nzbins):
        #Cut data to relevant range
        tindx= (data['RC_GALR'] > 4.)\
            *(data['RC_GALR'] <= 9.)\
                *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\
                *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj])
        tdata= data[tindx]
        bovy_plot.bovy_print()
        if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX:
            bovy_plot.scatterplot(tdata['METALS'],
                                  tdata['ALPHAFE'],
                                  'k.',
                                  levels=[0.68,.90],
                                  xrange=[-1.2,0.7],
                                  yrange=[-0.12,0.42],
                                  xlabel=r'$[\mathrm{Fe/H}]$',
                                  ylabel=r'$[\alpha/\mathrm{H}]$',
                                  onedhists=True,bins=31,onedhistsbins=31)
        else:
            axScatter,axHistx, axHisty=\
                bovy_plot.bovy_plot(tdata['METALS'],
                                    tdata['ALPHAFE'],
                                    'k.',
                                    xrange=[-1.2,0.7],
                                    yrange=[-0.12,0.42],
                                    xlabel=r'$[\mathrm{Fe/H}]$',
                                    ylabel=r'$[\alpha/\mathrm{H}]$',
                                    onedhists=True,bins=21)
        if _ADDBOVYRIX:
            add_bovy_rix(axScatter,4.,9.,zmins[jj],zmaxs[jj])
        #Overplot ridge line
        bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)],
                            '-',lw=2.,color='y',overplot=True)
        bovy_plot.bovy_text(r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]),
                                top_left=True,size=16.)
        bovy_plot.bovy_end_print(basefilename+'_%.1fz%.1f.' % (zmins[jj],zmaxs[jj])+_EXT)
    #Plot scatter in the high-alpha sequence
    #Histograms in 3 R bins
    bovy_plot.bovy_print(fig_width=7.)
    overplot= False
    colors= ['y','k','r']
    labelposx= 0.235
    labelposy= [13.,11.,9.]
    for ii in range(nRbins):
        tindx= (data['RC_GALR'] > Rmins[ii])\
            *(data['RC_GALR'] <= Rmaxs[ii])\
            *(numpy.fabs(data['RC_GALZ']) <= 3.)
        tdata= data[tindx]
        hindx= determine_highalpha(tdata)
        tdata= tdata[hindx]
        bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']),
                            color=colors[ii],histtype='step',
                            bins=28,range=[-0.275,0.25],yrange=[0.,15.],
                            weights=numpy.ones(len(tdata)),
                            xlabel=r'$\delta[\alpha\mathrm{/Fe}]$',
                            overplot=overplot,normed=True)
        dafe= tdata['ALPHAFE']-ridge1(tdata['METALS'])
        dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)]
        txa, txm, txc= run_xd(dafe)
        print txm.flatten(), numpy.sqrt(txc.flatten()), txa[0]*len(dafe)
        bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2.,
                            color=colors[ii],overplot=True)
        bovy_plot.bovy_text(labelposx,labelposy[ii],
                            r'$%i < R \leq %i: \sigma = %.3f$' % (Rmins[ii],Rmaxs[ii],numpy.sqrt(txc[0,0,0])),
                            size=16.,color=colors[ii],ha='right')
        overplot= True
    bovy_plot.bovy_end_print(basefilename+'_afefehhist.%s' % _EXT)
    #High SN
    bovy_plot.bovy_print(fig_width=7.)
    overplot= False
    for ii in range(nRbins):
        tindx= (data['RC_GALR'] > Rmins[ii])\
            *(data['RC_GALR'] <= Rmaxs[ii])\
            *(numpy.fabs(data['RC_GALZ']) <= 3.)\
            *(data['SNR'] >= 150.)
        tdata= data[tindx]
        hindx= determine_highalpha(tdata)
        tdata= tdata[hindx]
        bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']),
                            color=colors[ii],histtype='step',
                            bins=19,range=[-0.275,0.15],yrange=[0.,19.5],
                            weights=numpy.ones(len(tdata)),
                            xlabel=r'$\delta[\alpha\mathrm{/Fe}]$',
                            normed=True,
                            overplot=overplot)
        dafe= tdata['ALPHAFE']-ridge1(tdata['METALS'])
        dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)]
        txa, txm, txc= run_xd(dafe)
        print txm.flatten(), numpy.sqrt(txc.flatten())
        bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2.,
                            color=colors[ii],overplot=True)
        overplot= True
    bovy_plot.bovy_end_print(basefilename+'_afefehhist_highsn.%s' % _EXT)
    return None
Пример #16
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)
Пример #17
0
def compareMagFluxFits(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')
            params.append(pickle.load(savefile))
            savefile.close()
        else:
            print filename + " does not exist ..."
            print "Returning ..."
            return
    if options.plottype == 'AA':
        ys = []
        xs = []
        for key in params[1].keys():
            try:
                ys.append(params[0][key]['logA'] / 2.)
                xs.append(params[1][key]['logA'] / 2.)
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        ys = xs - ys - nu.log(nu.log(10.) / 2.5)
        xrange = [-9.21 / 2., 0.]
        yrange = [-.25, .25]
        xlabel = r'$\log A^{\mathrm{flux}}_' + options.band + r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log A^{\mathrm{flux}}_' + options.band + r'-\log A^{\mathrm{mag}}_' + options.band + r'- \log\left(\frac{\log 10}{2.5}\right)$'
    elif options.plottype == 'gg':
        ys = []
        xs = []
        for key in params[1].keys():
            try:
                ys.append(params[0][key]['gamma'])
                xs.append(params[1][key]['gamma'])
            except KeyError:
                continue
        xs = nu.array(xs).reshape(len(xs))
        ys = nu.array(ys).reshape(len(xs))
        print len(xs)
        ys = xs - ys
        xrange = [0., 1.2]
        yrange = [-.25, .25]
        xlabel = r'$\gamma^{\mathrm{flux}}_' + options.band + r'\ \mathrm{(power-law\ exponent)}$'
        ylabel = r'$\gamma^{\mathrm{flux}}_' + options.band + r'- \gamma^{\mathrm{mag}}_' + options.band + '$'
    elif options.plottype == 'loglike2':
        ys = []
        xs = []
        nepochs = []
        cnt = 0
        for key in params[1].keys():
            #cnt+= 1
            #print cnt
            #if cnt > 10: break
            #Get the number of epochs
            v = VarQso(os.path.join('../data/s82qsos/', key))
            try:
                ys.append(params[0][key]['loglike'] -
                          v.nepochs(options.band) * nu.log(nu.log(10.) / 2.5))
                nepochs.append(v.nepochs(options.band))
                xs.append(params[1][key]['loglike'])
            except KeyError:
                continue
        xs = -nu.array(xs).reshape(len(xs))
        ys = -nu.array(ys).reshape(len(xs))
        nepochs = nu.array(nepochs).reshape(len(nepochs))
        ys /= nepochs
        xs /= nepochs
        ys = xs - ys
        xrange = [-3., 0.]
        yrange = [-.1, .1]
        xlabel = r'$\log \mathcal{L}^{\mathrm{flux}}_{' + options.band + r',\mathrm{red}}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel = r'$\log \mathcal{L}^{\mathrm{flux}}_{' + options.band + r',\mathrm{red}}- \log \mathcal{L}^{\mathrm{mag}}_{' + options.band + ',\mathrm{red}}' + r'- \log\left(\frac{\log 10}{2.5}\right)$'
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(xs,
                          ys,
                          'k,',
                          onedhists=True,
                          yrange=yrange,
                          xrange=xrange,
                          bins=31,
                          xlabel=xlabel,
                          ylabel=ylabel)
    bovy_plot.bovy_plot(nu.array(xrange), [0., 0.], '0.5', overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Пример #18
0
def plot_rovo(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()
    if _ANALYTIC:  #Calculate by fixing everything except for Ro anv vo
        options = plot_pdfs.set_options(None)
        nros = 15
        noos = 15
        ros = numpy.linspace(7., 13., nros)
        oos = numpy.linspace(20., 30., noos)
        ll = numpy.zeros((noos, nros))
        for ii in range(noos):
            if not _MULTI is None:
                theseparamss = []
                for jj in range(nros):
                    theseparams = copy.copy(params)
                    theseparams[0] = oos[ii] * ros[jj] / _REFV0
                    theseparams[1] = ros[jj] / _REFR0
                    theseparamss.append(theseparams)
                thisll = multi.parallel_map(
                    (lambda x: numpy.sum(
                        logl.logl(init=theseparamss[x], options=options))),
                    range(nros),
                    numcores=numpy.amin(
                        [nros, _MULTI,
                         multiprocessing.cpu_count()]))
                ll[ii, :] = thisll
            else:
                for jj in range(nros):
                    theseparams = copy.copy(params)
                    theseparams[0] = oos[ii] * ros[jj] / _REFV0
                    theseparams[1] = ros[jj] / _REFR0
                    ll[ii, jj] = numpy.sum(
                        logl.logl(init=theseparams, options=options))
        #Normalize
        ll -= logsumexp(ll)
        ll = numpy.exp(ll)
        levels = list(special.erf(0.5 * numpy.arange(1, 4)))
        bovy_plot.bovy_dens2d(
            ll.T,
            origin='lower',
            levels=levels,
            xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
            ylabel=r'$R_0\ [\mathrm{kpc}]$',
            xrange=[20., 35.],
            yrange=[7., 13.],
            contours=True,
            cntrcolors='k',
            onedhists=True,
            cmap='gist_yarg')
    else:
        vos = numpy.array([s[0] for s in params]) * _REFV0
        ros = numpy.array([s[1] for s in params]) * _REFR0
        bovy_plot.bovy_print()
        levels = list(special.erf(0.5 * numpy.arange(1, 4)))
        levels.append(1.01)  #HACK to not plot outliers
        bovy_plot.scatterplot(
            vos / ros,
            ros,
            'k,',
            levels=levels,
            xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
            ylabel=r'$R_0\ [\mathrm{kpc}]$',
            bins=31,
            xrange=[200. / 8., 250. / 8.],
            yrange=[7., 9.],
            contours=True,
            cntrcolors='k',
            onedhists=True,
            cmap='gist_yarg')
    bovy_plot.bovy_end_print(plotfilename)
def plot_mcmc_c(samples,
                fitvoro,
                cs,
                bf_params,
                add_families=False,
                savefig=None):
    """Plot MCMC C-Parameter.

    Parameters
    ----------
    samples : list
    fitvoro : bool
    add_families : bool, optional

    Returns
    -------
    None

    """
    if add_families:
        st0 = np.random.get_state()
        np.random.seed(1)
        with open("output/mwpot14varyc-samples.pkl", "rb") as savefile:
            pot_samples = pickle.load(savefile)
        rndindices = np.random.permutation(pot_samples.shape[1])
        pot_params = np.zeros((8, 32))
        for ii in range(32):
            pot_params[:, ii] = pot_samples[:, rndindices[ii]]

    cindx = 9 if fitvoro else 7

    cmap = cm.viridis
    levels = list(special.erf(np.arange(1, 3) / np.sqrt(2.0)))
    levels.append(1.01)

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

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

    fig = plt.figure(figsize=(16 + 2 * fitvoro, 4))
    gs = gridspec.GridSpec(1, 5 + 2 * fitvoro, wspace=0.015)
    plt.subplot(gs[0])
    bovy_plot.scatterplot(
        samples[0],
        samples[cindx],
        ",",
        gcf=True,
        bins=31,
        cmap=cmap,
        cntrcolors="0.6",
        xrange=[0.0, 0.99],
        yrange=[0.0, 4.0],
        levels=levels,
        xlabel=r"$f_d$",
        ylabel=r"$c/a$",
        zorder=1,
    )
    bovy_plot.bovy_plot([bp[0] for bp in bf_params], cs, "w-", overplot=True)
    if add_families:
        fm_kw = {
            "color": "w",
            "marker": "x",
            "ls": "none",
            "ms": 4.0,
            "mew": 1.2,
        }
        bovy_plot.bovy_plot(pot_params[0],
                            pot_params[7],
                            overplot=True,
                            **fm_kw)
    axes_white()
    plt.subplot(gs[1])
    bovy_plot.scatterplot(
        samples[1],
        samples[cindx],
        ",",
        gcf=True,
        bins=31,
        cmap=cmap,
        cntrcolors="0.6",
        xrange=[0.0, 0.99],
        yrange=[0.0, 4.0],
        levels=levels,
        xlabel=r"$f_h$",
    )
    bovy_plot.bovy_plot([bp[1] for bp in bf_params], cs, "w-", overplot=True)
    if add_families:
        bovy_plot.bovy_plot(pot_params[1],
                            pot_params[7],
                            overplot=True,
                            **fm_kw)
    nullfmt = NullFormatter()
    plt.gca().yaxis.set_major_formatter(nullfmt)
    axes_white()
    plt.subplot(gs[2])
    bovy_plot.scatterplot(
        np.exp(samples[2]) * REFR0,
        samples[cindx],
        ",",
        gcf=True,
        bins=21,
        levels=levels,
        xrange=[2.0, 4.49],
        yrange=[0.0, 4.0],
        cmap=cmap,
        cntrcolors="0.6",
        xlabel=r"$h_R\,(\mathrm{kpc})$",
    )
    bovy_plot.bovy_plot(
        [np.exp(bp[2]) * REFR0 for bp in bf_params],
        cs,
        "w-",
        overplot=True,
    )
    if add_families:
        bovy_plot.bovy_plot(
            np.exp(pot_params[2]) * REFR0,
            pot_params[7],
            overplot=True,
            **fm_kw,
        )
    nullfmt = NullFormatter()
    plt.gca().yaxis.set_major_formatter(nullfmt)
    axes_white()
    plt.subplot(gs[3])
    bovy_plot.scatterplot(
        np.exp(samples[3]) * REFR0 * 1000.0,
        samples[cindx],
        ",",
        gcf=True,
        bins=26,
        levels=levels,
        xrange=[150.0, 445.0],
        yrange=[0.0, 4.0],
        cmap=cmap,
        cntrcolors="0.6",
        xlabel=r"$h_z\,(\mathrm{pc})$",
    )
    bovy_plot.bovy_plot(
        [np.exp(bp[3]) * REFR0 * 1000.0 for bp in bf_params],
        cs,
        "w-",
        overplot=True,
    )
    if add_families:
        bovy_plot.bovy_plot(
            np.exp(pot_params[3]) * REFR0 * 1000.0,
            pot_params[7],
            overplot=True,
            **fm_kw,
        )
    nullfmt = NullFormatter()
    plt.gca().yaxis.set_major_formatter(nullfmt)
    plt.gca().xaxis.set_ticks([200.0, 300.0, 400.0])
    axes_white()
    plt.subplot(gs[4])
    bovy_plot.scatterplot(
        np.exp(samples[4]) * REFR0,
        samples[cindx],
        ",",
        gcf=True,
        bins=26,
        levels=levels,
        xrange=[0.0, 39.0],
        yrange=[0.0, 4.0],
        cmap=cmap,
        cntrcolors="0.6",
        xlabel=r"$r_s\,(\mathrm{kpc})$",
    )
    bovy_plot.bovy_plot(
        [np.exp(bp[4]) * REFR0 for bp in bf_params],
        cs,
        "w-",
        overplot=True,
    )
    if add_families:
        bovy_plot.bovy_plot(
            np.exp(pot_params[4]) * REFR0,
            pot_params[7],
            overplot=True,
            **fm_kw,
        )
    nullfmt = NullFormatter()
    plt.gca().yaxis.set_major_formatter(nullfmt)
    axes_white()

    if fitvoro:
        plt.subplot(gs[5])
        bovy_plot.scatterplot(
            samples[7] * REFR0,
            samples[cindx],
            ",",
            gcf=True,
            bins=26,
            levels=levels,
            xrange=[7.1, 8.9],
            yrange=[0.0, 4.0],
            cmap=cmap,
            cntrcolors="0.6",
            xlabel=r"$R_0\,(\mathrm{kpc})$",
        )
        nullfmt = NullFormatter()
        plt.gca().yaxis.set_major_formatter(nullfmt)
        axes_white()
        plt.subplot(gs[6])
        bovy_plot.scatterplot(
            samples[8] * REFV0,
            samples[cindx],
            ",",
            gcf=True,
            bins=26,
            levels=levels,
            xrange=[200.0, 250.0],
            yrange=[0.0, 4.0],
            cmap=cmap,
            cntrcolors="0.6",
            xlabel=r"$V_c(R_0)\,(\mathrm{km\,s}^{-1})$",
        )
        nullfmt = NullFormatter()
        plt.gca().yaxis.set_major_formatter(nullfmt)
        axes_white()

    if savefig is not None:
        fig.savefig(savefig)

    return None
Пример #20
0
def plot_afefeh(plotfilename):
    # Load the data
    data= define_rcsample.get_rcsample()
    # Plot the data
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(data[define_rcsample._FEHTAG],
                          data[define_rcsample._AFETAG],
                          'k.',ms=.8,
                          levels=special.erf(numpy.arange(1,2)/numpy.sqrt(2.)),
                          xrange=[-1.,0.4],
                          yrange=[-0.15,0.35],
                          xlabel=r'$[\mathrm{Fe/H}]$',
                          ylabel=define_rcsample._AFELABEL)
    # Overplot sub-samples
    # low alpha, low feh
    lowfeh= define_rcsample._lowlow_lowfeh(0.)
    highfeh= define_rcsample._lowlow_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._lowlow_lowafe(lowfeh),
                                 define_rcsample._lowlow_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._lowlow_lowafe(highfeh),
                                   define_rcsample._lowlow_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._lowlow_lowafe(lowfeh),
                                  define_rcsample._lowlow_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._lowlow_highafe(lowfeh),
                                  define_rcsample._lowlow_highafe(highfeh)],
                'k--',lw=2.)
    # high alpha
    lowfeh= define_rcsample._highalpha_lowfeh(0.)
    highfeh= define_rcsample._highalpha_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._highalpha_lowafe(lowfeh),
                                 define_rcsample._highalpha_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._highalpha_lowafe(highfeh),
                                   define_rcsample._highalpha_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highalpha_lowafe(lowfeh),
                                  define_rcsample._highalpha_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highalpha_highafe(lowfeh),
                                  define_rcsample._highalpha_highafe(highfeh)],
                'k--',lw=2.)
    # solar
    lowfeh= define_rcsample._solar_lowfeh(0.)
    highfeh= define_rcsample._solar_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._solar_lowafe(lowfeh),
                                 define_rcsample._solar_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._solar_lowafe(highfeh),
                                   define_rcsample._solar_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._solar_lowafe(lowfeh),
                                  define_rcsample._solar_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._solar_highafe(lowfeh),
                                  define_rcsample._solar_highafe(highfeh)],
                'k--',lw=2.)
    # high [Fe/H]
    lowfeh= define_rcsample._highfeh_lowfeh(0.)
    highfeh= define_rcsample._highfeh_highfeh(0.)
    pyplot.plot([lowfeh,lowfeh],[define_rcsample._highfeh_lowafe(lowfeh),
                                 define_rcsample._highfeh_highafe(lowfeh)],
                'k--',lw=2.)
    pyplot.plot([highfeh,highfeh],[define_rcsample._highfeh_lowafe(highfeh),
                                   define_rcsample._highfeh_highafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highfeh_lowafe(lowfeh),
                                  define_rcsample._highfeh_lowafe(highfeh)],
                'k--',lw=2.)
    pyplot.plot([lowfeh,highfeh],[define_rcsample._highfeh_highafe(lowfeh),
                                  define_rcsample._highfeh_highafe(highfeh)],
                'k--',lw=2.)
    # Label them
    bovy_plot.bovy_text(-0.4,0.265,r'$\mathrm{high}\ [\alpha/\mathrm{Fe}]$',
                         size=15.,backgroundcolor='w')
    bovy_plot.bovy_text(-0.975,0.05,r'$\mathrm{low\ [Fe/H]}$',
                         size=15.,backgroundcolor='w')
    bovy_plot.bovy_text(0.,-0.125,r'$\mathrm{high\ [Fe/H]}$',
                         size=15.,backgroundcolor='w')
    bovy_plot.bovy_text(-0.225,-0.125,r'$\mathrm{solar}$',
                         size=15.,backgroundcolor='w')
    # Loci
    if False:
        haloc= define_rcsample.highalphalocus()
        bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'k-',lw=2.,overplot=True)
        haloc= define_rcsample.lowalphalocus()
        bovy_plot.bovy_plot(haloc[:,0],haloc[:,1],'k-',lw=2.,overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Пример #21
0
def plotXDall(parser):
    nu.random.seed(1)
    (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
    if os.path.exists(args[1]):
        savefile = open(args[1], 'rb')
        starxamp = pickle.load(savefile)
        starxmean = pickle.load(savefile)
        starxcovar = pickle.load(savefile)
        savefile.close()
    else:
        print args[1] + " does not exist ..."
        print "Returning ..."
        return
    if os.path.exists(args[2]):
        savefile = open(args[2], 'rb')
        rrxamp = pickle.load(savefile)
        rrxmean = pickle.load(savefile)
        rrxcovar = pickle.load(savefile)
        savefile.close()
    else:
        print args[2] + " does not exist ..."
        print "Returning ..."
        return
    if options.nsamplesstar is None: options.nsamplesstar = options.nsamples
    if options.nsamplesrrlyrae is None:
        options.nsamplesrrlyrae = options.nsamples
    #Load XD object in xdtarget
    xdt = xdtarget.xdtarget(amp=xamp, mean=xmean, covar=xcovar)
    out = xdt.sample(nsample=options.nsamples)
    xdt = xdtarget.xdtarget(amp=starxamp, mean=starxmean, covar=starxcovar)
    starout = xdt.sample(nsample=options.nsamplesstar)
    xdt = xdtarget.xdtarget(amp=rrxamp, mean=rrxmean, covar=rrxcovar)
    rrout = xdt.sample(nsample=options.nsamplesrrlyrae)
    #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
    #stars
    if options.expd1: starxs = nu.exp(starout[:, options.d1])
    elif not options.divided1 is None:
        starxs = starout[:, options.d1] / options.divided1
    else:
        starxs = starout[:, options.d1]
    if options.expd2: starys = nu.exp(starout[:, options.d2])
    elif not options.divided2 is None:
        starys = starout[:, options.d2] / options.divided2
    else:
        starys = starout[:, options.d2]
    if options.type == 'DRW':
        #plot logA, logA = 0
        if options.d1 == 0 and options.d2 == 1:
            #Convert to logA
            starxs = (nu.log(2.) + starxs +
                      nu.log(1. - nu.exp(-1. / nu.exp(starys)))) / 2.
        elif options.d1 == 1 and options.d2 == 0:
            #Convert to logA
            starys = (nu.log(2.) + starys +
                      nu.log(1. - nu.exp(-1. / nu.exp(starxs)))) / 2.
        else:
            print "d1 and d2 have to be 0 or 1 (and not the same!) ..."
            print "Returning ..."
            return
    #RR Lyrae
    if options.expd1: rrxs = nu.exp(rrout[:, options.d1])
    elif not options.divided1 is None:
        rrxs = rrout[:, options.d1] / options.divided1
    else:
        rrxs = rrout[:, options.d1]
    if options.expd2: rrys = nu.exp(rrout[:, options.d2])
    elif not options.divided2 is None:
        rrys = rrout[:, options.d2] / options.divided2
    else:
        rrys = rrout[:, options.d2]
    if options.type == 'DRW':
        #plot logA, logA = 0
        if options.d1 == 0 and options.d2 == 1:
            #Convert to logA
            rrxs = (nu.log(2.) + rrxs +
                    nu.log(1. - nu.exp(-1. / nu.exp(rrys)))) / 2.
        elif options.d1 == 1 and options.d2 == 0:
            #Convert to logA
            rrys = (nu.log(2.) + rrys +
                    nu.log(1. - nu.exp(-1. / nu.exp(rrxs)))) / 2.
        else:
            print "d1 and d2 have to be 0 or 1 (and not the same!) ..."
            print "Returning ..."
            return
    #Plot
    xrange = [options.xmin, options.xmax]
    yrange = [options.ymin, options.ymax]
    data = sc.array([xs, ys]).T
    bins = int(round(0.3 * sc.sqrt(options.nsamples)))
    hist, edges = sc.histogramdd(data, bins=bins, range=[xrange, yrange])
    #Censor hist ASSUMES gamma=[0.,1.2], logA=[-9.21/2.,0.] for powerlawSF
    x = nu.zeros((bins, bins))
    y = nu.zeros((bins, bins))
    for bb in range(bins):
        x[:, bb] = nu.linspace(options.xmin, options.xmax, bins)
        y[bb, :] = nu.linspace(options.ymin, options.ymax, bins)
    #mask
    if options.type == 'powerlawSF':
        hist[(y < 0.1) * (x > -3.) * (x < -1.5)] = nu.nan
        hist[(x < -3.)] = nu.nan
        hist[(x > -2.) * (y < (0.25 * x + 0.6))] = nu.nan
        onedhistyweights = nu.ones(len(ys)) / 100.
    elif options.type == 'DRW':
        hist[(y < (-4.223 * (x + 2) - 10))] = nu.nan
        hist[(y < -4.153) * (y < (58.47 * (x + 2.1) - 10.))] = nu.nan
        hist[(y > -4.153) * (y < (2.93 * x + 2.) - 1.)] = nu.nan
        onedhistyweights = nu.ones(len(ys)) / 2500.
    bovy_plot.bovy_print()
    #First just plot contours
    cdict = {
        'red': ((.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
        'green': ((.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
        'blue': ((.0, 1.0, 1.0), (1.0, 1.0, 1.0))
    }
    allwhite = matplotlib.colors.LinearSegmentedColormap(
        'allwhite', cdict, 256)
    bovy_plot.scatterplot(xs,
                          ys,
                          'b,',
                          onedhists=True,
                          bins=bins,
                          cmap=allwhite,
                          onedhistynormed=False,
                          onedhistyweights=onedhistyweights,
                          xrange=xrange,
                          yrange=yrange,
                          onedhistec='b',
                          xlabel=options.xlabel,
                          ylabel=options.ylabel)
    bovy_plot.scatterplot(starxs,
                          starys,
                          'k,',
                          onedhists=True,
                          bins=bins,
                          cmap=allwhite,
                          xrange=xrange,
                          yrange=yrange,
                          overplot=True)
    bovy_plot.scatterplot(rrxs,
                          rrys,
                          'r,',
                          onedhists=True,
                          bins=bins,
                          cmap=allwhite,
                          onedhistec='r',
                          xrange=xrange,
                          yrange=yrange,
                          overplot=True)
    hist /= nu.nansum(hist)
    #Custom colormap
    cdict = {
        'red': ((.0, 1.0, 1.0), (1.0, .0, .0)),
        'green': ((0.0, 1.0, 1.0), (1.0, .0, .0)),
        'blue': ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0))
    }
    my_cmap = matplotlib.colors.LinearSegmentedColormap(
        'my_colormap', cdict, 256)
    bovy_plot.scatterplot(xs,
                          ys,
                          'b,',
                          onedhists=False,
                          contours=False,
                          levels=[1.01],
                          bins=bins,
                          cmap=my_cmap,
                          hist=hist,
                          edges=edges,
                          onedhistynormed=False,
                          onedhistyweights=onedhistyweights,
                          xrange=xrange,
                          yrange=yrange,
                          overplot=True)
    #Stars
    data = sc.array([starxs, starys]).T
    hist, edges = sc.histogramdd(data, bins=bins, range=[xrange, yrange])
    if options.type == 'powerlawSF':
        hist[(x > -2.5)] = nu.nan
        hist[(x < -2.5) * (y > (-.19 * (x + 2.5)))] = nu.nan
    elif options.type == 'DRW':
        hist[(y >= (-4.223 * (x + 2) - 10))] = nu.nan
    hist /= nu.nansum(hist)
    bovy_plot.scatterplot(
        starxs,
        starys,
        'k,',
        onedhists=True,
        contours=False,
        levels=[1.01],  #HACK such that outliers aren't plotted
        bins=bins,
        hist=hist,
        edges=edges,
        xrange=xrange,
        yrange=yrange,
        overplot=True)
    #RR Lyrae
    data = sc.array([rrxs, rrys]).T
    hist, edges = sc.histogramdd(data, bins=bins, range=[xrange, yrange])
    if options.type == 'powerlawSF':
        hist[(x < -2.5)] = nu.nan
        hist[(x > -2.5) * (y > ((x + 2.5) / 1.5)**9. * 1.15 + 0.1)] = nu.nan
        #hist[(x > -2.5)*(y > (.25*x+.6))]= nu.nan
    elif options.type == 'DRW':
        hist[(y < -4.153) * (y >=
                             (58.47 * (x + 2.1) - 10.)) * (y > -7.5)] = nu.nan
        hist[(y < -7.5) * (x < -2.1)] = nu.nan
        hist[(y > -4.153) * (y >= (2.93 * x + 2. - 1.5))] = nu.nan
    #Custom colormap
    cdict = {
        'red': ((.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
        'green': ((0.0, 1.0, 1.0), (1.0, .0, .0)),
        'blue': ((0.0, 1.0, 1.0), (1.0, .0, .0))
    }
    my_cmap = matplotlib.colors.LinearSegmentedColormap(
        'my_colormap', cdict, 256)
    hist /= nu.nansum(hist)
    bovy_plot.scatterplot(
        rrxs,
        rrys,
        'r,',
        onedhists=False,
        contours=False,
        levels=[1.01],  #HACK such that outliers aren't plotted
        bins=bins,
        cmap=my_cmap,
        hist=hist,
        edges=edges,
        xrange=xrange,
        yrange=yrange,
        overplot=True)
    #Label
    if options.type == 'powerlawSF':
        bovy_plot.bovy_text(-4.4, 1.15, r'$\mathrm{F/G\ stars}$', color='k')
        bovy_plot.bovy_text(-4.4, 1.05, r'$\mathrm{QSOs}$', color='b')
        bovy_plot.bovy_text(-4.4, 0.95, r'$\mathrm{RR\ Lyrae}$', color='r')
    elif options.type == 'DRW':
        bovy_plot.bovy_text(-4.4, 2.88, r'$\mathrm{F/G\ stars}$', color='k')
        bovy_plot.bovy_text(-4.4, 1.76, r'$\mathrm{QSOs}$', color='b')
        bovy_plot.bovy_text(-4.4, .64, r'$\mathrm{RR\ Lyrae}$', color='r')
    bovy_plot.bovy_end_print(options.plotfilename)
Пример #22
0
def singleBandSampleExample(
    datafilename="SDSSJ000051.56+001202.5.fit", 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, 0.0]
            SF = covarFunc(gamma=0.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.0,
        gammas,
        "k,",
        ylabel=r"$\gamma$",
        xlabel=r"\log A",
        xrange=[-9.21 / 2.0, 0.0],
        yrange=[0.0, 1.25],
        bins=50,
        onedhists=True,
    )
    bovy_plot.bovy_end_print(basefilename + "_sample_2d.png")
Пример #23
0
def plot_fake_data(parser):
    """
    NAME:
       plot_fake_data
    PURPOSE:
       plot the fake data created by create_fake_data
    INPUT:
       parser - from optparse
    OUTPUT:
       stuff as specified by the options
    HISTORY:
       2011-04-20 - Written - Bovy (NYU)
    """
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        sys.exit(-1)
    #Set up DF
    dfc= dehnendf(beta=options.beta,profileParams=(options.rd,options.rs,options.so),correct=True,niter=20)
    #Open pickle
    picklefile= open(args[0],'rb')
    out= pickle.load(picklefile)
    picklefile.close()
    if not options.vlosdname is None:
        #Plot distribution of vlos vs. d
        vloss=nu.array([o.vlos(obs=[1.,0.,0.,0.,1.,0.],ro=1.,vo=1.) \
                            for o in out]).flatten()
        ds= nu.array([o.dist(obs=[1.,0.,0.],ro=1.) \
                          for o in out]).flatten()
        #Also calculate the expected relation
        ntheory= 1001
        dx= nu.linspace(0.,2.,ntheory)
        vtheory= nu.zeros(ntheory)
        l= options.los*_DEGTORAD
        for ii in range(ntheory):
            R= nu.sqrt(1.+dx[ii]**2.-2.*dx[ii]*nu.cos(l))
            if 1./nu.cos(l) < dx[ii] and nu.cos(l) > 0.:
                phi= nu.pi-m.asin(dx[ii]/R*nu.sin(l))
            else:
                phi= m.asin(dx[ii]/R*nu.sin(l))
            vtheory[ii]= (R**options.beta-dfc.asymmetricdrift(R))*m.sin(phi+l)-m.sin(l) #last term is the LSR
        bovy_plot.bovy_print()
        bovy_plot.scatterplot(ds,vloss,'.',bins=options.scatterbins,
                              xlabel=r'$d / R_0$',
                              ylabel=r'$v_{los} / v_0$')
        bovy_plot.bovy_plot(dx,vtheory,overplot=True)
        bovy_plot.bovy_text(r'$l = %i^\circ$' % round(options.los),
                            top_left=True)
        bovy_plot.bovy_end_print(options.vlosdname)
    if not options.vtname is None:
        vts= nu.array([o[1]-1. for o in out]).flatten() #subtract vc
        #Calculate expected
        ntheory= 1001
        vx= nu.linspace(-1.,1.,ntheory)
        y= nu.zeros(ntheory)
        for ii in range(ntheory):
            y[ii]= dfc(Orbit([1.,0.,vx[ii]+1.]))
        y/= nu.sum(y)*(vx[1]-vx[0])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(vts,bins=options.histbins,normed=True,
                            xlabel=r'$v_T / v_0 - 1$')
        bovy_plot.bovy_plot(vx,y,overplot=True)
        bovy_plot.bovy_end_print(options.vtname)
    if not options.vrname is None:
        vrs= nu.array([o[0] for o in out]).flatten() #subtract vc
        #Calculate expected
        ntheory= 1001
        vx= nu.linspace(-1.,1.,ntheory)
        y= nu.zeros(ntheory)
        vT= 1.-dfc.asymmetricdrift(1.)
        for ii in range(ntheory):
            y[ii]= dfc(Orbit([1.,vx[ii],vT]))
        y/= nu.sum(y)*(vx[1]-vx[0])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(vrs,bins=options.histbins,normed=True,
                            xlabel=r'$v_R / v_0$')
        bovy_plot.bovy_plot(vx,y,overplot=True)
        bovy_plot.bovy_end_print(options.vrname)
    if not options.vrvtname is None:
        vts= nu.array([o[1]-1. for o in out]).flatten() #subtract vc
        vrs= nu.array([o[0] for o in out]).flatten() #subtract vc
        bovy_plot.bovy_print()
        bovy_plot.scatterplot(vrs,vts,'.',bins=options.scatterbins,
                              xlabel=r'$v_R / v_0$',
                              ylabel=r'$v_T / v_0 - 1$')
        bovy_plot.bovy_end_print(options.vrvtname)
Пример #24
0
def fitSigz(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        params= pickle.load(savefile)
        samples= pickle.load(savefile)
        savefile.close()
        if _DEBUG:
            print "Printing mean and std dev of samples ..."
            for ii in range(len(params)):
                xs= numpy.array([s[ii] for s in samples])
                print numpy.mean(xs), numpy.std(xs)
    else:
        #First read the data
        if _VERBOSE:
            print "Reading and parsing data ..."
        XYZ,vxvyvz,cov_vxvyvz,rawdata= readData(metal=options.metal,
                                                sample=options.sample)
        vxvyvz= vxvyvz.astype(numpy.float64)
        cov_vxvyvz= cov_vxvyvz.astype(numpy.float64)
        R= ((8.-XYZ[:,0])**2.+XYZ[:,1]**2.)**(0.5)
        XYZ[:,2]+= _ZSUN
        d= numpy.fabs((XYZ[:,2]-numpy.mean(numpy.fabs(XYZ[:,2]))))
        #Optimize likelihood
        if _VERBOSE:
            print "Optimizing the likelihood ..."
        if options.model.lower() == 'hwr':
            if options.metal == 'rich':
                params= numpy.array([0.02,numpy.log(25.),0.,0.,numpy.log(6.)])
            elif options.metal == 'poor':
                params= numpy.array([0.02,numpy.log(40.),0.,0.,numpy.log(15.)])
            else:
                params= numpy.array([0.02,numpy.log(30.),0.,0.,numpy.log(15.)])
            like_func= _HWRLikeMinus
            pdf_func= _HWRLike
            #Slice sampling keywords
            step= [0.01,0.05,0.3,0.3,0.3]
            create_method=['full','step_out','step_out',
                           'step_out','step_out']
            isDomainFinite=[[True,True],[False,False],
                            [False,False],[False,False],
                            [False,False]]
            domain=[[0.,1.],[0.,0.],[0.,0.],[0.,0.],
                    [0.,4.6051701859880918]]
        elif options.model.lower() == 'isotherm':
            if options.metal == 'rich':
                params= numpy.array([0.02,numpy.log(25.),numpy.log(6.)])
            elif options.metal == 'poor':
                params= numpy.array([0.02,numpy.log(40.),numpy.log(15.)])
            else:
                params= numpy.array([0.02,numpy.log(30.),numpy.log(15.)])
            like_func= _IsothermLikeMinus
            pdf_func= _IsothermLike
            #Slice sampling keywords
            step= [0.01,0.05,0.3]
            create_method=['full','step_out','step_out']
            isDomainFinite=[[True,True],[False,False],
                            [False,True]]
            domain=[[0.,1.],[0.,0.],[0.,4.6051701859880918]]
        params= optimize.fmin_powell(like_func,params,
                                     args=(XYZ,vxvyvz,cov_vxvyvz,R,d))
        if _VERBOSE:
            print "Optimal likelihood:", params
        #Now sample
        if _VERBOSE:
            print "Sampling the likelihood ..."
        samples= bovy_mcmc.slice(params,
                                 step,
                                 pdf_func,
                                 (XYZ,vxvyvz,cov_vxvyvz,R,d),
                                 create_method=create_method,
                                 isDomainFinite=isDomainFinite,
                                 domain=domain,
                                 nsamples=options.nsamples)
        if _DEBUG:
            print "Printing mean and std dev of samples ..."
            for ii in range(len(params)):
                xs= numpy.array([s[ii] for s in samples])
                print numpy.mean(xs), numpy.std(xs)
        if _VERBOSE:
            print "Saving ..."
        savefile= open(args[0],'wb')
        pickle.dump(params,savefile)
        pickle.dump(samples,savefile)
        savefile.close()
    if options.noplots: return None
    #Plot
    if options.plotfunc:
        #First plot the best fit
        zs= numpy.linspace(0.3,1.2,1001)
        ds= zs-1.
        func= zfunc
        maxys= math.exp(params[1])+params[2]*ds+params[3]*ds**2.
        if options.xmin is None or options.xmax is None:
            xrange= [numpy.amin(zs)-0.2,numpy.amax(zs)+0.1]
        else:
            xrange= [options.xmin,options.xmax]
        if options.ymin is None or options.ymax is None:
            yrange= [numpy.amin(ys)-1.,numpy.amax(ys)+1.]
        else:
            yrange= [options.ymin,options.ymax]
        #Now plot the mean and std-dev from the posterior
        zmean= numpy.zeros(len(zs))
        nsigs= 3
        zsigs= numpy.zeros((len(zs),2*nsigs))
        fs= numpy.zeros((len(zs),len(samples)))
        ds= zs-1.
        for ii in range(len(samples)):
            thisparams= samples[ii]
            fs[:,ii]= math.exp(thisparams[1])+thisparams[2]*ds+thisparams[3]*ds**2.
        #Record mean and std-devs
        zmean[:]= numpy.mean(fs,axis=1)
        bovy_plot.bovy_print()
        bovy_plot.bovy_plot(zs,zmean,'k-',xrange=xrange,yrange=yrange,
                            xlabel=options.xlabel,
                            ylabel=options.ylabel)
        for ii in range(nsigs):
            for jj in range(len(zs)):
                thisf= sorted(fs[jj,:])
                thiscut= 0.5*special.erfc((ii+1.)/math.sqrt(2.))
                zsigs[jj,2*ii]= thisf[int(math.floor(thiscut*len(samples)))]
                thiscut= 1.-thiscut
                zsigs[jj,2*ii+1]= thisf[int(math.floor(thiscut*len(samples)))]
        colord, cc= (1.-0.75)/nsigs, 1
        nsigma= nsigs
        pyplot.fill_between(zs,zsigs[:,0],zsigs[:,1],color='0.75')
        while nsigma > 1:
            pyplot.fill_between(zs,zsigs[:,cc+1],zsigs[:,cc-1],
                                color='%f' % (.75+colord*cc))
            pyplot.fill_between(zs,zsigs[:,cc],zsigs[:,cc+2],
                                color='%f' % (.75+colord*cc))
            cc+= 1.
            nsigma-= 1
        bovy_plot.bovy_plot(zs,zmean,'k-',overplot=True)
        #bovy_plot.bovy_plot(zs,maxys,'w--',overplot=True)
        bovy_plot.bovy_end_print(options.plotfile)
    else:
        xs= numpy.array([s[options.d1] for s in samples])
        ys= numpy.array([s[options.d2] for s in samples])
        if options.expd1: xs= numpy.exp(xs)
        if options.expd2: ys= numpy.exp(ys)
        if options.xmin is None or options.xmax is None:
            xrange= [numpy.amin(xs),numpy.amax(xs)]
        else:
            xrange= [options.xmin,options.xmax]
        if options.ymin is None or options.ymax is None:
            yrange= [numpy.amin(ys),numpy.amax(ys)]
        else:
            yrange= [options.ymin,options.ymax]
        bovy_plot.bovy_print()
        bovy_plot.scatterplot(xs,ys,'k,',onedhists=True,xrange=xrange,
                              yrange=yrange,xlabel=options.xlabel,
                              ylabel=options.ylabel)
        maxx, maxy= params[options.d1], params[options.d2]
        if options.expd1: maxx= math.exp(maxx)
        if options.expd2: maxy= math.exp(maxy)
        bovy_plot.bovy_plot([maxx],[maxy],'wx',
                            overplot=True,ms=10.,mew=2.)
        bovy_plot.bovy_end_print(options.plotfile)
Пример #25
0
 cntrThisa= numpy.reshape(cntrThisa,Z.shape)
 print "vertex deviation", -0.5*math.atan(2*V[0,1]/(V[0,0]-V[1,1]))/math.pi*180.
 print m
 print a
 print numpy.sqrt([V[0,0],V[1,1]])
 print "vertex deviation", -0.5*math.atan(2*Va[0,1]/(Va[0,0]-Va[1,1]))/math.pi*180.
 print ma
 print aa
 print numpy.sqrt([Va[0,0],Va[1,1]])
 bovy_plot.bovy_print() 
 axScatter, axHistx,axHisty= bovy_plot.scatterplot(vs[0,:],vs[1,:],
                                                   'k,',zorder=2,
                                                   xlabel=r'$v_R / v_0$',
                                                   ylabel=r'$v_T / v_0$',
                                                   yrange=[.0,1.5],
                                                   xrange=[-1.,1.],bins=51,
                                                   onedhists=True,
                                                   retAxes=True,
                                                   cntrls='dashed',
                                                   onedhistxnormed=True,
                                                   onedhistynormed=True)
 #grid.df/= numpy.sum(grid.df)*(grid.vRgrid[1]-grid.vRgrid[0])\
 #    *(grid.vTgrid[1]-grid.vTgrid[0])
 #axScatter, axHistx,axHisty= bovy_plot.bovy_dens2d(grid.df[:,:,0].T,origin='lower',
 #                                                  cmap='gist_yarg',
 #                                                  contours=True,
 #                                                  cntrmass=True,
 #                                                  levels=special.erf(0.5*numpy.arange(1,4)),
 #                                                  xlabel=r'$v_R / v_0$',
 #                                                  ylabel=r'$v_T / v_0$',
 #                                                  yrange=[grid.vTgrid[0],grid.vTgrid[-1]],
Пример #26
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
Пример #27
0
def plotXDall(parser):
    nu.random.seed(1)
    (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
    if os.path.exists(args[1]):
        savefile = open(args[1], "rb")
        starxamp = pickle.load(savefile)
        starxmean = pickle.load(savefile)
        starxcovar = pickle.load(savefile)
        savefile.close()
    else:
        print args[1] + " does not exist ..."
        print "Returning ..."
        return
    if os.path.exists(args[2]):
        savefile = open(args[2], "rb")
        rrxamp = pickle.load(savefile)
        rrxmean = pickle.load(savefile)
        rrxcovar = pickle.load(savefile)
        savefile.close()
    else:
        print args[2] + " does not exist ..."
        print "Returning ..."
        return
    if options.nsamplesstar is None:
        options.nsamplesstar = options.nsamples
    if options.nsamplesrrlyrae is None:
        options.nsamplesrrlyrae = options.nsamples
    # Load XD object in xdtarget
    xdt = xdtarget.xdtarget(amp=xamp, mean=xmean, covar=xcovar)
    out = xdt.sample(nsample=options.nsamples)
    xdt = xdtarget.xdtarget(amp=starxamp, mean=starxmean, covar=starxcovar)
    starout = xdt.sample(nsample=options.nsamplesstar)
    xdt = xdtarget.xdtarget(amp=rrxamp, mean=rrxmean, covar=rrxcovar)
    rrout = xdt.sample(nsample=options.nsamplesrrlyrae)
    # 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.0) + xs + nu.log(1.0 - nu.exp(-1.0 / nu.exp(ys)))) / 2.0
        elif options.d1 == 1 and options.d2 == 0:
            # Convert to logA
            ys = (nu.log(2.0) + ys + nu.log(1.0 - nu.exp(-1.0 / nu.exp(xs)))) / 2.0
        else:
            print "d1 and d2 have to be 0 or 1 (and not the same!) ..."
            print "Returning ..."
            return
    # stars
    if options.expd1:
        starxs = nu.exp(starout[:, options.d1])
    elif not options.divided1 is None:
        starxs = starout[:, options.d1] / options.divided1
    else:
        starxs = starout[:, options.d1]
    if options.expd2:
        starys = nu.exp(starout[:, options.d2])
    elif not options.divided2 is None:
        starys = starout[:, options.d2] / options.divided2
    else:
        starys = starout[:, options.d2]
    if options.type == "DRW":
        # plot logA, logA = 0
        if options.d1 == 0 and options.d2 == 1:
            # Convert to logA
            starxs = (nu.log(2.0) + starxs + nu.log(1.0 - nu.exp(-1.0 / nu.exp(starys)))) / 2.0
        elif options.d1 == 1 and options.d2 == 0:
            # Convert to logA
            starys = (nu.log(2.0) + starys + nu.log(1.0 - nu.exp(-1.0 / nu.exp(starxs)))) / 2.0
        else:
            print "d1 and d2 have to be 0 or 1 (and not the same!) ..."
            print "Returning ..."
            return
    # RR Lyrae
    if options.expd1:
        rrxs = nu.exp(rrout[:, options.d1])
    elif not options.divided1 is None:
        rrxs = rrout[:, options.d1] / options.divided1
    else:
        rrxs = rrout[:, options.d1]
    if options.expd2:
        rrys = nu.exp(rrout[:, options.d2])
    elif not options.divided2 is None:
        rrys = rrout[:, options.d2] / options.divided2
    else:
        rrys = rrout[:, options.d2]
    if options.type == "DRW":
        # plot logA, logA = 0
        if options.d1 == 0 and options.d2 == 1:
            # Convert to logA
            rrxs = (nu.log(2.0) + rrxs + nu.log(1.0 - nu.exp(-1.0 / nu.exp(rrys)))) / 2.0
        elif options.d1 == 1 and options.d2 == 0:
            # Convert to logA
            rrys = (nu.log(2.0) + rrys + nu.log(1.0 - nu.exp(-1.0 / nu.exp(rrxs)))) / 2.0
        else:
            print "d1 and d2 have to be 0 or 1 (and not the same!) ..."
            print "Returning ..."
            return
    # Plot
    xrange = [options.xmin, options.xmax]
    yrange = [options.ymin, options.ymax]
    data = sc.array([xs, ys]).T
    bins = int(round(0.3 * sc.sqrt(options.nsamples)))
    hist, edges = sc.histogramdd(data, bins=bins, range=[xrange, yrange])
    # Censor hist ASSUMES gamma=[0.,1.2], logA=[-9.21/2.,0.] for powerlawSF
    x = nu.zeros((bins, bins))
    y = nu.zeros((bins, bins))
    for bb in range(bins):
        x[:, bb] = nu.linspace(options.xmin, options.xmax, bins)
        y[bb, :] = nu.linspace(options.ymin, options.ymax, bins)
    # mask
    if options.type == "powerlawSF":
        hist[(y < 0.1) * (x > -3.0) * (x < -1.5)] = nu.nan
        hist[(x < -3.0)] = nu.nan
        hist[(x > -2.0) * (y < (0.25 * x + 0.6))] = nu.nan
        onedhistyweights = nu.ones(len(ys)) / 100.0
    elif options.type == "DRW":
        hist[(y < (-4.223 * (x + 2) - 10))] = nu.nan
        hist[(y < -4.153) * (y < (58.47 * (x + 2.1) - 10.0))] = nu.nan
        hist[(y > -4.153) * (y < (2.93 * x + 2.0) - 1.0)] = nu.nan
        onedhistyweights = nu.ones(len(ys)) / 2500.0
    bovy_plot.bovy_print()
    # First just plot contours
    cdict = {
        "red": ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
        "green": ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
        "blue": ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
    }
    allwhite = matplotlib.colors.LinearSegmentedColormap("allwhite", cdict, 256)
    bovy_plot.scatterplot(
        xs,
        ys,
        "b,",
        onedhists=True,
        bins=bins,
        cmap=allwhite,
        onedhistynormed=False,
        onedhistyweights=onedhistyweights,
        xrange=xrange,
        yrange=yrange,
        onedhistec="b",
        xlabel=options.xlabel,
        ylabel=options.ylabel,
    )
    bovy_plot.scatterplot(
        starxs, starys, "k,", onedhists=True, bins=bins, cmap=allwhite, xrange=xrange, yrange=yrange, overplot=True
    )
    bovy_plot.scatterplot(
        rrxs,
        rrys,
        "r,",
        onedhists=True,
        bins=bins,
        cmap=allwhite,
        onedhistec="r",
        xrange=xrange,
        yrange=yrange,
        overplot=True,
    )
    hist /= nu.nansum(hist)
    # Custom colormap
    cdict = {
        "red": ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)),
        "green": ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)),
        "blue": ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
    }
    my_cmap = matplotlib.colors.LinearSegmentedColormap("my_colormap", cdict, 256)
    bovy_plot.scatterplot(
        xs,
        ys,
        "b,",
        onedhists=False,
        contours=False,
        levels=[1.01],
        bins=bins,
        cmap=my_cmap,
        hist=hist,
        edges=edges,
        onedhistynormed=False,
        onedhistyweights=onedhistyweights,
        xrange=xrange,
        yrange=yrange,
        overplot=True,
    )
    # Stars
    data = sc.array([starxs, starys]).T
    hist, edges = sc.histogramdd(data, bins=bins, range=[xrange, yrange])
    if options.type == "powerlawSF":
        hist[(x > -2.5)] = nu.nan
        hist[(x < -2.5) * (y > (-0.19 * (x + 2.5)))] = nu.nan
    elif options.type == "DRW":
        hist[(y >= (-4.223 * (x + 2) - 10))] = nu.nan
    hist /= nu.nansum(hist)
    bovy_plot.scatterplot(
        starxs,
        starys,
        "k,",
        onedhists=True,
        contours=False,
        levels=[1.01],  # HACK such that outliers aren't plotted
        bins=bins,
        hist=hist,
        edges=edges,
        xrange=xrange,
        yrange=yrange,
        overplot=True,
    )
    # RR Lyrae
    data = sc.array([rrxs, rrys]).T
    hist, edges = sc.histogramdd(data, bins=bins, range=[xrange, yrange])
    if options.type == "powerlawSF":
        hist[(x < -2.5)] = nu.nan
        hist[(x > -2.5) * (y > ((x + 2.5) / 1.5) ** 9.0 * 1.15 + 0.1)] = nu.nan
        # hist[(x > -2.5)*(y > (.25*x+.6))]= nu.nan
    elif options.type == "DRW":
        hist[(y < -4.153) * (y >= (58.47 * (x + 2.1) - 10.0)) * (y > -7.5)] = nu.nan
        hist[(y < -7.5) * (x < -2.1)] = nu.nan
        hist[(y > -4.153) * (y >= (2.93 * x + 2.0 - 1.5))] = nu.nan
    # Custom colormap
    cdict = {
        "red": ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
        "green": ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)),
        "blue": ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)),
    }
    my_cmap = matplotlib.colors.LinearSegmentedColormap("my_colormap", cdict, 256)
    hist /= nu.nansum(hist)
    bovy_plot.scatterplot(
        rrxs,
        rrys,
        "r,",
        onedhists=False,
        contours=False,
        levels=[1.01],  # HACK such that outliers aren't plotted
        bins=bins,
        cmap=my_cmap,
        hist=hist,
        edges=edges,
        xrange=xrange,
        yrange=yrange,
        overplot=True,
    )
    # Label
    if options.type == "powerlawSF":
        bovy_plot.bovy_text(-4.4, 1.15, r"$\mathrm{F/G\ stars}$", color="k")
        bovy_plot.bovy_text(-4.4, 1.05, r"$\mathrm{QSOs}$", color="b")
        bovy_plot.bovy_text(-4.4, 0.95, r"$\mathrm{RR\ Lyrae}$", color="r")
    elif options.type == "DRW":
        bovy_plot.bovy_text(-4.4, 2.88, r"$\mathrm{F/G\ stars}$", color="k")
        bovy_plot.bovy_text(-4.4, 1.76, r"$\mathrm{QSOs}$", color="b")
        bovy_plot.bovy_text(-4.4, 0.64, r"$\mathrm{RR\ Lyrae}$", color="r")
    bovy_plot.bovy_end_print(options.plotfilename)
Пример #28
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')
Пример #29
0
def plot_rovo(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()
    if _ANALYTIC: #Calculate by fixing everything except for Ro anv vo
        options= plot_pdfs.set_options(None)
        nros= 15
        noos= 15
        ros= numpy.linspace(7.,13.,nros)
        oos= numpy.linspace(20.,30.,noos)
        ll= numpy.zeros((noos,nros))
        for ii in range(noos):
            if not _MULTI is None:
                theseparamss= []
                for jj in range(nros):
                    theseparams= copy.copy(params)
                    theseparams[0]= oos[ii]*ros[jj]/_REFV0
                    theseparams[1]= ros[jj]/_REFR0
                    theseparamss.append(theseparams)
                thisll= multi.parallel_map((lambda x: numpy.sum(logl.logl(init=theseparamss[x],options=options))),
                                           range(nros),
                                           numcores=numpy.amin([nros,_MULTI,multiprocessing.cpu_count()]))
                ll[ii,:]= thisll
            else:
                for jj in range(nros):
                    theseparams= copy.copy(params)
                    theseparams[0]= oos[ii]*ros[jj]/_REFV0
                    theseparams[1]= ros[jj]/_REFR0
                    ll[ii,jj]= numpy.sum(logl.logl(init=theseparams,
                                                   options=options))
        #Normalize
        ll-= logsumexp(ll)
        ll= numpy.exp(ll)
        levels= list(special.erf(0.5*numpy.arange(1,4)))
        bovy_plot.bovy_dens2d(ll.T,origin='lower',levels=levels,
                              xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
                              ylabel=r'$R_0\ [\mathrm{kpc}]$',
                              xrange=[20.,35.],
                              yrange=[7.,13.],
                              contours=True,
                              cntrcolors='k',
                              onedhists=True,
                              cmap='gist_yarg')
    else:
        vos= numpy.array([s[0] for s in params])*_REFV0
        ros= numpy.array([s[1] for s in params])*_REFR0
        bovy_plot.bovy_print()
        levels= list(special.erf(0.5*numpy.arange(1,4)))
        levels.append(1.01) #HACK to not plot outliers
        bovy_plot.scatterplot(vos/ros,ros,'k,',levels=levels,
                              xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
                              ylabel=r'$R_0\ [\mathrm{kpc}]$',
                              bins=31,
                              xrange=[200./8.,250./8.],
                              yrange=[7.,9.],
                              contours=True,
                              cntrcolors='k',
                              onedhists=True,
                              cmap='gist_yarg')
    bovy_plot.bovy_end_print(plotfilename)
Пример #30
0
def plotMass(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        mass= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        mass= []
        ii, jj= 0, 0
    #parameters
    if os.path.exists(args[1]):#Load initial
        savefile= open(args[1],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    else:
        print "Error: must provide parameters of best fits"
        print "Returning ..."
        return None
    #Mass uncertainties are in savefile3
    if len(args) > 2 and os.path.exists(args[2]):
        savefile= open(args[2],'rb')
        masssamples= pickle.load(savefile)
        savefile.close()
        masserrors= True
    else:
        masssamples= None
        masserrors= False
    if len(args) > 3 and os.path.exists(args[3]): #Load savefile
        savefile= open(args[3],'rb')
        denssamples= pickle.load(savefile)
        savefile.close()
        denserrors= True
    else:
        denssamples= None
        denserrors= False
    if len(args) > 4 and os.path.exists(args[4]):#Load savefile
        savefile= open(args[4],'rb')
        velfits= pickle.load(savefile)
        savefile.close()
        velfitsLoaded= True
    else:
        velfitsLoaded= False
    if len(args) > 5 and os.path.exists(args[5]):
        savefile= open(args[5],'rb')
        velsamples= pickle.load(savefile)
        savefile.close()
        velerrors= True
    else:
        velsamples= None            
        velerrors= False
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    if denserrors: errors= []
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(fits):
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            thismass= mass[afeindx+fehindx*binned.npixafe()]
            if masserrors:
                thismasssamples= masssamples[afeindx+fehindx*binned.npixafe()]
            else:
                thismasssamples= None
            thisfit= fits[afeindx+fehindx*binned.npixafe()]
            if denserrors:
                thisdenssamples= denssamples[afeindx+fehindx*binned.npixafe()]
            else:
                thisdenssamples= None
            if velfitsLoaded:
                thisvelfit= velfits[afeindx+fehindx*binned.npixafe()]
            if velerrors:
                thisvelsamples= velsamples[afeindx+fehindx*binned.npixafe()]
            if thisfit is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if options.type == 'mass':
                if not options.distzmin is None or not options.distzmax is None:
                    if options.distzmin is None and not options.distzmax is None:
                        thismass*= (1.-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.))
                    elif not options.distzmin is None and options.distzmax is None:
                        thismass*= numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)
                    else:
                        thismass*= (numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.))
                if options.logmass:
                    plotthis[ii,jj]= numpy.log10(thismass/10**6.)
                else:
                    plotthis[ii,jj]= thismass/10**6.
            elif options.type == 'nstars':
                if options.logmass:
                    plotthis[ii,jj]= numpy.log10(len(data))
                else:
                    plotthis[ii,jj]= len(data)
            elif options.model.lower() == 'hwr':
                if options.type == 'hz':
                    plotthis[ii,jj]= numpy.exp(thisfit[0])*1000.
                elif options.type == 'hr':
                    plotthis[ii,jj]= numpy.exp(thisfit[1])
                elif options.type.lower() == 'afe' \
                        or options.type.lower() == 'feh' \
                        or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    plotthis.append([tightbinned.feh(ii),
                                         tightbinned.afe(jj),
                                     numpy.exp(thisfit[0])*1000.,
                                     numpy.exp(thisfit[1]),
                                     len(data),
                                     thismass/10.**6.,
                                     thismasssamples])
                    if denserrors:
                        theseerrors= []
                        thesesamples= denssamples[afeindx+fehindx*binned.npixafe()]
                        if options.model.lower() == 'hwr':
                            for kk in [0,1]:
                                xs= numpy.array([s[kk] for s in thesesamples])
                                theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                        errors.append(theseerrors)
                    if velfitsLoaded:
                        if options.velmodel.lower() == 'hwr':
                            plotthis[-1].extend([numpy.exp(thisvelfit[1]),
                                                 numpy.exp(thisvelfit[4]),
                                                 thisvelfit[2],
                                                 thisvelfit[3]])
                            if velerrors:
                                theseerrors= []
                                thesesamples= velsamples[afeindx+fehindx*binned.npixafe()]
                                for kk in [1,4]:
                                    xs= numpy.array([s[kk] for s in thesesamples])
                                    theseerrors.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                                xs= numpy.array([s[4] for s in thesesamples])
                                theseerrors.append(0.5*(numpy.exp(-numpy.mean(xs))-numpy.exp(numpy.mean(-xs)-numpy.std(-xs))-numpy.exp(numpy.mean(-xs))+numpy.exp(numpy.mean(-xs)+numpy.std(-xs))))
                                errors[-1].extend(theseerrors)
    #Set up plot
    #print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    if options.type == 'mass':
        if options.logmass:
            vmin, vmax= numpy.log10(0.01), numpy.log10(2.)
            zlabel=r'$\log_{10} \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
        else:
            vmin, vmax= 0.,1.
            zlabel=r'$\Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
            if not options.distzmin is None or not options.distzmax is None:
                vmin, vmax= None, None
        title=r'$\mathrm{mass\ weighted}$'
    elif options.type == 'nstars':
        if options.logmass:
            vmin, vmax= 2., 3.
            zlabel=r'$\log_{10} \mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$'
        else:
            vmin, vmax= 100.,1000.
            zlabel=r'$\mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$'
        title= r'$\mathrm{raw\ sample\ counts}$'
    elif options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.5,0.
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.6]
        yrange=[-0.1,0.6]
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        #Gather hR and hz
        sz_err, sz, hz_err, hr_err, mass_err, mass, hz, hr,afe, feh, ndata= [], [], [], [], [], [], [], [], [], [], []
        for ii in range(len(plotthis)):
            if denserrors:
                hz_err.append(errors[ii][0]*1000.)
                hr_err.append(errors[ii][1])
            mass.append(plotthis[ii][5])
            hz.append(plotthis[ii][2])
            hr.append(plotthis[ii][3])
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][4])
            if velfitsLoaded:
                sz.append(plotthis[ii][7])
            if velerrors:
                sz_err.append(errors[ii][2])
            if masserrors:
                mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.))
                
                """
                if options.logmass:
                    mass_err.append(numpy.std(numpy.log10(numpy.array(plotthis[ii][6])/10.**6.)))
                else:
                    mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.))
                """
        if denserrors:
            hz_err= numpy.array(hz_err)
            hr_err= numpy.array(hr_err)
        if velfitsLoaded:
            sz= numpy.array(sz)
        if velerrors:
            sz_err= numpy.array(sz_err)
        mass= numpy.array(mass)
        if masserrors:
            mass_err= numpy.array(mass_err)
        hz= numpy.array(hz)
        hr= numpy.array(hr)
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata))
        #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        xrange= [150,1200]
        if options.cumul:
            #Print total surface mass and uncertainty
            totmass= numpy.sum(mass)
            if options.ploterrors:
                toterr= numpy.sqrt(numpy.sum(mass_err**2.))
            else:
                toterr= 0.
            print "Total surface-mass density: %4.1f +/- %4.2f" %(totmass,toterr)
            ids= numpy.argsort(hz)
            plotc= plotc[ids]
            ndata= ndata[ids]
            mass= mass[ids]
            mass= numpy.cumsum(mass)
            hz.sort()
            ylabel=r'$\mathrm{cumulative}\ \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
            if options.logmass:
                yrange= [0.01,30.]
            else:
                yrange= [-0.1,30.]
        else:
            if options.logmass:
                yrange= [0.005*0.13/.07,10.*.13/.07]
            else:
                yrange= [-0.1,10.*.13/.07]
            ylabel=r'$\Sigma_{R_0}(h_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
        if not options.vstructure and not options.hzhr:
            if options.hr:
                ploth= hr
                plotherr= hr_err
                xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$'
                xrange= [1.2,4.]
                bins= 11
            elif options.sz:
                ploth= sz**2.
                plotherr= 2.*sz_err*sz
                xlabel=r'$\sigma_z^2\ \mathrm{[km}^2\ \mathrm{s}^{-2}]$'
                xrange= [12.**2.,50.**2.]
                ylabel=r'$\Sigma_{R_0}(\sigma^2_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$'
                bins= 9
            else:
                ploth= hz
                plotherr= hz_err
                xlabel=r'$\mathrm{vertical\ scale\ height}\ h_z\ \mathrm{[pc]}$'
                xrange= [165,1200]
                bins= 12
            bovy_plot.bovy_plot(ploth,mass*.13/0.07,
                                s=ndata,c=plotc,
                                cmap='jet',
                                xlabel=xlabel,
                                ylabel=ylabel,
                                clabel=zlabel,
                                xrange=xrange,yrange=yrange,
                                vmin=vmin,vmax=vmax,
                                scatter=True,edgecolors='none',
                                colorbar=True,zorder=2,
                                semilogy=options.logmass)
            if not options.cumul and masserrors and options.ploterrors:
                colormap = cm.jet
                for ii in range(len(hz)):
                    pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,
                                    yerr=mass_err[ii]*.13/0.07,
                                    color=colormap(_squeeze(plotc[ii],
                                                            numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                            numpy.amin([vmax,
                                                                        numpy.amax(plotc)]))),
                                    elinewidth=1.,capsize=3,zorder=0)
            if not options.cumul and denserrors and options.ploterrors:
                colormap = cm.jet
                for ii in range(len(hz)):
                    pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,xerr=plotherr[ii],
                                    color=colormap(_squeeze(plotc[ii],
                                                            numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                            numpy.amin([vmax,
                                                                        numpy.amax(plotc)]))),
                                    elinewidth=1.,capsize=3,zorder=0)
            #Add binsize label
            bovy_plot.bovy_text(r'$\mathrm{points\ use}\ \Delta [\mathrm{Fe/H}] = 0.1,$'+'\n'+r'$\Delta [\alpha/\mathrm{Fe}] = 0.05\ \mathrm{bins}$',
                                bottom_left=True)
            #Overplot histogram
            #ax2 = pyplot.twinx()
            pyplot.hist(ploth,range=xrange,weights=mass*0.13/0.07,color='k',histtype='step',
                        bins=bins,lw=3.,zorder=10)
            #Also XD?
            if options.xd:
                #Set up data
                ydata= numpy.zeros((len(hz),1))
                if options.sz:
                    ydata[:,0]= numpy.log(sz)
                else:
                    ydata[:,0]= numpy.log(hz)
                ycovar= numpy.zeros((len(hz),1))
                if options.sz:
                    ycovar[:,0]= sz_err**2./sz**2.
                else:
                    ycovar[:,0]= hz_err**2./hz**2.
                #Set up initial conditions
                xamp= numpy.ones(options.k)/float(options.k)
                xmean= numpy.zeros((options.k,1))
                for kk in range(options.k):
                    xmean[kk,:]= numpy.mean(ydata,axis=0)\
                        +numpy.random.normal()*numpy.std(ydata,axis=0)
                xcovar= numpy.zeros((options.k,1,1))
                for kk in range(options.k):
                    xcovar[kk,:,:]= numpy.cov(ydata.T)
                #Run XD
                print extreme_deconvolution(ydata,ycovar,xamp,xmean,xcovar,
                                      weight=mass)*len(hz)
                print xamp, xmean, xcovar
                #Plot
                xs= numpy.linspace(xrange[0],xrange[1],1001)
                xdys= numpy.zeros(len(xs))
                for kk in range(options.k):
                    xdys+= xamp[kk]/numpy.sqrt(2.*numpy.pi*xcovar[kk,0,0])\
                        *numpy.exp(-0.5*(numpy.log(xs)-xmean[kk,0])**2./xcovar[kk,0,0])
                xdys/= xs
                bovy_plot.bovy_plot(xs,xdys,'-',color='0.5',overplot=True)
#            ax2.set_yscale('log')
#            ax2.set_yticklabels('')        
#            if options.hr:
#                pyplot.ylim(10**-2.,10.**0.)
#            if options.sz:
#                pyplot.ylim(10**-5.,10.**-2.5)
#            else:
#                pyplot.ylim(10**-5.5,10.**-1.5)
#            pyplot.xlim(xrange[0],xrange[1])
            ax= pyplot.gca()
            if options.sz:
                def my_formatter(x, pos):
                    """s^2"""
                    xs= int(round(math.sqrt(x)))
                    return r'$%i^2$' % xs
                major_formatter = FuncFormatter(my_formatter)
                ax.xaxis.set_major_formatter(major_formatter)
            xstep= ax.xaxis.get_majorticklocs()
            xstep= xstep[1]-xstep[0]
            ax.xaxis.set_minor_locator(MultipleLocator(xstep/5.))
        elif options.hzhr:
            #Make density plot in hR and hz
            bovy_plot.scatterplot(hr,hz,'k,',
                                  levels=[1.01],#HACK such that outliers aren't plotted
                                  cmap='gist_yarg',
                                  bins=11,
                                  xrange=[1.,7.],
                                  yrange=[150.,1200.],
                                  ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$',
                                  xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$',
                                  onedhists=False,
                                  weights=mass)
        else:
            #Make an illustrative plot of the vertical structure
            nzs= 1001
            zs= numpy.linspace(200.,3000.,nzs)
            total= numpy.zeros(nzs)
            for ii in range(len(hz)):
                total+= mass[ii]/2./hz[ii]*numpy.exp(-zs/hz[ii])
            bovy_plot.bovy_plot(zs,total,color='k',ls='-',lw=3.,
                                semilogy=True,
                                xrange=[0.,3200.],
                                yrange=[0.000001,0.02],
                                xlabel=r'$\mathrm{vertical\ height}\ Z$',
                                ylabel=r'$\rho_*(R=R_0,Z)\ [\mathrm{M}_\odot\ \mathrm{pc}^{-3}]$',
                                zorder=10)
            if options.vbinned:
                #Bin
                mhist, edges= numpy.histogram(hz,range=xrange,
                                              weights=mass,bins=10)
                stotal= numpy.zeros(nzs)
                for ii in range(len(mhist)):
                    hz= (edges[ii+1]+edges[ii])/2.
                    if options.vcumul:
                        if ii == 0.:
                            pstotal= numpy.zeros(nzs)+0.0000001
                        else:
                            pstotal= copy.copy(stotal)
                        stotal+= mhist[ii]/2./hz*numpy.exp(-zs/hz)
                        pyplot.fill_between(zs,stotal,pstotal,
                                            color='%.6f' % (0.25+0.5/(len(mhist)-1)*ii))
                    else:
                        bovy_plot.bovy_plot([zs[0],zs[-1]],
                                            1.*numpy.array([mhist[ii]/2./hz*numpy.exp(-zs[0]/hz),
                                                            mhist[ii]/2./hz*numpy.exp(-zs[-1]/hz)]),
                                            color='0.5',ls='-',overplot=True,
                                            zorder=0)
            else:
                colormap = cm.jet
                for ii in range(len(hz)):
                    bovy_plot.bovy_plot([zs[0],zs[-1]],
                                        100.*numpy.array([mass[ii]/2./hz[ii]*numpy.exp(-zs[0]/hz[ii]),
                                                          mass[ii]/2./hz[ii]*numpy.exp(-zs[-1]/hz[ii])]),
                                        ls='-',overplot=True,alpha=0.5,
                                        zorder=0,
                                        color=colormap(_squeeze(plotc[ii],
                                                                numpy.amax([vmin,
                                                                        numpy.amin(plotc)]),
                                                                numpy.amin([vmax,
                                                                            numpy.amax(plotc)]))))
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              onedhists=True,
                              contours=False)
        bovy_plot.bovy_text(title,top_right=True,fontsize=16)
        if not options.distzmin is None or not options.distzmax is None:
            if options.distzmin is None:
                distlabel= r'$|Z| < %i\ \mathrm{pc}$' % int(options.distzmax)
            elif options.distzmax is None:
                distlabel= r'$|Z| > %i\ \mathrm{pc}$' % int(options.distzmin)
            else:
                distlabel= r'$%i < |Z| < %i\ \mathrm{pc}$' % (int(options.distzmin),int(options.distzmax))
            bovy_plot.bovy_text(distlabel,bottom_left=True,fontsize=16)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
Пример #31
0
def compareMagFluxFits(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')  
            params.append(pickle.load(savefile))
            savefile.close()
        else:
            print filename+" does not exist ..."
            print "Returning ..."
            return
    if options.plottype == 'AA':
        ys= []
        xs= []
        for key in params[1].keys():
            try:
                ys.append(params[0][key]['logA']/2.)
                xs.append(params[1][key]['logA']/2.)
            except KeyError:
                continue
        xs= nu.array(xs).reshape(len(xs))
        ys= nu.array(ys).reshape(len(xs))
        ys= xs-ys-nu.log(nu.log(10.)/2.5)
        xrange=[-9.21/2.,0.]
        yrange=[-.25,.25]
        xlabel= r'$\log A^{\mathrm{flux}}_'+options.band+r'\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel= r'$\log A^{\mathrm{flux}}_'+options.band+r'-\log A^{\mathrm{mag}}_'+options.band+r'- \log\left(\frac{\log 10}{2.5}\right)$'
    elif options.plottype == 'gg':
        ys= []
        xs= []
        for key in params[1].keys():
            try:
                ys.append(params[0][key]['gamma'])
                xs.append(params[1][key]['gamma'])
            except KeyError:
                continue
        xs= nu.array(xs).reshape(len(xs))
        ys= nu.array(ys).reshape(len(xs))
        print len(xs)
        ys= xs-ys
        xrange=[0.,1.2]
        yrange=[-.25,.25]
        xlabel= r'$\gamma^{\mathrm{flux}}_'+options.band+r'\ \mathrm{(power-law\ exponent)}$'
        ylabel= r'$\gamma^{\mathrm{flux}}_'+options.band+r'- \gamma^{\mathrm{mag}}_'+options.band+'$'
    elif options.plottype == 'loglike2':
        ys= []
        xs= []
        nepochs= []
        cnt= 0
        for key in params[1].keys():
            #cnt+= 1
            #print cnt
            #if cnt > 10: break
            #Get the number of epochs
            v= VarQso(os.path.join('../data/s82qsos/',key))
            try:
                ys.append(params[0][key]['loglike']
                          -v.nepochs(options.band)*nu.log(nu.log(10.)/2.5))
                nepochs.append(v.nepochs(options.band))
                xs.append(params[1][key]['loglike'])
            except KeyError:
                continue
        xs= -nu.array(xs).reshape(len(xs))
        ys= -nu.array(ys).reshape(len(xs))
        nepochs= nu.array(nepochs).reshape(len(nepochs))
        ys/= nepochs
        xs/= nepochs
        ys= xs-ys
        xrange=[-3.,0.]
        yrange=[-.1,.1]
        xlabel= r'$\log \mathcal{L}^{\mathrm{flux}}_{'+options.band+r',\mathrm{red}}\ \mathrm{(amplitude\ at\ 1\ yr)}$'
        ylabel= r'$\log \mathcal{L}^{\mathrm{flux}}_{'+options.band+r',\mathrm{red}}- \log \mathcal{L}^{\mathrm{mag}}_{'+options.band+',\mathrm{red}}'+r'- \log\left(\frac{\log 10}{2.5}\right)$'
    bovy_plot.bovy_print()
    bovy_plot.scatterplot(xs,ys,'k,',onedhists=True,
                          yrange=yrange,
                          xrange=xrange,bins=31,
                          xlabel=xlabel,
                          ylabel=ylabel)
    bovy_plot.bovy_plot(nu.array(xrange),[0.,0.],'0.5',
                        overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None