def plot_data_h_jk(location=None,
                   plotfilename=os.path.join(OUTDIR, 'data_h_jk.' + OUTEXT)):
    data = readVclosData()
    if not location is None:
        if location == 0:
            locs = set(data['LOCATION'])
            for l in locs:
                plot_data_h_jk(location=l,
                               plotfilename=os.path.join(
                                   OUTDIR, 'data_h_jk_%i.' % l + OUTEXT))
            return None
        data = data[(data['LOCATION'] == location)]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['J0MAG'] - data['K0MAG'],
                        data['H0MAG'],
                        'k,',
                        xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                        ylabel=r'$H_0\ [\mathrm{mag}]$',
                        xrange=[0.4, 1.4],
                        yrange=[5., 14.],
                        onedhists=True,
                        bins=31)
    #Overplot distance if wanted
    if _PLOTDISTANCE:
        iso = isomodel(imfmodel='lognormalChabrier2001', Z=0.019, expsfh=True)
        nds = 101
        ds = numpy.zeros((nds, nds))
        jks = numpy.linspace(0.5, 1.2, nds)
        hs = numpy.linspace(14., 5., nds)
        for ii in range(nds):
            for jj in range(nds):
                ds[ii, jj] = iso.peak(jks[ii], hs[jj])
        #Now contour this
        levels = [1., 3., 10., 30.]
        colors = '0.6'  #['0.5','0.5','0.5','k','k','k']
        CS = pyplot.contour(jks,
                            hs,
                            ds.T,
                            levels=levels,
                            colors=colors,
                            zorder=10.,
                            linewidths=2.)
        ys = [5.3, 6.7, 9.22, 11.7]
        for ii in range(len(levels)):
            bovy_plot.bovy_text(1.21,
                                ys[ii],
                                r'$%.0f\ \mathrm{kpc}$' % levels[ii],
                                fontsize=14.,
                                color='0.3')
        if False:
            pyplot.clabel(CS,
                          levels,
                          inline=1,
                          fmt='%.0f',
                          fontsize=14,
                          colors=colors,
                          zorder=10.)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def simplePlot(location=4242,
               plotfile=None,
               predict=False,
               nv=11,
               dmax=10. / 8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data = readVclosData(**kwargs)
    data = data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range = [-200., 200.]
    hist, xvec, p = bovy_plot.bovy_hist(
        data['VHELIO'],
        range=range,
        bins=31,
        histtype='step',
        color='k',
        xlabel=
        r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs = numpy.linspace(range[0], range[1], nv)
        pred_dist = _calc_pred(pred_vs, location, numpy.mean(data['GLON']),
                               dmax)
        data_int = numpy.sum(hist) * (xvec[1] - xvec[0])
        pred_dist *= data_int / numpy.sum(pred_dist) / (pred_vs[1] -
                                                        pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,
                            pred_dist,
                            '-',
                            color='0.65',
                            overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location + '\n' +
                        r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,
                        size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
Example #3
0
def fieldsTable(parser):
    (options, args) = parser.parse_args()
    #Read data
    print "Reading the data ..."
    data = readVclosData(postshutdown=options.postshutdown,
                         fehcut=options.fehcut,
                         cohort=options.cohort,
                         lmin=options.lmin,
                         bmax=options.bmax,
                         ak=True,
                         cutmultiples=options.cutmultiples,
                         jkmax=options.jkmax)
    #Parse data
    locs = numpy.array(sorted(list(set(data['LOCATION']))))
    nlocs = len(locs)
    platel = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locs[ii])
        platel[ii] = numpy.mean(data['GLON'][indx])
    sortindx = numpy.argsort(platel)
    locs = locs[sortindx]
    outfile = open(options.plotfilename, 'w')
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locs[ii])
        #l
        printline = '$%i^\circ$ ' % int(round(numpy.mean(data['GLON'][indx])))
        # # of data
        printline += '& %i' % numpy.sum(indx)
        # # of data H < 12.2
        printline += '& %i' % numpy.sum(
            (data['LOCATION'] == locs[ii]) * (data['HMAG'] < 12.2))
        # # of data 12.2 <= H < 12.8
        nn = numpy.sum((data['LOCATION'] == locs[ii]) *
                       (data['HMAG'] >= 12.2) * (data['HMAG'] < 12.8))
        if nn > 0:
            printline += '& %i' % nn
        else:
            printline += '& 0'
        # # of data 12.8 <= H < 13.8
        nn = numpy.sum((data['LOCATION'] == locs[ii]) *
                       (data['HMAG'] >= 12.8) * (data['HMAG'] < 13.8))
        if nn > 0: printline += '& %i' % nn
        else: printline += '& 0 '
        #median ak
        printline += '& %.1f ' % numpy.median(data['AK'][indx])
        #median visits
        #printline+= '& %i ' % numpy.median(data['NVISITS'][indx])
        #Write the line
        if not ii == (nlocs - 1): printline += '\\\\\n'
        else: printline += '\n'
        outfile.write(printline)
    outfile.close()
Example #4
0
def fieldsTable(parser):
    (options,args)= parser.parse_args()
    #Read data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        jkmax=options.jkmax)
    #Parse data
    locs= numpy.array(sorted(list(set(data['LOCATION']))))
    nlocs= len(locs)
    platel= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locs[ii])
        platel[ii]= numpy.mean(data['GLON'][indx])
    sortindx= numpy.argsort(platel)
    locs= locs[sortindx]
    outfile= open(options.plotfilename,'w')
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locs[ii])
        #l
        printline= '$%i^\circ$ ' % int(round(numpy.mean(data['GLON'][indx])))
        # # of data
        printline+= '& %i' % numpy.sum(indx)
        # # of data H < 12.2
        printline+= '& %i' % numpy.sum((data['LOCATION'] == locs[ii])*(data['HMAG'] < 12.2))
        # # of data 12.2 <= H < 12.8
        nn= numpy.sum((data['LOCATION'] == locs[ii])*(data['HMAG'] >= 12.2)*(data['HMAG'] < 12.8))
        if nn > 0:
            printline+= '& %i' % nn
        else:
            printline+= '& 0'
        # # of data 12.8 <= H < 13.8
        nn= numpy.sum((data['LOCATION'] == locs[ii])*(data['HMAG'] >= 12.8)*(data['HMAG'] < 13.8))
        if nn > 0: printline+= '& %i' % nn
        else: printline+= '& 0 '
        #median ak
        printline+= '& %.1f ' % numpy.median(data['AK'][indx])
        #median visits
        #printline+= '& %i ' % numpy.median(data['NVISITS'][indx])
        #Write the line
        if not ii == (nlocs-1): printline+= '\\\\\n'
        else: printline+= '\n'
        outfile.write(printline)
    outfile.close()
def plot_data_h_jk(location=None,
                   plotfilename=os.path.join(OUTDIR,'data_h_jk.'+OUTEXT)):
    data= readVclosData()
    if not location is None:
        if location == 0:
            locs= set(data['LOCATION'])
            for l in locs:
                plot_data_h_jk(location=l,
                               plotfilename=os.path.join(OUTDIR,'data_h_jk_%i.' % l +OUTEXT))
            return None
        data= data[(data['LOCATION'] == location)]
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['J0MAG']-data['K0MAG'],
                        data['H0MAG'],'k,',
                        xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                        ylabel=r'$H_0\ [\mathrm{mag}]$',
                        xrange=[0.4,1.4],
                        yrange=[5.,14.],
                        onedhists=True,bins=31)
    #Overplot distance if wanted
    if _PLOTDISTANCE:
        iso= isomodel(imfmodel='lognormalChabrier2001',
                      Z=0.019,
                      expsfh=True)
        nds= 101
        ds= numpy.zeros((nds,nds))
        jks= numpy.linspace(0.5,1.2,nds)
        hs= numpy.linspace(14.,5.,nds)
        for ii in range(nds):
            for jj in range(nds):
                ds[ii,jj]= iso.peak(jks[ii],hs[jj])
        #Now contour this
        levels=[1.,3.,10.,30.]
        colors='0.6'#['0.5','0.5','0.5','k','k','k']
        CS=pyplot.contour(jks,hs,ds.T,levels=levels,
                          colors=colors,zorder=10.,linewidths=2.)
        ys= [5.3,6.7,9.22,11.7]
        for ii in range(len(levels)):
            bovy_plot.bovy_text(1.21,ys[ii],r'$%.0f\ \mathrm{kpc}$' % levels[ii],
                                fontsize=14.,color='0.3')
        if False:
            pyplot.clabel(CS, levels,
                          inline=1,
                          fmt='%.0f',
                          fontsize=14,
                          colors=colors,zorder=10.)
    bovy_plot.bovy_end_print(plotfilename)
    return None
def simplePlot(location=4242,plotfile=None,predict=False,nv=11,dmax=10./8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data= readVclosData(**kwargs)
    data= data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range= [-200.,200.]
    hist, xvec, p= bovy_plot.bovy_hist(data['VHELIO'],range=range,bins=31,
                                       histtype='step',color='k',
                                       xlabel=r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs= numpy.linspace(range[0],range[1],nv)
        pred_dist= _calc_pred(pred_vs,location,numpy.mean(data['GLON']),dmax)
        data_int= numpy.sum(hist)*(xvec[1]-xvec[0])
        pred_dist*= data_int/numpy.sum(pred_dist)/(pred_vs[1]-pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,pred_dist,'-',color='0.65',overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location
                        +'\n'
                        +r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
def plot_data_feh(location=0,
                  plotfilename=os.path.join(OUTDIR,'data_h_jk.'+OUTEXT)):
    data= readVclosData()
    #Good feh
    data= data[(data['FEH']!= -9999.00)]
    if not location is None:
        if location == 0:
            locs= set(data['LOCATION'])
            for l in locs:
                plot_data_feh(location=l,
                              plotfilename=os.path.join(OUTDIR,'data_feh_%i.' % l +OUTEXT))
            return None
        data= data[(data['LOCATION'] == location)]
    meanfeh= numpy.mean(data['FEH'])
    sigfeh= numpy.std(data['FEH'])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data['FEH'],
                        xlabel=r'$[\mathrm{Fe/H}]$',
                        xrange=[meanfeh-1.,meanfeh+1],
                        bins=16)
    bovy_plot.bovy_text(r'$\sigma = %.2f$' % sigfeh,top_right=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Example #8
0
def plot_data_feh(location=0,
                  plotfilename=os.path.join(OUTDIR, 'data_h_jk.' + OUTEXT)):
    data = readVclosData()
    #Good feh
    data = data[(data['FEH'] != -9999.00)]
    if not location is None:
        if location == 0:
            locs = set(data['LOCATION'])
            for l in locs:
                plot_data_feh(location=l,
                              plotfilename=os.path.join(
                                  OUTDIR, 'data_feh_%i.' % l + OUTEXT))
            return None
        data = data[(data['LOCATION'] == location)]
    meanfeh = numpy.mean(data['FEH'])
    sigfeh = numpy.std(data['FEH'])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data['FEH'],
                        xlabel=r'$[\mathrm{Fe/H}]$',
                        xrange=[meanfeh - 1., meanfeh + 1],
                        bins=16)
    bovy_plot.bovy_text(r'$\sigma = %.2f$' % sigfeh, top_right=True)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Example #9
0
def plot_nonaxi(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    # Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        validfeh=options.indivfeh,  # if indivfeh, we need validfeh
        cutmultiples=options.cutmultiples,
        jkmax=options.jkmax,
    )
    # data= data[0:20]
    # HACK
    indx = data["J0MAG"] - data["K0MAG"] < 0.5
    data["J0MAG"][indx] = 0.5 + data["K0MAG"][indx]
    indx = data["GLON"] <= 30.0
    data["GLON"][indx] = 30.05  # Hack because the non-axi models don't go below Ro/2
    # Cut outliers
    # data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    # Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, "rb")
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            # Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data["LOCATION"]))
            iso = []
            for ii in range(len(locs)):
                indx = data["LOCATION"] == locs[ii]
                locl = numpy.mean(data["GLON"][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, marginalizefeh=True, glon=locl)
                )
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, expsfh=options.expsfh)
        if options.dwarf:
            iso = [iso, isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, dwarf=True, expsfh=options.expsfh)]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, "wb")
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data["H0MAG"][ii] - dm
        if options.indivfeh:
            # Find closest Z
            thisZ = isodist.FEH2Z(data[ii]["FEH"])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        elif options.varfeh:
            # Find correct iso
            indx = locl == data[ii]["LOCATION"]
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF, _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data["H0MAG"][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    else:
        logpisodwarf = None
    """ #Does not matter anyway
    #clean logpiso
    dataindx= []
    for ii in range(len(data)):
        thislogpiso= logpiso[ii,:]-logsumexp(logpiso[ii,:])
        if numpy.all(thislogpiso == 0.): dataindx.append(False)
        else: dataindx.append(True)
    dataindx= numpy.array(dataindx,dtype='bool')
    data= data[dataindx]
    logpiso= logpiso[dataindx,:]
    logpisodwarf= logpisodwarf[dataindx,:]
    """
    # Calculate data means etc.
    # Calculate means
    locations = list(set(data["LOCATION"]))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = data["LOCATION"] == locations[ii]
        l_plate[ii] = numpy.mean(data["GLON"][indx])
        avg_plate[ii] = numpy.mean(data["VHELIO"][indx])
        sig_plate[ii] = numpy.std(data["VHELIO"][indx])
        siga_plate[ii] = numpy.std(data["VHELIO"][indx]) / numpy.sqrt(numpy.sum(indx))
    # Calculate plate means and variances from the model
    # Load initial parameters from file
    savefile = open(args[0], "rb")
    params = pickle.load(savefile)
    savefile.close()
    # First calculate fiducial model
    if not options.dwarf:
        logpisodwarf = None
    avg_plate_model_fid = calc_model(params, options, data, logpiso, logpisodwarf, df, nlocs, locations, iso)
    print l_plate, avg_plate_model_fid
    # Plot everything
    bovy_plot.bovy_print(fig_height=6.0, fig_width=7.0)
    dx = 0.8 / 5.0
    left, bottom, width, height = 0.1, 0.9 - dx, 0.8, dx
    axTop = pyplot.axes([left, bottom, width, height])
    allaxes = [axTop]
    fig = pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "ko", overplot=True)
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{fiducial}$", top_right=True, size=14.0)
    thisax = pyplot.gca()
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Second is bar
    print "Reading bar file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, 0.0)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 2.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{bar}$", top_right=True, size=14.0)
    # pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Third is spiral
    print "Reading spiral file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/spiral/spiral_rect_vr_51_101.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, 0.0)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 3.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{spiral}$", top_right=True, size=14.0)
    pyplot.ylabel(r"$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}} \ [\mathrm{km\ s}^{-1}]$")
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    # Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, 0.0)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 4.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{elliptical}$", top_right=True, size=14.0)
    # pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    # pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = "/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav"
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs, locations, -45.0 * _DEGTORAD)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 5.0 * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True, zorder=-1)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid, "o", overplot=True, color="0.6")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid,
        yerr=siga_plate,
        marker="o",
        color="0.6",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model_fid - avg_plate_bar, "o", overplot=True, color="k")
    pyplot.errorbar(
        l_plate,
        avg_plate - avg_plate_model_fid - avg_plate_bar,
        yerr=siga_plate,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    bovy_plot.bovy_text(r"$\mathrm{elliptical}$", top_right=True, size=14.0)
    # pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r"$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$")
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
                vR = -thisvs[ii] * math.cos(
                    theta + thisl)  #vperp=0 for marginalization
                vT = thisvs[ii] * math.sin(theta + thisl)
                o = Orbit([R, vR, vT, theta])
                surfmass = dfc.surfacemassLOS(d, thisl, deg=False)
                out += surfmass * dfc(
                    o, marginalizeVperp=True) / dfc.targetSurfacemass(R)
                norm += surfmass
            pred_dist[ii] = out / norm
            ii += 1
        if _PREDICTCACHE:
            savefile = open(savefilename, 'wb')
            try:
                pickle.dump(pred_dist, savefile)
            finally:
                savefile.close()
    return pred_dist


if __name__ == '__main__':
    data = readVclosData()
    locations = list(set(data['LOCATION']))
    for l in locations:
        print l
        simplePlot(location=l,
                   plotfile=os.path.join(
                       os.getenv('HOME'),
                       'Desktop/locationPlots/vlosdist_%i.png' % l),
                   predict=True,
                   nv=201)
Example #11
0
def mockTable(parser):
    (options, args) = parser.parse_args()
    cmdline = '%python mockTable.py ' + args[0]
    if len(args) == 0:
        parser.print_help()
        return
    #Open savefile for flat fit and samples
    savefile = open(_FLATFIT, 'rb')
    flatparams = pickle.load(savefile)
    savefile.close()
    savefile = open(_FLATSAMPLES, 'rb')
    flatsamples = pickle.load(savefile)
    savefile.close()
    #Open savefile for all mocks' fit and samples
    mockparams = []
    mocksamples = []
    for ii in range(_NMOCKS):
        savefile = open(_MOCKFIT[ii], 'rb')
        mockparams.append(pickle.load(savefile))
        savefile.close()
        savefile = open(_MOCKSAMPLES[ii], 'rb')
        mocksamples.append(pickle.load(savefile))
        savefile.close()
    #Set up sections
    names = [
        '$V_c(R_0)\ [\mathrm{km\ s}^{-1}]$', '$R_0\ [\mathrm{kpc}]$',
        '$V_{R,\odot}\ [\mathrm{km\ s}^{-1}]$',
        '$\Omega_{\odot}\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
        '$\\sigma_R(R_0)\ [\mathrm{km\ s}^{-1}]$', '$R_0/h_\sigma$',
        '$X^2 \equiv \sigma_\phi^2 / \sigma_R^2$',
        '$\Delta\chi^2/\mathrm{dof}$'
    ]
    scale = [_REFV0, _REFR0, _VRSUN, 1., _REFV0, 1., 1., 1.]
    flatbestfits = []
    flatxs = []
    mockbestfits = []
    mockxs = []
    #V_c
    flatbestfits.append(flatparams[0])
    flatxs.append(numpy.array([s[0] for s in flatsamples]))
    #R_0
    flatbestfits.append(flatparams[1])
    flatxs.append(numpy.array([s[1] for s in flatsamples]))
    #VRsun
    flatbestfits.append(flatparams[6])
    flatxs.append(numpy.array([s[6] for s in flatsamples]))
    #Omega_sun
    flatbestfits.append(flatparams[7] * _PMSGRA)
    flatxs.append(numpy.array([s[7] * _PMSGRA for s in flatsamples]))
    #\sigma_R(R_0)
    flatbestfits.append(numpy.exp(flatparams[2]))
    flatxs.append(numpy.exp(numpy.array([s[2] for s in flatsamples])))
    #R_0/h_sigma
    flatbestfits.append(flatparams[1] * flatparams[9])
    flatxs.append(numpy.array([s[1] * s[9] for s in flatsamples]))
    #X^2
    flatbestfits.append(flatparams[8])
    flatxs.append(numpy.array([s[8] for s in flatsamples]))
    #chi2
    options = set_options(None)
    data = readVclosData(validfeh=True)
    options.isofile = '../fits/isos.dat'
    thislogl = logl.logl(init=flatparams, options=options, data=data)
    flatbestfits.append(-2. * numpy.sum(thislogl) /
                        (len(data) - len(flatparams)))
    if _INDIVCHI2:
        locs = numpy.array(sorted(list(set(data['LOCATION']))))
        nlocs = len(locs)
        platel = numpy.zeros(nlocs)
        for ii in range(nlocs):
            indx = (data['LOCATION'] == locs[ii])
            platel[ii] = numpy.mean(data['GLON'][indx])
            sortindx = numpy.argsort(platel)
            locs = locs[sortindx]
            platel = platel[sortindx]

            for jj in range(len(locs)):
                names.append(
                    '$\Delta\chi^2/\mathrm{dof}\ \mathrm{w/o}\ l=%i^\circ$' %
                    int(round(platel[jj])))
                scale.append(1.)
                indx = (data['LOCATION'] != locs[jj])
                flatbestfits.append(-2. * numpy.sum(thislogl[indx]) /
                                    (len(data[indx]) - len(flatparams)))
    else:
        locs = []
    ##Same for all mocks
    for ii in range(_NMOCKS):
        thisbestfits = []
        thisxs = []
        #V_c
        thisbestfits.append(mockparams[ii][0])
        thisxs.append(numpy.array([s[0] for s in mocksamples[ii]]))
        #R_0
        thisbestfits.append(mockparams[ii][1])
        thisxs.append(numpy.array([s[1] for s in mocksamples[ii]]))
        #VRsun
        thisbestfits.append(mockparams[ii][6])
        thisxs.append(numpy.array([s[6] for s in mocksamples[ii]]))
        #Omega_sun
        thisbestfits.append(mockparams[ii][7] * _PMSGRA)
        thisxs.append(numpy.array([s[7] * _PMSGRA for s in mocksamples[ii]]))
        #\sigma_R(R_0)
        thisbestfits.append(numpy.exp(mockparams[ii][2]))
        thisxs.append(numpy.exp(numpy.array([s[2] for s in mocksamples[ii]])))
        #R_0/h_sigma
        thisbestfits.append(mockparams[ii][1] * mockparams[ii][9])
        thisxs.append(numpy.array([s[1] * s[9] for s in mocksamples[ii]]))
        #X^2
        thisbestfits.append(mockparams[ii][8])
        thisxs.append(numpy.array([s[8] for s in mocksamples[ii]]))
        #chi2
        #Load mock data
        data = readVclosData(datafilename=_MOCKDATA[ii])
        thislogl = logl.logl(init=mockparams[ii], data=data, options=options)
        thisbestfits.append(-2. * numpy.sum(thislogl) /
                            (len(data) - len(mockparams[ii])))
        if _INDIVCHI2:
            for jj in range(len(locs)):
                indx = (data['LOCATION'] != locs[jj])
                thisbestfits.append(-2. * numpy.sum(thislogl[indx]) /
                                    (len(data[indx]) - len(mockparams)))
        #Append all
        mockbestfits.append(thisbestfits)
        mockxs.append(thisxs)
    #Make table
    quantile = 0.68
    outfile = open(args[0], 'w')
    for ii in range(len(names)):
        #Set up line
        printline = names[ii]
        #Flat
        printline += ' & '
        if ii >= len(names) - (len(locs) + 1):  #chi2
            printline += ' \ldots & '
        else:
            bestfit = flatbestfits[ii] * scale[ii]
            xs = flatxs[ii] * scale[ii]
            lowval, highval = sixtyeigthinterval(bestfit,
                                                 xs,
                                                 quantile=quantile)
            dlow, dhigh = bestfit - lowval, highval - bestfit
            #Prepare
            maxerr = numpy.amin(numpy.fabs([dlow, dhigh]))
            print names[ii], maxerr
            if math.log10(maxerr) >= 0.:
                value = '$%.0f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 1.:
                    err = '$\pm$%.0f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.0f}_{-%.0f}$' % (dhigh, dlow)
            elif math.log10(maxerr) >= -1.:
                value = '$%.1f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.1:
                    err = '$\pm$%.1f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.1f}_{-%.1f}$' % (dhigh, dlow)
            elif math.log10(maxerr) >= -2.:
                value = '$%.2f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.01:
                    err = '$\pm$%.2f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.2f}_{-%.2f}$' % (dhigh, dlow)
            elif math.log10(maxerr) >= -3.:
                value = '$%.3f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.001:
                    err = '$\pm$%.3f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.3f}_{-%.3f}$' % (dhigh, dlow)
            else:
                value = '$%.4f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.0001:
                    err = '$\pm$%.4f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.4f}_{-%.4f}$' % (dhigh, dlow)
            printline += value + '&' + err
        #Mocks
        for jj in range(_NMOCKS):
            printline += ' & '
            if ii >= len(names) - (len(locs) + 1):  #chi2
                bestfit = mockbestfits[jj][ii] * scale[ii] - flatbestfits[
                    ii] * scale[ii]
                printline += '$%.2f$ & ' % bestfit
                if jj == _NMOCKS - 1:
                    if not ii == (len(names) - 1):
                        printline += '\\\\'
                    outfile.write(printline + '\n')
                continue
            bestfit = mockbestfits[jj][ii] * scale[ii]
            xs = mockxs[jj][ii] * scale[ii]
            lowval, highval = sixtyeigthinterval(bestfit,
                                                 xs,
                                                 quantile=quantile)
            dlow, dhigh = bestfit - lowval, highval - bestfit
            #Prepare
            maxerr = numpy.amin(numpy.fabs([dlow, dhigh]))
            if math.log10(maxerr) >= 0.:
                value = '$%.0f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 1.:
                    err = '$\pm$%.0f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.0f}_{-%.0f}$' % (dhigh, dlow)
            elif math.log10(maxerr) >= -1.:
                value = '$%.1f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.1:
                    err = '$\pm$%.1f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.1f}_{-%.1f}$' % (dhigh, dlow)
            elif math.log10(maxerr) >= -2.:
                value = '$%.2f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.01:
                    err = '$\pm$%.2f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.2f}_{-%.2f}$' % (dhigh, dlow)
            elif math.log10(maxerr) >= -3.:
                value = '$%.3f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.001:
                    err = '$\pm$%.3f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.3f}_{-%.3f}$' % (dhigh, dlow)
            else:
                value = '$%.4f$' % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.0001:
                    err = '$\pm$%.4f' % ((dlow + dhigh) / 2.)
                else:
                    err = '$^{+%.4f}_{-%.4f}$' % (dhigh, dlow)
            printline += value + '&' + err
        if not ii == (len(names) - 1):
            printline += '\\\\'
        if ii == (len(names) - (len(locs) + 2)):
            printline += '\\\\'
        if ii < (len(names) - (len(locs) + 1)):
            outfile.write(printline + '\n')
    outfile.write('\\enddata\n')
    outfile.write(cmdline + '\n')
    outfile.close()
Example #12
0
def plot_internalcomparison(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    #data= data[0:20]
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        if options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:    
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Calculate data means etc.
    #Calculate means
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    if not options.index is None:
        params= params[options.index]
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf= None
    avg_plate_model_fid= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #Plot everything
    bovy_plot.bovy_print(fig_height=10.,fig_width=7.)
    dx= 0.8/9.
    left, bottom, width, height= 0.1, 0.9, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'ko',overplot=True)
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$',top_right=True,size=14.)
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Second is Dehnen
    fid_dfmodel= options.dfmodel
    options.dfmodel= 'dehnen'
    avg_plate_model= avg_plate_model_fid 
    #avg_plate_model= calc_model(params,options,data,
    #                            logpiso,logpisodwarf,
    #                            df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{Dehnen\ DF}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Third = hR= 2. kpc
    fid_hr= options.hr
    options.dfmodel= fid_dfmodel
    options.hr= 2.
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-2.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$h_R = 2\ \mathrm{kpc}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Fourth = hR= 4. kpc
    options.dfmodel= fid_dfmodel
    options.hr= 4.
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-3.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$h_R = 4\ \mathrm{kpc}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Fifth = hs= 5. kpc
    fid_hs= options.hs
    options.hr= fid_hr
    options.hs= 5.
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-4.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$h_\sigma = 5\ \mathrm{kpc}$',top_right=True,size=14.)
    pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}\ [\mathrm{km\ s}^{-1}]$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Sixth: multiple pops
    options.hs= fid_hs
    options.dfmodel= 'multiplepops'
    fid_params=copy.copy(params)
    params[2]= -1.8
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-5.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{Multiple\ populations,\ SFR} = \exp\left( -t/8\ \mathrm{Gyr}\right)$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Seventh: cut multiples
    options.dfmodel= fid_dfmodel
    params= fid_params
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=True,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                              +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    l_plate_fid= l_plate
    avg_plate_fid= avg_plate
    siga_plate_fid= siga_plate
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-6.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate_fid,
                        avg_plate_fid-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate_fid,avg_plate_fid-avg_plate_model_fid,
                    yerr=siga_plate_fid,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{Multiple\ visit\ dispersion} < 1\ \mathrm{km\ s}^{-1}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Eight b=2
    options.dfmodel= fid_dfmodel
    params= fid_params
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=10.,
                        meanb=4.,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                              +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-7.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate_fid,
                        avg_plate_fid-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate_fid,avg_plate_fid-avg_plate_model_fid,
                    yerr=siga_plate_fid,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$b = 4^\circ\ \mathrm{fields}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Nintht b=-2
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=10.,
                        meanb=-4.,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-8.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate_fid,
                        avg_plate_fid-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate_fid,avg_plate_fid-avg_plate_model_fid,
                    yerr=siga_plate_fid,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$b = -4^\circ\ \mathrm{fields}$',top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Example #13
0
def mockTable(parser):
    (options, args) = parser.parse_args()
    cmdline = "%python mockTable.py " + args[0]
    if len(args) == 0:
        parser.print_help()
        return
    # Open savefile for flat fit and samples
    savefile = open(_FLATFIT, "rb")
    flatparams = pickle.load(savefile)
    savefile.close()
    savefile = open(_FLATSAMPLES, "rb")
    flatsamples = pickle.load(savefile)
    savefile.close()
    # Open savefile for all mocks' fit and samples
    mockparams = []
    mocksamples = []
    for ii in range(_NMOCKS):
        savefile = open(_MOCKFIT[ii], "rb")
        mockparams.append(pickle.load(savefile))
        savefile.close()
        savefile = open(_MOCKSAMPLES[ii], "rb")
        mocksamples.append(pickle.load(savefile))
        savefile.close()
    # Set up sections
    names = [
        "$V_c(R_0)\ [\mathrm{km\ s}^{-1}]$",
        "$R_0\ [\mathrm{kpc}]$",
        "$V_{R,\odot}\ [\mathrm{km\ s}^{-1}]$",
        "$\Omega_{\odot}\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$",
        "$\\sigma_R(R_0)\ [\mathrm{km\ s}^{-1}]$",
        "$R_0/h_\sigma$",
        "$X^2 \equiv \sigma_\phi^2 / \sigma_R^2$",
        "$\Delta\chi^2/\mathrm{dof}$",
    ]
    scale = [_REFV0, _REFR0, _VRSUN, 1.0, _REFV0, 1.0, 1.0, 1.0]
    flatbestfits = []
    flatxs = []
    mockbestfits = []
    mockxs = []
    # V_c
    flatbestfits.append(flatparams[0])
    flatxs.append(numpy.array([s[0] for s in flatsamples]))
    # R_0
    flatbestfits.append(flatparams[1])
    flatxs.append(numpy.array([s[1] for s in flatsamples]))
    # VRsun
    flatbestfits.append(flatparams[6])
    flatxs.append(numpy.array([s[6] for s in flatsamples]))
    # Omega_sun
    flatbestfits.append(flatparams[7] * _PMSGRA)
    flatxs.append(numpy.array([s[7] * _PMSGRA for s in flatsamples]))
    # \sigma_R(R_0)
    flatbestfits.append(numpy.exp(flatparams[2]))
    flatxs.append(numpy.exp(numpy.array([s[2] for s in flatsamples])))
    # R_0/h_sigma
    flatbestfits.append(flatparams[1] * flatparams[9])
    flatxs.append(numpy.array([s[1] * s[9] for s in flatsamples]))
    # X^2
    flatbestfits.append(flatparams[8])
    flatxs.append(numpy.array([s[8] for s in flatsamples]))
    # chi2
    options = set_options(None)
    data = readVclosData(validfeh=True)
    options.isofile = "../fits/isos.dat"
    thislogl = logl.logl(init=flatparams, options=options, data=data)
    flatbestfits.append(-2.0 * numpy.sum(thislogl) / (len(data) - len(flatparams)))
    if _INDIVCHI2:
        locs = numpy.array(sorted(list(set(data["LOCATION"]))))
        nlocs = len(locs)
        platel = numpy.zeros(nlocs)
        for ii in range(nlocs):
            indx = data["LOCATION"] == locs[ii]
            platel[ii] = numpy.mean(data["GLON"][indx])
            sortindx = numpy.argsort(platel)
            locs = locs[sortindx]
            platel = platel[sortindx]

            for jj in range(len(locs)):
                names.append("$\Delta\chi^2/\mathrm{dof}\ \mathrm{w/o}\ l=%i^\circ$" % int(round(platel[jj])))
                scale.append(1.0)
                indx = data["LOCATION"] != locs[jj]
                flatbestfits.append(-2.0 * numpy.sum(thislogl[indx]) / (len(data[indx]) - len(flatparams)))
    else:
        locs = []
    ##Same for all mocks
    for ii in range(_NMOCKS):
        thisbestfits = []
        thisxs = []
        # V_c
        thisbestfits.append(mockparams[ii][0])
        thisxs.append(numpy.array([s[0] for s in mocksamples[ii]]))
        # R_0
        thisbestfits.append(mockparams[ii][1])
        thisxs.append(numpy.array([s[1] for s in mocksamples[ii]]))
        # VRsun
        thisbestfits.append(mockparams[ii][6])
        thisxs.append(numpy.array([s[6] for s in mocksamples[ii]]))
        # Omega_sun
        thisbestfits.append(mockparams[ii][7] * _PMSGRA)
        thisxs.append(numpy.array([s[7] * _PMSGRA for s in mocksamples[ii]]))
        # \sigma_R(R_0)
        thisbestfits.append(numpy.exp(mockparams[ii][2]))
        thisxs.append(numpy.exp(numpy.array([s[2] for s in mocksamples[ii]])))
        # R_0/h_sigma
        thisbestfits.append(mockparams[ii][1] * mockparams[ii][9])
        thisxs.append(numpy.array([s[1] * s[9] for s in mocksamples[ii]]))
        # X^2
        thisbestfits.append(mockparams[ii][8])
        thisxs.append(numpy.array([s[8] for s in mocksamples[ii]]))
        # chi2
        # Load mock data
        data = readVclosData(datafilename=_MOCKDATA[ii])
        thislogl = logl.logl(init=mockparams[ii], data=data, options=options)
        thisbestfits.append(-2.0 * numpy.sum(thislogl) / (len(data) - len(mockparams[ii])))
        if _INDIVCHI2:
            for jj in range(len(locs)):
                indx = data["LOCATION"] != locs[jj]
                thisbestfits.append(-2.0 * numpy.sum(thislogl[indx]) / (len(data[indx]) - len(mockparams)))
        # Append all
        mockbestfits.append(thisbestfits)
        mockxs.append(thisxs)
    # Make table
    quantile = 0.68
    outfile = open(args[0], "w")
    for ii in range(len(names)):
        # Set up line
        printline = names[ii]
        # Flat
        printline += " & "
        if ii >= len(names) - (len(locs) + 1):  # chi2
            printline += " \ldots & "
        else:
            bestfit = flatbestfits[ii] * scale[ii]
            xs = flatxs[ii] * scale[ii]
            lowval, highval = sixtyeigthinterval(bestfit, xs, quantile=quantile)
            dlow, dhigh = bestfit - lowval, highval - bestfit
            # Prepare
            maxerr = numpy.amin(numpy.fabs([dlow, dhigh]))
            print names[ii], maxerr
            if math.log10(maxerr) >= 0.0:
                value = "$%.0f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 1.0:
                    err = "$\pm$%.0f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.0f}_{-%.0f}$" % (dhigh, dlow)
            elif math.log10(maxerr) >= -1.0:
                value = "$%.1f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.1:
                    err = "$\pm$%.1f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.1f}_{-%.1f}$" % (dhigh, dlow)
            elif math.log10(maxerr) >= -2.0:
                value = "$%.2f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.01:
                    err = "$\pm$%.2f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.2f}_{-%.2f}$" % (dhigh, dlow)
            elif math.log10(maxerr) >= -3.0:
                value = "$%.3f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.001:
                    err = "$\pm$%.3f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.3f}_{-%.3f}$" % (dhigh, dlow)
            else:
                value = "$%.4f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.0001:
                    err = "$\pm$%.4f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.4f}_{-%.4f}$" % (dhigh, dlow)
            printline += value + "&" + err
        # Mocks
        for jj in range(_NMOCKS):
            printline += " & "
            if ii >= len(names) - (len(locs) + 1):  # chi2
                bestfit = mockbestfits[jj][ii] * scale[ii] - flatbestfits[ii] * scale[ii]
                printline += "$%.2f$ & " % bestfit
                if jj == _NMOCKS - 1:
                    if not ii == (len(names) - 1):
                        printline += "\\\\"
                    outfile.write(printline + "\n")
                continue
            bestfit = mockbestfits[jj][ii] * scale[ii]
            xs = mockxs[jj][ii] * scale[ii]
            lowval, highval = sixtyeigthinterval(bestfit, xs, quantile=quantile)
            dlow, dhigh = bestfit - lowval, highval - bestfit
            # Prepare
            maxerr = numpy.amin(numpy.fabs([dlow, dhigh]))
            if math.log10(maxerr) >= 0.0:
                value = "$%.0f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 1.0:
                    err = "$\pm$%.0f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.0f}_{-%.0f}$" % (dhigh, dlow)
            elif math.log10(maxerr) >= -1.0:
                value = "$%.1f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.1:
                    err = "$\pm$%.1f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.1f}_{-%.1f}$" % (dhigh, dlow)
            elif math.log10(maxerr) >= -2.0:
                value = "$%.2f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.01:
                    err = "$\pm$%.2f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.2f}_{-%.2f}$" % (dhigh, dlow)
            elif math.log10(maxerr) >= -3.0:
                value = "$%.3f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.001:
                    err = "$\pm$%.3f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.3f}_{-%.3f}$" % (dhigh, dlow)
            else:
                value = "$%.4f$" % (bestfit)
                if numpy.fabs((dlow - dhigh)) < 0.0001:
                    err = "$\pm$%.4f" % ((dlow + dhigh) / 2.0)
                else:
                    err = "$^{+%.4f}_{-%.4f}$" % (dhigh, dlow)
            printline += value + "&" + err
        if not ii == (len(names) - 1):
            printline += "\\\\"
        if ii == (len(names) - (len(locs) + 2)):
            printline += "\\\\"
        if ii < (len(names) - (len(locs) + 1)):
            outfile.write(printline + "\n")
    outfile.write("\\enddata\n")
    outfile.write(cmdline + "\n")
    outfile.close()
Example #14
0
def plot_chi2(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Cut inner disk locations
    #data= data[(data['GLON'] > 75.)]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        if options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    if not options.index is None:
        params= params[options.index]
    savefile.close()
    #params[0]= 245./235.
    #params[1]= 8.5/8.
    #Calculate data means etc.
    #Calculate means
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    sigerr_plate= numpy.zeros(nlocs)
    fidlogl= logl.logl(init=params,data=data,options=options)
    logl_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
        sigerr_plate[ii]= bootstrap_sigerr(data['VHELIO'][indx])
        #Logl
        logl_plate[ii]= -2.*(numpy.sum(fidlogl[indx])-numpy.sum(fidlogl)/len(indx)*numpy.sum(indx))
    #Calculate plate means and variances from the model
    avg_plate_model= numpy.zeros(nlocs)
    sig_plate_model= numpy.zeros(nlocs)
    for ii in range(nlocs):
        #Calculate vlos | los
        indx= (data['LOCATION'] == locations[ii])
        thesedata= data[indx]
        thislogpiso= logpiso[indx,:]
        if options.dwarf:
            thislogpisodwarf= logpisodwarf[indx,:]
        else:
            thislogpisodwarf= None
        vlos= numpy.linspace(-200.,200.,options.nvlos)
        pvlos= numpy.zeros(options.nvlos)
        if not options.multi is None:
            pvlos= multi.parallel_map((lambda x: pvlosplate(params,vlos[x],
                                                            thesedata,
                                                            df,options,
                                                            thislogpiso,
                                                            thislogpisodwarf,iso)),
                                      range(options.nvlos),
                                      numcores=numpy.amin([len(vlos),multiprocessing.cpu_count(),options.multi]))
        else:
            for jj in range(options.nvlos):
                print jj
                pvlos[jj]= pvlosplate(params,vlos[jj],thesedata,df,options,
                                      thislogpiso,thislogpisodwarf,iso)
        pvlos-= logsumexp(pvlos)
        pvlos= numpy.exp(pvlos)
        #Calculate mean and velocity dispersion
        avg_plate_model[ii]= numpy.sum(vlos*pvlos)
        sig_plate_model[ii]= numpy.sqrt(numpy.sum(vlos**2.*pvlos)\
                                            -avg_plate_model[ii]**2.)
    #Plot everything
    left, bottom, width, height= 0.1, 0.4, 0.8, 0.3
    axTop= pyplot.axes([left,bottom,width,height])
    left, bottom, width, height= 0.1, 0.1, 0.8, 0.3
    axChi2= pyplot.axes([left,bottom,width,height])
    #left, bottom, width, height= 0.1, 0.1, 0.8, 0.2
    #axSig= pyplot.axes([left,bottom,width,height])
    fig= pyplot.gcf()
    #Plot the difference
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'ko',overplot=True)
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',linestyle='none',elinestyle='-')
    pyplot.ylabel(r'$\langle v_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle v_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    pyplot.ylim(-14.5,14.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Plot the chi2
    fig.sca(axChi2)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        logl_plate,
                        'ko',overplot=True)
    pyplot.ylabel(r'$\Delta \chi^2$')
    #pyplot.ylim(numpy.amin(logl_plate),numpy.amax(logl_plate))
    pyplot.ylim(-150.,150.)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Example #15
0
#set up; kind of plot
justData= False
dataMean=False
noSolar= False
justSolar= False
betas, vcbetas= True, 250.
hrs= False
dmaxs= False
addNonAxi= False
#Data selection
nodups= True
fehcut= False
postshutdown= True
cohort= None
ext= 'png'
data= readVclosData(postshutdown=postshutdown,fehcut=fehcut,cohort=cohort)
#Calculate means
plates= list(set(data['PLATE']))
nplates= len(plates)
l_plate= numpy.zeros(nplates)
avg_plate= numpy.zeros(nplates)
sig_plate= numpy.zeros(nplates)
siga_plate= numpy.zeros(nplates)
for ii in range(nplates):
    indx= (data['PLATE'] == plates[ii])
    l_plate[ii]= numpy.mean(data['GLON'][indx])
    avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
    sig_plate[ii]= numpy.std(data['VHELIO'][indx])
    siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
#print sig_plate
#print l_plate
if __name__ == '__main__':
    #Get options
    parser= get_options()
    options,args= parser.parse_args()
    #Read data
    #AK quantiles?
    if not options.aklow is None:
        akquantiles= [options.aklow,options.akhigh]
    else:
        akquantiles= None
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        jkmax=options.jkmax,
                        datafilename=options.fakedata,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        akquantiles=akquantiles)
    if options.location == 0:
        locations= list(set(data['LOCATION']))
    else:
        locations= [options.location]
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Fit parameters
    if options.dwarf:
        params= [270./_REFV0,8./_REFR0,numpy.log(35./_REFV0),0.025,0.5,1.]
    else:
Example #17
0
def plot_bestfit(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    # Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  # if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata,
    )
    # HACK
    indx = data["J0MAG"] - data["K0MAG"] < 0.5
    data["J0MAG"][indx] = 0.5 + data["K0MAG"][indx]
    # Cut inner disk locations
    # data= data[(data['GLON'] > 75.)]
    # Cut outliers
    # data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    # Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, "rb")
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        if options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            # Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data["LOCATION"]))
            iso = []
            for ii in range(len(locs)):
                indx = data["LOCATION"] == locs[ii]
                locl = numpy.mean(data["GLON"][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel, expsfh=options.expsfh, marginalizefeh=True, glon=locl)
                )
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, expsfh=options.expsfh)
        if options.dwarf:
            iso = [iso, isomodel.isomodel(imfmodel=options.imfmodel, Z=options.Z, dwarf=True, expsfh=options.expsfh)]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, "wb")
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data["H0MAG"][ii] - dm
        if options.indivfeh:
            # Find closest Z
            thisZ = isodist.FEH2Z(data[ii]["FEH"])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        elif options.varfeh:
            # Find correct iso
            indx = locl == data[ii]["LOCATION"]
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF, _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data["H0MAG"][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) + (data["J0MAG"] - data["K0MAG"])[ii], mh)
    else:
        logpisodwarf = None
    # Calculate data means etc.
    # Calculate means
    locations = list(set(data["LOCATION"]))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    sigerr_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = data["LOCATION"] == locations[ii]
        l_plate[ii] = numpy.mean(data["GLON"][indx])
        avg_plate[ii] = numpy.mean(data["VHELIO"][indx])
        sig_plate[ii] = numpy.std(data["VHELIO"][indx])
        siga_plate[ii] = numpy.std(data["VHELIO"][indx]) / numpy.sqrt(numpy.sum(indx))
        sigerr_plate[ii] = bootstrap_sigerr(data["VHELIO"][indx])
    # Calculate plate means and variances from the model
    # Load initial parameters from file
    savefile = open(args[0], "rb")
    params = pickle.load(savefile)
    if not options.index is None:
        params = params[options.index]
    savefile.close()
    # params[0]= 245./235.
    # params[1]= 8.5/8.
    avg_plate_model = numpy.zeros(nlocs)
    sig_plate_model = numpy.zeros(nlocs)
    for ii in range(nlocs):
        # Calculate vlos | los
        indx = data["LOCATION"] == locations[ii]
        thesedata = data[indx]
        thislogpiso = logpiso[indx, :]
        if options.dwarf:
            thislogpisodwarf = logpisodwarf[indx, :]
        else:
            thislogpisodwarf = None
        vlos = numpy.linspace(-200.0, 200.0, options.nvlos)
        pvlos = numpy.zeros(options.nvlos)
        if not options.multi is None:
            pvlos = multi.parallel_map(
                (lambda x: pvlosplate(params, vlos[x], thesedata, df, options, thislogpiso, thislogpisodwarf, iso)),
                range(options.nvlos),
                numcores=numpy.amin([len(vlos), multiprocessing.cpu_count(), options.multi]),
            )
        else:
            for jj in range(options.nvlos):
                print jj
                pvlos[jj] = pvlosplate(params, vlos[jj], thesedata, df, options, thislogpiso, thislogpisodwarf, iso)
        pvlos -= logsumexp(pvlos)
        pvlos = numpy.exp(pvlos)
        # Calculate mean and velocity dispersion
        avg_plate_model[ii] = numpy.sum(vlos * pvlos)
        sig_plate_model[ii] = numpy.sqrt(numpy.sum(vlos ** 2.0 * pvlos) - avg_plate_model[ii] ** 2.0)
    # Plot everything
    left, bottom, width, height = 0.1, 0.4, 0.8, 0.5
    axTop = pyplot.axes([left, bottom, width, height])
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.3
    axMean = pyplot.axes([left, bottom, width, height])
    # left, bottom, width, height= 0.1, 0.1, 0.8, 0.2
    # axSig= pyplot.axes([left,bottom,width,height])
    fig = pyplot.gcf()
    fig.sca(axTop)
    pyplot.ylabel(r"$\mathrm{Heliocentric\ velocity}\ [\mathrm{km\ s}^{-1}]$")
    pyplot.xlabel(r"$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$")
    pyplot.xlim(0.0, 360.0)
    pyplot.ylim(-200.0, 200.0)
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_plot(data["GLON"], data["VHELIO"], "k,", yrange=[-200.0, 200.0], xrange=[0.0, 360.0], overplot=True)
    ndata_t = int(math.floor(len(data) / 1000.0))
    ndata_h = len(data) - ndata_t * 1000
    bovy_plot.bovy_plot(l_plate, avg_plate, "o", overplot=True, mfc="0.5", mec="none")
    bovy_plot.bovy_plot(l_plate, avg_plate_model, "x", overplot=True, ms=10.0, mew=1.5, color="0.7")
    # Legend
    bovy_plot.bovy_plot([260.0], [150.0], "k,", overplot=True)
    bovy_plot.bovy_plot([260.0], [120.0], "o", mfc="0.5", mec="none", overplot=True)
    bovy_plot.bovy_plot([260.0], [90.0], "x", ms=10.0, mew=1.5, color="0.7", overplot=True)
    bovy_plot.bovy_text(270.0, 145.0, r"$\mathrm{data}$")
    bovy_plot.bovy_text(270.0, 115.0, r"$\mathrm{data\ mean}$")
    bovy_plot.bovy_text(270.0, 85.0, r"$\mathrm{model\ mean}$")
    bovy_plot._add_ticks()
    # Now plot the difference
    fig.sca(axMean)
    bovy_plot.bovy_plot([0.0, 360.0], [0.0, 0.0], "-", color="0.5", overplot=True)
    bovy_plot.bovy_plot(l_plate, avg_plate - avg_plate_model, "ko", overplot=True)
    pyplot.errorbar(
        l_plate, avg_plate - avg_plate_model, yerr=siga_plate, marker="o", color="k", linestyle="none", elinestyle="-"
    )
    pyplot.ylabel(r"$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}}$")
    pyplot.ylim(-14.5, 14.5)
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # axMean.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r"$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$")
    pyplot.xlim(0.0, 360.0)
    bovy_plot._add_ticks()
    # Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
    # Sigma
    fig.sca(axSig)
    pyplot.plot([0.0, 360.0], [1.0, 1.0], "-", color="0.5")
    bovy_plot.bovy_plot(l_plate, sig_plate / sig_plate_model, "ko", overplot=True)
    pyplot.errorbar(
        l_plate,
        sig_plate / sig_plate_model,
        yerr=sigerr_plate / sig_plate_model,
        marker="o",
        color="k",
        linestyle="none",
        elinestyle="-",
    )
    pyplot.ylabel(r"$\sigma_{\mathrm{los}}^{\mathrm{data}}/ \sigma_{\mathrm{los}}^{\mathrm{model}}$")
    pyplot.ylim(0.5, 1.5)
def createFakeData(parser):
    options, args= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    if os.path.exists(options.plotfile):
        print "Outfile "+options.plotfile+" exists ..."
        print "Returning ..."
        return None
    #Read the data
    numpy.random.seed(options.seed)
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        jkmax=options.jkmax)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Set up the isochrone
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        elif options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso,
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    savefile.close()
    #Prep data
    l= data['GLON']*_DEGTORAD
    b= data['GLAT']*_DEGTORAD
    sinl= numpy.sin(l)
    cosl= numpy.cos(l)
    sinb= numpy.sin(b)
    cosb= numpy.cos(b)
    jk= data['J0MAG']-data['K0MAG']
    jk[(jk < 0.5)]= 0.5 #BOVY: FIX THIS HACK BY EMAILING GAIL
    h= data['H0MAG']
    #Re-sample
    vlos= numpy.linspace(-200.,200.,options.nvlos)
    pvlos= numpy.zeros((len(data),options.nvlos))
    if options.dwarf:
        thislogpisodwarf= logpisodwarf
    else:
        thislogpisodwarf= None
    if not options.multi is None and options.multi > 1:
        thismulti= options.multi
        options.multi= 1 #To avoid conflict
        thispvlos= multi.parallel_map((lambda x: -mloglike(params,
                                                           numpy.zeros(len(data))+vlos[x],
                                                           l,
                                                           b,
                                                           jk,
                                                           h,
                                                           df,options,
                                                           sinl,
                                                           cosl,
                                                           cosb,
                                                           sinb,
                                                           logpiso,
                                                           thislogpisodwarf,
                                                           True,
                                                           None,None,None)),
                                      range(options.nvlos),
                                      numcores=numpy.amin([len(vlos),multiprocessing.cpu_count(),thismulti]))
        for jj in range(options.nvlos):
            pvlos[:,jj]= thispvlos[jj]
    else:
        for jj in range(options.nvlos):
            pvlos[:,jj]= -mloglike(params,numpy.zeros(len(data))+vlos[jj],
                                   l,
                                   b,
                                   jk,
                                   h,
                                   df,options,
                                   sinl,
                                   cosl,
                                   cosb,
                                   sinb,
                                   logpiso,
                                   thislogpisodwarf,True,None,None,None)
    """
    for jj in range(options.nvlos):
        pvlos[:,jj]= -mloglike(params,numpy.zeros(len(data))+vlos[jj],
                               l,
                               b,
                               jk,
                               h,
                               df,options,
                               sinl,
                               cosl,
                               cosb,
                               sinb,
                               logpiso,
                               thislogpisodwarf,True,None,None,None)
    """
    for ii in range(len(data)):
        pvlos[ii,:]-= logsumexp(pvlos[ii,:])
        pvlos[ii,:]= numpy.exp(pvlos[ii,:])
        pvlos[ii,:]= numpy.cumsum(pvlos[ii,:])
        pvlos[ii,:]/= pvlos[ii,-1]
        #Draw
        randindx= numpy.random.uniform()
        kk= 0
        while pvlos[ii,kk] < randindx:
            kk+= 1
        data['VHELIO'][ii]= vlos[kk]
    #Dump raw
    fitsio.write(options.plotfile,data,clobber=True)
Example #19
0
def plot_lb():
    #Read basic data
    data = readVclosData()
    ndata = len(data)
    if _PLOTHIGHB:
        yrange = [-6., 6.]
    else:
        yrange = [-2.5, 2.5]
    #Plot
    if OUTEXT == 'ps':
        bovy_plot.bovy_print(fig_width=8.5, fig_height=6. / 16. * 8.5)
    else:
        bovy_plot.bovy_print(fig_width=16., fig_height=6.)
    fig = pyplot.figure()
    #Set up axes
    nullfmt = NullFormatter()  # no labels
    # definitions for the axes
    left, width = 0.1, 0.7
    bottom, height = 0.1, 0.85
    bottom_h = left_h = left + width
    rect_scatter = [left, bottom, width, height]
    rect_histy = [left_h, bottom, 0.15, height]
    axScatter = pyplot.axes(rect_scatter)
    axHisty = pyplot.axes(rect_histy)
    # no labels
    axHisty.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)
    fig.sca(axScatter)
    bovy_plot.bovy_plot(data['GLON'],
                        data['GLAT'],
                        'k.',
                        ms=1.5,
                        overplot=True)
    pyplot.xlim(0., 250.)
    pyplot.ylim(yrange[0], yrange[1])
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ l\ \mathrm{[deg]}$')
    pyplot.ylabel(r'$\mathrm{Galactic\ latitude}\ b\ \mathrm{[deg]}$')
    bovy_plot._add_ticks()
    #bovy_plot.bovy_end_print(os.path.join(OUTDIR,'data_lb.'+OUTEXT))
    if _PLOTHIGHB:
        #Read other data
        otherdata = readVclosData(meanb=-4., bmax=10.)
        nmdata = len(otherdata)
        otherl = list(otherdata['GLON'])
        otherb = list(otherdata['GLAT'])
        otherdata2 = readVclosData(meanb=4., bmax=10.)
        npdata = len(otherdata2)
        otherl.extend(list(otherdata2['GLON']))
        otherb.extend(list(otherdata2['GLAT']))
        bovy_plot.bovy_plot(otherl,
                            otherb,
                            '.',
                            mec='0.5',
                            mfc='0.5',
                            ms=1.5,
                            overplot=True)
        #Add histogram of bs
        otherl.extend(list(data['GLON']))
        otherb.extend(list(data['GLAT']))
    else:
        #Add histogram of bs
        otherl = list(data['GLON'])
        otherb = list(data['GLAT'])
        nmdata, npdata = 0, 0
    histy, edges, patches = axHisty.hist(otherb,
                                         bins=49,
                                         orientation='horizontal',
                                         normed=True,
                                         histtype='step',
                                         range=yrange,
                                         color='k',
                                         zorder=2)
    #Overlay predictions
    #Center, constant
    ys = numpy.linspace(-1.5, 1.5, 1001)
    pdf = numpy.sqrt(1.5**2. - ys**2.)
    pdf *= float(ndata) / (ndata + nmdata + npdata) / numpy.sum(pdf) / (ys[1] -
                                                                        ys[0])
    axHisty.plot(pdf, ys, 'k-', zorder=-2)
    constpdf = pdf
    #Center, exponential disk
    """
    dfc= dehnendf(beta=0.,correct=True,niter=20)
    pdf= numpy.zeros(len(ys))
    plates= list(set(data['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= data[(data['PLATE'] == plates[ii])]
        thisl= numpy.mean(data['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(ys[jj],thisl,0.,dmax/ro,0.,dfc,hz/ro)
        pdf+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdf*= float(ndata)/(ndata+nmdata+npdata)/numpy.sum(pdf)/(ys[1]-ys[0])
    axHisty.plot(pdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    #axHisty.plot(.8*pdf+.2*constpdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    """
    if _PLOTHIGHB:
        #positive b, constant
        constpdf *= float(npdata) / ndata
        axHisty.plot(constpdf, ys + 4., 'k-', zorder=-2)
        """
        #Positive, exponential disk
        pdfp= numpy.zeros(len(ys))
        plates= list(set(otherdata2['PLATE']))
        for ii in range(len(plates)):
            print ii
            #For each plate, calculate pdf and add with data weights
            thisdata= otherdata2[(otherdata2['PLATE'] == plates[ii])]
            thisl= numpy.mean(otherdata2['GLON'])
            thisndata= len(thisdata)
            thispdf= numpy.zeros(len(ys))
            for jj in range(len(ys)):
                thispdf[jj]= surfacemassLOSd(4.+ys[jj],
                thisl,0.,dmax/ro,4.,dfc,hz/ro)
            pdfp+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
        pdfp*= float(npdata)/(ndata+nmdata+npdata)/numpy.sum(pdfp)/(ys[1]-ys[0])
        axHisty.plot(pdfp,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        #axHisty.plot(.8*pdfp+.2*constpdf,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        """
        #negative b, constant
        constpdf *= nmdata / float(npdata)
        axHisty.plot(constpdf, ys - 4., 'k-', zorder=-2.)
    """
    #Negative, exponential disk
    pdfm= numpy.zeros(len(ys))
    plates= list(set(otherdata['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= otherdata[(otherdata['PLATE'] == plates[ii])]
        thisl= numpy.mean(otherdata['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(-4.+ys[jj],
                                          thisl,0.,dmax/ro,-4.,dfc,hz/ro)
        pdfm+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdfm*= float(nmdata)/(ndata+nmdata+npdata)/numpy.sum(pdfm)/(ys[1]-ys[0])
    axHisty.plot(pdfm,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    #axHisty.plot(.8*pdfm+.2*constpdf,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    """
    axHisty.set_ylim(yrange[0], yrange[1])
    axHisty.set_xlim(0, 1.2 * numpy.amax(histy))
    pyplot.sca(axHisty)
    bovy_plot._add_ticks()
    bovy_plot.bovy_end_print(os.path.join(OUTDIR, 'data_lb.' + OUTEXT))
    return None
Example #20
0
def plot_bestfit(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata)
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    #Cut inner disk locations
    #data= data[(data['GLON'] > 75.)]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    print "Using %i data points ..." % len(data)
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        if options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
        if options.dwarf:
            iso = [
                iso,
                isomodel.isomodel(imfmodel=options.imfmodel,
                                  Z=options.Z,
                                  dwarf=True,
                                  expsfh=options.expsfh)
            ]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, 'wb')
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data['H0MAG'][ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) +
                                    (data['J0MAG'] - data['K0MAG'])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF,
                                 _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data['H0MAG'][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) +
                                         (data['J0MAG'] - data['K0MAG'])[ii],
                                         mh)
    else:
        logpisodwarf = None
    #Calculate data means etc.
    #Calculate means
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    sigerr_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
        avg_plate[ii] = numpy.mean(data['VHELIO'][indx])
        sig_plate[ii] = numpy.std(data['VHELIO'][indx])
        siga_plate[ii] = numpy.std(data['VHELIO'][indx]) / numpy.sqrt(
            numpy.sum(indx))
        sigerr_plate[ii] = bootstrap_sigerr(data['VHELIO'][indx])
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile = open(args[0], 'rb')
    params = pickle.load(savefile)
    if not options.index is None:
        params = params[options.index]
    savefile.close()
    #params[0]= 245./235.
    #params[1]= 8.5/8.
    avg_plate_model = numpy.zeros(nlocs)
    sig_plate_model = numpy.zeros(nlocs)
    for ii in range(nlocs):
        #Calculate vlos | los
        indx = (data['LOCATION'] == locations[ii])
        thesedata = data[indx]
        thislogpiso = logpiso[indx, :]
        if options.dwarf:
            thislogpisodwarf = logpisodwarf[indx, :]
        else:
            thislogpisodwarf = None
        vlos = numpy.linspace(-200., 200., options.nvlos)
        pvlos = numpy.zeros(options.nvlos)
        if not options.multi is None:
            pvlos = multi.parallel_map(
                (lambda x: pvlosplate(params, vlos[x], thesedata, df, options,
                                      thislogpiso, thislogpisodwarf, iso)),
                range(options.nvlos),
                numcores=numpy.amin(
                    [len(vlos),
                     multiprocessing.cpu_count(), options.multi]))
        else:
            for jj in range(options.nvlos):
                print jj
                pvlos[jj] = pvlosplate(params, vlos[jj], thesedata, df,
                                       options, thislogpiso, thislogpisodwarf,
                                       iso)
        pvlos -= logsumexp(pvlos)
        pvlos = numpy.exp(pvlos)
        #Calculate mean and velocity dispersion
        avg_plate_model[ii] = numpy.sum(vlos * pvlos)
        sig_plate_model[ii]= numpy.sqrt(numpy.sum(vlos**2.*pvlos)\
                                            -avg_plate_model[ii]**2.)
    #Plot everything
    left, bottom, width, height = 0.1, 0.4, 0.8, 0.5
    axTop = pyplot.axes([left, bottom, width, height])
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.3
    axMean = pyplot.axes([left, bottom, width, height])
    #left, bottom, width, height= 0.1, 0.1, 0.8, 0.2
    #axSig= pyplot.axes([left,bottom,width,height])
    fig = pyplot.gcf()
    fig.sca(axTop)
    pyplot.ylabel(r'$\mathrm{Heliocentric\ velocity}\ [\mathrm{km\ s}^{-1}]$')
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    pyplot.ylim(-200., 200.)
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_plot(data['GLON'],
                        data['VHELIO'],
                        'k,',
                        yrange=[-200., 200.],
                        xrange=[0., 360.],
                        overplot=True)
    ndata_t = int(math.floor(len(data) / 1000.))
    ndata_h = len(data) - ndata_t * 1000
    bovy_plot.bovy_plot(l_plate,
                        avg_plate,
                        'o',
                        overplot=True,
                        mfc='0.5',
                        mec='none')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate_model,
                        'x',
                        overplot=True,
                        ms=10.,
                        mew=1.5,
                        color='0.7')
    #Legend
    bovy_plot.bovy_plot([260.], [150.], 'k,', overplot=True)
    bovy_plot.bovy_plot([260.], [120.],
                        'o',
                        mfc='0.5',
                        mec='none',
                        overplot=True)
    bovy_plot.bovy_plot([260.], [90.],
                        'x',
                        ms=10.,
                        mew=1.5,
                        color='0.7',
                        overplot=True)
    bovy_plot.bovy_text(270., 145., r'$\mathrm{data}$')
    bovy_plot.bovy_text(270., 115., r'$\mathrm{data\ mean}$')
    bovy_plot.bovy_text(270., 85., r'$\mathrm{model\ mean}$')
    bovy_plot._add_ticks()
    #Now plot the difference
    fig.sca(axMean)
    bovy_plot.bovy_plot([0., 360.], [0., 0.], '-', color='0.5', overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    pyplot.ylabel(r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}}$')
    pyplot.ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #axMean.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
    #Sigma
    fig.sca(axSig)
    pyplot.plot([0., 360.], [1., 1.], '-', color='0.5')
    bovy_plot.bovy_plot(l_plate,
                        sig_plate / sig_plate_model,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    sig_plate / sig_plate_model,
                    yerr=sigerr_plate / sig_plate_model,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    pyplot.ylabel(
        r'$\sigma_{\mathrm{los}}^{\mathrm{data}}/ \sigma_{\mathrm{los}}^{\mathrm{model}}$'
    )
    pyplot.ylim(0.5, 1.5)
Example #21
0
def plot_distanceprior(parser):
    (options, args) = parser.parse_args()
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata)
    l = data['GLON'] * _DEGTORAD
    b = data['GLAT'] * _DEGTORAD
    sinl = numpy.sin(l)
    cosl = numpy.cos(l)
    sinb = numpy.sin(b)
    cosb = numpy.cos(b)
    jk = data['J0MAG'] - data['K0MAG']
    jk[(jk < 0.5)] = 0.5  #BOVY: FIX THIS HACK BY EMAILING GAIL
    h = data['H0MAG']
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
    #Set up polar grid
    res = 51
    xgrid = numpy.linspace(0., 2. * math.pi * (1. - 1. / res / 2.), 2 * res)
    ygrid = numpy.linspace(0.5, 2.8, res)
    plotxgrid = numpy.linspace(xgrid[0] - (xgrid[1] - xgrid[0]) / 2.,
                               xgrid[-1] + (xgrid[1] - xgrid[0]) / 2.,
                               len(xgrid) + 1)
    plotygrid = numpy.linspace(ygrid[0] - (ygrid[1] - ygrid[0]) / 2.,
                               ygrid[-1] + (ygrid[1] - ygrid[0]) / 2.,
                               len(ygrid) + 1)
    plotthis = numpy.zeros((2 * res, res, len(data))) - numpy.finfo(
        numpy.dtype(numpy.float64)).max
    #_BINTEGRATENBINS= 11 #For quick testing
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = h[ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          jk[ii], mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          jk[ii], mh)
        else:
            logpiso[ii, :] = iso(numpy.zeros(_BINTEGRATENBINS) + jk[ii], mh)
    for jj in range(_BINTEGRATENBINS):
        d = ds[jj] / _REFR0
        R = numpy.sqrt(1. + d**2. - 2. * d * cosl)
        indx = (R == 0.)
        R[indx] += 0.0001
        theta = numpy.arcsin(d / R * sinl)
        indx = (1. / cosl < d) * (cosl > 0.)
        theta[indx] = numpy.pi - theta[indx]
        indx = (theta < 0.)
        theta[indx] += 2. * math.pi
        thisout = _logpd([0., 1.], d, None, None, None, None, None, options, R,
                         theta, 1., 0., logpiso[:, jj])
        #Find bin to which these contribute
        thetabin = numpy.floor((theta - xgrid[0]) / (xgrid[1] - xgrid[0]) +
                               0.5)
        Rbin = numpy.floor((R - plotygrid[0]) / (plotygrid[1] - plotygrid[0]))
        indx = (thetabin < 0)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (thetabin >= 2 * res)
        thetabin[indx] = 0.  #Has to be
        #Rbin[indx]= 0
        #thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (Rbin < 0)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (Rbin >= res)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        thetabin = thetabin.astype('int')
        Rbin = Rbin.astype('int')
        for ii in range(len(data)):
            plotthis[thetabin, Rbin, ii] = thisout[ii]
    #Normalize
    for ii in range(2 * res):
        for jj in range(res):
            plotthis[ii, jj, 0] = logsumexp(plotthis[ii, jj, :])
    plotthis = plotthis[:, :, 0]
    plotthis -= numpy.amax(plotthis)
    plotthis = numpy.exp(plotthis)
    plotthis[(plotthis == 0.)] = numpy.nan
    #Get los
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
    bovy_plot.bovy_print()
    ax = pyplot.subplot(111, projection='galpolar')  #galpolar is in bovy_plot
    vmin, vmax = 0., 1.
    out = ax.pcolor(plotxgrid,
                    plotygrid,
                    plotthis.T,
                    cmap='gist_yarg',
                    vmin=vmin,
                    vmax=vmax,
                    zorder=2)
    #Overlay los
    for ii in range(nlocs):
        lds = numpy.linspace(0., 2.95, 501)
        lt = numpy.zeros(len(lds))
        lr = numpy.zeros(len(lds))
        lr = numpy.sqrt(1. + lds**2. -
                        2. * lds * numpy.cos(l_plate[ii] * _DEGTORAD))
        lt = numpy.arcsin(lds / lr * numpy.sin(l_plate[ii] * _DEGTORAD))
        indx = (1. / numpy.cos(l_plate[ii] * _DEGTORAD) < lds) * (numpy.cos(
            l_plate[ii] * _DEGTORAD) > 0.)
        lt[indx] = numpy.pi - lt[indx]
        ax.plot(lt, lr, ls='--', color='w', zorder=3)
    from matplotlib.patches import Arrow, FancyArrowPatch
    arr = FancyArrowPatch(posA=(-math.pi / 2., 1.8),
                          posB=(-math.pi / 4., 1.8),
                          arrowstyle='->',
                          connectionstyle='arc3,rad=%4.2f' % (-math.pi / 16.),
                          shrinkA=2.0,
                          shrinkB=2.0,
                          mutation_scale=20.0,
                          mutation_aspect=None,
                          fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(-math.pi / 2.,
                        1.97,
                        r'$\mathrm{Galactic\ rotation}$',
                        rotation=-22.5)
    radii = numpy.array([0.5, 1., 1.5, 2., 2.5])
    labels = []
    for r in radii:
        ax.plot(numpy.linspace(
            0.,
            2. * math.pi,
            501,
        ),
                numpy.zeros(501) + r,
                ls='-',
                color='0.65',
                zorder=1,
                lw=0.5)
        labels.append(r'$%i$' % int(r * 8.))
    pyplot.rgrids(radii, labels=labels, angle=-32.5)
    bovy_plot.bovy_text(5.785, 2.82, r'$\mathrm{kpc}$')
    azs = numpy.array([0., 45., 90., 135., 180., 225., 270., 315.]) * _DEGTORAD
    for az in azs:
        ax.plot(numpy.zeros(501) + az,
                numpy.linspace(0., 2.8, 501),
                '-',
                color='0.6',
                lw=0.5,
                zorder=1)
    #Sun
    bovy_plot.bovy_text(0.065, .9075, r'$\odot$')
    pyplot.ylim(0., 2.8)
    bovy_plot.bovy_end_print(options.plotfile)
Example #22
0
def plot_lb():
    #Read basic data
    data= readVclosData()
    ndata= len(data)
    if _PLOTHIGHB:
        yrange= [-6.,6.]
    else:
        yrange= [-2.5,2.5]
    #Plot
    if OUTEXT == 'ps':
        bovy_plot.bovy_print(fig_width=8.5,fig_height=6./16.*8.5)
    else:
        bovy_plot.bovy_print(fig_width=16.,fig_height=6.)
    fig= pyplot.figure()
    #Set up axes
    nullfmt   = NullFormatter()         # no labels
    # definitions for the axes
    left, width = 0.1, 0.7
    bottom, height = 0.1, 0.85
    bottom_h = left_h = left+width
    rect_scatter = [left, bottom, width, height]
    rect_histy = [left_h, bottom, 0.15, height]
    axScatter = pyplot.axes(rect_scatter)
    axHisty = pyplot.axes(rect_histy)
    # no labels
    axHisty.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)
    fig.sca(axScatter)  
    bovy_plot.bovy_plot(data['GLON'],data['GLAT'],'k.',ms=1.5,
                        overplot=True)
    pyplot.xlim(0.,250.)
    pyplot.ylim(yrange[0],yrange[1])
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ l\ \mathrm{[deg]}$')
    pyplot.ylabel(r'$\mathrm{Galactic\ latitude}\ b\ \mathrm{[deg]}$')
    bovy_plot._add_ticks()
    #bovy_plot.bovy_end_print(os.path.join(OUTDIR,'data_lb.'+OUTEXT))
    if _PLOTHIGHB:
        #Read other data
        otherdata= readVclosData(meanb=-4.,bmax=10.)
        nmdata= len(otherdata)
        otherl= list(otherdata['GLON'])
        otherb= list(otherdata['GLAT'])
        otherdata2= readVclosData(meanb=4.,bmax=10.)
        npdata= len(otherdata2)
        otherl.extend(list(otherdata2['GLON']))
        otherb.extend(list(otherdata2['GLAT']))
        bovy_plot.bovy_plot(otherl,otherb,'.',mec='0.5',mfc='0.5',ms=1.5,
                            overplot=True)
        #Add histogram of bs
        otherl.extend(list(data['GLON']))
        otherb.extend(list(data['GLAT']))
    else:
        #Add histogram of bs
        otherl= list(data['GLON'])
        otherb= list(data['GLAT'])
        nmdata, npdata= 0,0
    histy, edges, patches= axHisty.hist(otherb,
                                        bins=49,
                                        orientation='horizontal',
                                        normed=True,
                                        histtype='step',
                                        range=yrange,
                                        color='k',zorder=2)
    #Overlay predictions
    #Center, constant
    ys= numpy.linspace(-1.5,1.5,1001)
    pdf= numpy.sqrt(1.5**2.-ys**2.)
    pdf*= float(ndata)/(ndata+nmdata+npdata)/numpy.sum(pdf)/(ys[1]-ys[0])
    axHisty.plot(pdf,ys,'k-',zorder=-2)
    constpdf= pdf
    #Center, exponential disk
    """
    dfc= dehnendf(beta=0.,correct=True,niter=20)
    pdf= numpy.zeros(len(ys))
    plates= list(set(data['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= data[(data['PLATE'] == plates[ii])]
        thisl= numpy.mean(data['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(ys[jj],thisl,0.,dmax/ro,0.,dfc,hz/ro)
        pdf+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdf*= float(ndata)/(ndata+nmdata+npdata)/numpy.sum(pdf)/(ys[1]-ys[0])
    axHisty.plot(pdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    #axHisty.plot(.8*pdf+.2*constpdf,ys,'-',color='0.',lw=1.,zorder=-1.)
    """
    if _PLOTHIGHB:
        #positive b, constant
        constpdf*= float(npdata)/ndata
        axHisty.plot(constpdf,ys+4.,'k-',zorder=-2)
        """
        #Positive, exponential disk
        pdfp= numpy.zeros(len(ys))
        plates= list(set(otherdata2['PLATE']))
        for ii in range(len(plates)):
            print ii
            #For each plate, calculate pdf and add with data weights
            thisdata= otherdata2[(otherdata2['PLATE'] == plates[ii])]
            thisl= numpy.mean(otherdata2['GLON'])
            thisndata= len(thisdata)
            thispdf= numpy.zeros(len(ys))
            for jj in range(len(ys)):
                thispdf[jj]= surfacemassLOSd(4.+ys[jj],
                thisl,0.,dmax/ro,4.,dfc,hz/ro)
            pdfp+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
        pdfp*= float(npdata)/(ndata+nmdata+npdata)/numpy.sum(pdfp)/(ys[1]-ys[0])
        axHisty.plot(pdfp,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        #axHisty.plot(.8*pdfp+.2*constpdf,4.+ys,'-',color='0.',lw=1.,zorder=-1)
        """
        #negative b, constant
        constpdf*= nmdata/float(npdata)
        axHisty.plot(constpdf,ys-4.,'k-',zorder=-2.)
    """
    #Negative, exponential disk
    pdfm= numpy.zeros(len(ys))
    plates= list(set(otherdata['PLATE']))
    for ii in range(len(plates)):
        print ii
        #For each plate, calculate pdf and add with data weights
        thisdata= otherdata[(otherdata['PLATE'] == plates[ii])]
        thisl= numpy.mean(otherdata['GLON'])
        thisndata= len(thisdata)
        thispdf= numpy.zeros(len(ys))
        for jj in range(len(ys)):
            thispdf[jj]= surfacemassLOSd(-4.+ys[jj],
                                          thisl,0.,dmax/ro,-4.,dfc,hz/ro)
        pdfm+= thispdf/numpy.sum(thispdf)/(ys[1]-ys[0])*thisndata
    pdfm*= float(nmdata)/(ndata+nmdata+npdata)/numpy.sum(pdfm)/(ys[1]-ys[0])
    axHisty.plot(pdfm,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    #axHisty.plot(.8*pdfm+.2*constpdf,-4.+ys,'-',color='0.',lw=1.,zorder=-1)
    """
    axHisty.set_ylim(yrange[0],yrange[1])
    axHisty.set_xlim( 0, 1.2*numpy.amax(histy))
    pyplot.sca(axHisty)
    bovy_plot._add_ticks()
    bovy_plot.bovy_end_print(os.path.join(OUTDIR,'data_lb.'+OUTEXT))
    return None
                R= math.sqrt(1.+d**2.-2.*d*math.cos(thisl))
                if R == 0.:
                    R+= 0.0001
                    d+= 0.0001
                if 1./math.cos(thisl) < d and math.cos(thisl) > 0.:
                    theta= math.pi-math.asin(d/R*math.sin(thisl))
                else:
                    theta= math.asin(d/R*math.sin(thisl))
                vR= -thisvs[ii]*math.cos(theta+thisl) #vperp=0 for marginalization
                vT= thisvs[ii]*math.sin(theta+thisl)
                o= Orbit([R,vR,vT,theta])
                surfmass= dfc.surfacemassLOS(d,thisl,deg=False)
                out+= surfmass*dfc(o,marginalizeVperp=True)/dfc.targetSurfacemass(R)
                norm+= surfmass
            pred_dist[ii]= out/norm
            ii+= 1
        if _PREDICTCACHE:
            savefile= open(savefilename,'wb')
            try:
                pickle.dump(pred_dist,savefile)
            finally:
                savefile.close()
    return pred_dist

if __name__ == '__main__':
    data= readVclosData()
    locations= list(set(data['LOCATION']))
    for l in locations:
        print l
        simplePlot(location=l,plotfile=os.path.join(os.getenv('HOME'),'Desktop/locationPlots/vlosdist_%i.png' % l),predict=True,nv=201)
Example #24
0
def createFakeData(parser):
    options, args = parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    if os.path.exists(options.plotfile):
        print "Outfile " + options.plotfile + " exists ..."
        print "Returning ..."
        return None
    #Read the data
    numpy.random.seed(options.seed)
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        ak=True,
        cutmultiples=options.cutmultiples,
        jkmax=options.jkmax)
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    #Set up the isochrone
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
        if options.dwarf:
            iso = [
                iso,
                isomodel.isomodel(imfmodel=options.imfmodel,
                                  Z=options.Z,
                                  dwarf=True,
                                  expsfh=options.expsfh)
            ]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, 'wb')
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data['H0MAG'][ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin((thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) +
                                    (data['J0MAG'] - data['K0MAG'])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF,
                                 _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data['H0MAG'][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) +
                                         (data['J0MAG'] - data['K0MAG'])[ii],
                                         mh)
    else:
        logpisodwarf = None
    #Load initial parameters from file
    savefile = open(args[0], 'rb')
    params = pickle.load(savefile)
    savefile.close()
    #Prep data
    l = data['GLON'] * _DEGTORAD
    b = data['GLAT'] * _DEGTORAD
    sinl = numpy.sin(l)
    cosl = numpy.cos(l)
    sinb = numpy.sin(b)
    cosb = numpy.cos(b)
    jk = data['J0MAG'] - data['K0MAG']
    jk[(jk < 0.5)] = 0.5  #BOVY: FIX THIS HACK BY EMAILING GAIL
    h = data['H0MAG']
    #Re-sample
    vlos = numpy.linspace(-200., 200., options.nvlos)
    pvlos = numpy.zeros((len(data), options.nvlos))
    if options.dwarf:
        thislogpisodwarf = logpisodwarf
    else:
        thislogpisodwarf = None
    if not options.multi is None and options.multi > 1:
        thismulti = options.multi
        options.multi = 1  #To avoid conflict
        thispvlos = multi.parallel_map(
            (lambda x: -mloglike(params,
                                 numpy.zeros(len(data)) + vlos[x], l, b, jk, h,
                                 df, options, sinl, cosl, cosb, sinb, logpiso,
                                 thislogpisodwarf, True, None, None, None)),
            range(options.nvlos),
            numcores=numpy.amin(
                [len(vlos), multiprocessing.cpu_count(), thismulti]))
        for jj in range(options.nvlos):
            pvlos[:, jj] = thispvlos[jj]
    else:
        for jj in range(options.nvlos):
            pvlos[:, jj] = -mloglike(
                params,
                numpy.zeros(len(data)) + vlos[jj], l, b, jk, h, df, options,
                sinl, cosl, cosb, sinb, logpiso, thislogpisodwarf, True, None,
                None, None)
    """
    for jj in range(options.nvlos):
        pvlos[:,jj]= -mloglike(params,numpy.zeros(len(data))+vlos[jj],
                               l,
                               b,
                               jk,
                               h,
                               df,options,
                               sinl,
                               cosl,
                               cosb,
                               sinb,
                               logpiso,
                               thislogpisodwarf,True,None,None,None)
    """
    for ii in range(len(data)):
        pvlos[ii, :] -= logsumexp(pvlos[ii, :])
        pvlos[ii, :] = numpy.exp(pvlos[ii, :])
        pvlos[ii, :] = numpy.cumsum(pvlos[ii, :])
        pvlos[ii, :] /= pvlos[ii, -1]
        #Draw
        randindx = numpy.random.uniform()
        kk = 0
        while pvlos[ii, kk] < randindx:
            kk += 1
        data['VHELIO'][ii] = vlos[kk]
    #Dump raw
    fitsio.write(options.plotfile, data, clobber=True)
def plot_distanceprior(parser):
    (options,args)= parser.parse_args()
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    l= data['GLON']*_DEGTORAD
    b= data['GLAT']*_DEGTORAD
    sinl= numpy.sin(l)
    cosl= numpy.cos(l)
    sinb= numpy.sin(b)
    cosb= numpy.cos(b)
    jk= data['J0MAG']-data['K0MAG']
    jk[(jk < 0.5)]= 0.5 #BOVY: FIX THIS HACK BY EMAILING GAIL
    h= data['H0MAG']
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        elif options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
    #Set up polar grid
    res= 51
    xgrid= numpy.linspace(0.,2.*math.pi*(1.-1./res/2.),
                       2*res)
    ygrid= numpy.linspace(0.5,2.8,res)
    plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2.,
                              xgrid[-1]+(xgrid[1]-xgrid[0])/2.,
                              len(xgrid)+1)
    plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2.,
                              ygrid[-1]+(ygrid[1]-ygrid[0])/2.,
                              len(ygrid)+1)
    plotthis= numpy.zeros((2*res,res,len(data)))-numpy.finfo(numpy.dtype(numpy.float64)).max
    #_BINTEGRATENBINS= 11 #For quick testing
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,_BINTEGRATENBINS)
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= h[ii]-dm 
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin(numpy.fabs(thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+jk[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+jk[ii],mh)
        else:
            logpiso[ii,:]= iso(numpy.zeros(_BINTEGRATENBINS)+jk[ii],mh)
    for jj in range(_BINTEGRATENBINS):
        d= ds[jj]/_REFR0
        R= numpy.sqrt(1.+d**2.-2.*d*cosl)
        indx= (R == 0.)
        R[indx]+= 0.0001
        theta= numpy.arcsin(d/R*sinl)
        indx= (1./cosl < d)*(cosl > 0.)
        theta[indx]= numpy.pi-theta[indx]
        indx= (theta < 0.)
        theta[indx]+= 2.*math.pi
        thisout= _logpd([0.,1.],d,None,None,
                        None,None,None,
                        options,R,theta,
                        1.,0.,logpiso[:,jj])
        #Find bin to which these contribute
        thetabin= numpy.floor((theta-xgrid[0])/(xgrid[1]-xgrid[0])+0.5)
        Rbin= numpy.floor((R-plotygrid[0])/(plotygrid[1]-plotygrid[0]))
        indx= (thetabin < 0)
        thetabin[indx]= 0
        Rbin[indx]= 0
        thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx= (thetabin >= 2*res)
        thetabin[indx]= 0. #Has to be
        #Rbin[indx]= 0
        #thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx= (Rbin < 0)
        thetabin[indx]= 0
        Rbin[indx]= 0
        thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx= (Rbin >= res)
        thetabin[indx]= 0
        Rbin[indx]= 0
        thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        thetabin= thetabin.astype('int')
        Rbin= Rbin.astype('int')
        for ii in range(len(data)):
            plotthis[thetabin,Rbin,ii]= thisout[ii]
    #Normalize
    for ii in range(2*res):
        for jj in range(res):
            plotthis[ii,jj,0]= logsumexp(plotthis[ii,jj,:])
    plotthis= plotthis[:,:,0]
    plotthis-= numpy.amax(plotthis)
    plotthis= numpy.exp(plotthis)
    plotthis[(plotthis == 0.)]= numpy.nan
    #Get los
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
    bovy_plot.bovy_print()
    ax= pyplot.subplot(111,projection='galpolar')#galpolar is in bovy_plot
    vmin, vmax= 0., 1.
    out= ax.pcolor(plotxgrid,plotygrid,plotthis.T,cmap='gist_yarg',
                   vmin=vmin,vmax=vmax,zorder=2)
    #Overlay los
    for ii in range(nlocs):
        lds= numpy.linspace(0.,2.95,501)
        lt= numpy.zeros(len(lds))
        lr= numpy.zeros(len(lds))
        lr= numpy.sqrt(1.+lds**2.-2.*lds*numpy.cos(l_plate[ii]*_DEGTORAD))
        lt= numpy.arcsin(lds/lr*numpy.sin(l_plate[ii]*_DEGTORAD))
        indx= (1./numpy.cos(l_plate[ii]*_DEGTORAD) < lds)*(numpy.cos(l_plate[ii]*_DEGTORAD) > 0.)
        lt[indx]= numpy.pi-lt[indx]
        ax.plot(lt,lr,
               ls='--',color='w',zorder=3)      
    from matplotlib.patches import Arrow, FancyArrowPatch
    arr= FancyArrowPatch(posA=(-math.pi/2.,1.8),
                         posB=(-math.pi/4.,1.8),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (-math.pi/16.),
                         shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(-math.pi/2.,1.97,r'$\mathrm{Galactic\ rotation}$',
                         rotation=-22.5)
    radii= numpy.array([0.5,1.,1.5,2.,2.5])
    labels= []
    for r in radii:
        ax.plot(numpy.linspace(0.,2.*math.pi,501,),
                numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5)
        labels.append(r'$%i$' % int(r*8.))
    pyplot.rgrids(radii,labels=labels,angle=-32.5)
    bovy_plot.bovy_text(5.785,2.82,r'$\mathrm{kpc}$')
    azs= numpy.array([0.,45.,90.,135.,180.,225.,270.,315.])*_DEGTORAD
    for az in azs:
        ax.plot(numpy.zeros(501)+az,
                numpy.linspace(0.,2.8,501),'-',color='0.6',lw=0.5,zorder=1)
    #Sun
    bovy_plot.bovy_text(0.065,.9075,r'$\odot$')
    pyplot.ylim(0.,2.8)
    bovy_plot.bovy_end_print(options.plotfile)
Example #26
0
def logl(init=None,data=None,options=None):
    if options is None:
        parser= get_options()
        options, args= parser.parse_args([])
    if data is None:
        #Read data
        data= readVclosData(lmin=25.,
                            bmax=2.,
                            ak=True,
                            validfeh=options.indivfeh, #if indivfeh, we need validfeh
                            correctak=options.correctak,
                            jkmax=1.1)
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        elif options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(Z=0.019)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(Z=0.019,
                                    dwarf=True)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    #Pre-calculate distance prior
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    if isinstance(init,str): #FILE
        #Load initial parameters from file
        savefile= open(init,'rb')
        params= pickle.load(savefile)
        savefile.close()
    else: #Array
        params= init
    #Prep data
    l= data['GLON']*_DEGTORAD
    b= data['GLAT']*_DEGTORAD
    sinl= numpy.sin(l)
    cosl= numpy.cos(l)
    sinb= numpy.sin(b)
    cosb= numpy.cos(b)
    jk= data['J0MAG']-data['K0MAG']
    try:
        jk[(jk < 0.5)]= 0.5 #BOVY: FIX THIS HACK BY EMAILING GAIL
    except TypeError:
        pass #HACK
    h= data['H0MAG']
    options.multi= 1
    out= -mloglike(params,data['VHELIO'],
                   l,
                   b,
                   jk,
                   h,
                   df,options,
                   sinl,
                   cosl,
                   cosb,
                   sinb,
                   logpiso,
                   logpisodwarf,True,None,iso,data['FEH']) #None iso for now
    return out
Example #27
0
def plot_nonaxi(parser):
    (options, args) = parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        cutmultiples=options.cutmultiples,
        jkmax=options.jkmax)
    #data= data[0:20]
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    indx = (data['GLON'] <= 30.)
    data['GLON'][
        indx] = 30.05  #Hack because the non-axi models don't go below Ro/2
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
        if options.dwarf:
            iso = [
                iso,
                isomodel.isomodel(imfmodel=options.imfmodel,
                                  Z=options.Z,
                                  dwarf=True,
                                  expsfh=options.expsfh)
            ]
        else:
            iso = [iso]
        if not options.isofile is None:
            isofile = open(options.isofile, 'wb')
            pickle.dump(iso, isofile)
            if options.indivfeh:
                pickle.dump(zs, isofile)
            elif options.varfeh:
                pickle.dump(locl, isofile)
            isofile.close()
    df = None
    print "Pre-calculating isochrone distance prior ..."
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = data['H0MAG'][ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          (data['J0MAG'] - data['K0MAG'])[ii],
                                          mh)
        else:
            logpiso[ii, :] = iso[0](numpy.zeros(_BINTEGRATENBINS) +
                                    (data['J0MAG'] - data['K0MAG'])[ii], mh)
    if options.dwarf:
        logpisodwarf = numpy.zeros((len(data), _BINTEGRATENBINS))
        dwarfds = numpy.linspace(_BINTEGRATEDMIN_DWARF, _BINTEGRATEDMAX_DWARF,
                                 _BINTEGRATENBINS)
        dm = _dm(dwarfds)
        for ii in range(len(data)):
            mh = data['H0MAG'][ii] - dm
            logpisodwarf[ii, :] = iso[1](numpy.zeros(_BINTEGRATENBINS) +
                                         (data['J0MAG'] - data['K0MAG'])[ii],
                                         mh)
    else:
        logpisodwarf = None
    """ #Does not matter anyway
    #clean logpiso
    dataindx= []
    for ii in range(len(data)):
        thislogpiso= logpiso[ii,:]-logsumexp(logpiso[ii,:])
        if numpy.all(thislogpiso == 0.): dataindx.append(False)
        else: dataindx.append(True)
    dataindx= numpy.array(dataindx,dtype='bool')
    data= data[dataindx]
    logpiso= logpiso[dataindx,:]
    logpisodwarf= logpisodwarf[dataindx,:]
    """
    #Calculate data means etc.
    #Calculate means
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    avg_plate = numpy.zeros(nlocs)
    sig_plate = numpy.zeros(nlocs)
    siga_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
        avg_plate[ii] = numpy.mean(data['VHELIO'][indx])
        sig_plate[ii] = numpy.std(data['VHELIO'][indx])
        siga_plate[ii] = numpy.std(data['VHELIO'][indx]) / numpy.sqrt(
            numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile = open(args[0], 'rb')
    params = pickle.load(savefile)
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf = None
    avg_plate_model_fid = calc_model(params, options, data, logpiso,
                                     logpisodwarf, df, nlocs, locations, iso)
    print l_plate, avg_plate_model_fid
    #Plot everything
    bovy_plot.bovy_print(fig_height=6., fig_width=7.)
    dx = 0.8 / 5.
    left, bottom, width, height = 0.1, 0.9 - dx, 0.8, dx
    axTop = pyplot.axes([left, bottom, width, height])
    allaxes = [axTop]
    fig = pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0., 360.], [0., 0.], '-', color='0.5', overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'ko',
                        overplot=True)
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$', top_right=True, size=14.)
    thisax = pyplot.gca()
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    nullfmt = NullFormatter()  # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Second is bar
    print "Reading bar file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/bar/bar_rect_vr_tform-150_tsteady-4pi_51_101.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 2. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{bar}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Third is spiral
    print "Reading spiral file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/spiral/spiral_rect_vr_51_101.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 3. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{spiral}$', top_right=True, size=14.)
    pyplot.ylabel(
        r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}} \ [\mathrm{km\ s}^{-1}]$'
    )
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    #Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, 0.)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 4. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{elliptical}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Fourth is first elliptical
    print "Reading elliptical file ..."
    barfile = '/work/bovy/data/bovy/nonaximw/elliptical/el_rect_so_0.2_res_51_grid_101_tform_-150._tsteady_125._cp_0.05_nsigma_4.sav'
    avg_plate_bar = calc_nonaxi(params, barfile, options, data, logpiso, nlocs,
                                locations, -45. * _DEGTORAD)
    print avg_plate_bar
    left, bottom, width, height = 0.1, 0.9 - 5. * dx, 0.8, dx
    thisax = pyplot.axes([left, bottom, width, height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0., 360.], [0., 0.],
                        '-',
                        color='0.5',
                        overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid,
                        'o',
                        overplot=True,
                        color='0.6')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid,
                    yerr=siga_plate,
                    marker='o',
                    color='0.6',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate - avg_plate_model_fid - avg_plate_bar,
                        'o',
                        overplot=True,
                        color='k')
    pyplot.errorbar(l_plate,
                    avg_plate - avg_plate_model_fid - avg_plate_bar,
                    yerr=siga_plate,
                    marker='o',
                    color='k',
                    linestyle='none',
                    elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{elliptical}$', top_right=True, size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-14.5, 14.5)
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0., 360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Example #28
0
#set up; kind of plot
justData = False
dataMean = False
noSolar = False
justSolar = False
betas, vcbetas = True, 250.
hrs = False
dmaxs = False
addNonAxi = False
#Data selection
nodups = True
fehcut = False
postshutdown = True
cohort = None
ext = 'png'
data = readVclosData(postshutdown=postshutdown, fehcut=fehcut, cohort=cohort)
#Calculate means
plates = list(set(data['PLATE']))
nplates = len(plates)
l_plate = numpy.zeros(nplates)
avg_plate = numpy.zeros(nplates)
sig_plate = numpy.zeros(nplates)
siga_plate = numpy.zeros(nplates)
for ii in range(nplates):
    indx = (data['PLATE'] == plates[ii])
    l_plate[ii] = numpy.mean(data['GLON'][indx])
    avg_plate[ii] = numpy.mean(data['VHELIO'][indx])
    sig_plate[ii] = numpy.std(data['VHELIO'][indx])
    siga_plate[ii] = numpy.std(data['VHELIO'][indx]) / numpy.sqrt(
        numpy.sum(indx))
#print sig_plate
if __name__ == '__main__':
    #Get options
    parser = get_options()
    options, args = parser.parse_args()
    #Read data
    #AK quantiles?
    if not options.aklow is None:
        akquantiles = [options.aklow, options.akhigh]
    else:
        akquantiles = None
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        jkmax=options.jkmax,
        datafilename=options.fakedata,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        akquantiles=akquantiles)
    if options.location == 0:
        locations = list(set(data['LOCATION']))
    else:
        locations = [options.location]
    #HACK
    indx = (data['J0MAG'] - data['K0MAG'] < 0.5)
    data['J0MAG'][indx] = 0.5 + data['K0MAG'][indx]
    #Fit parameters
    if options.dwarf:
        params = [
def plot_externalcomparison(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0 or options.plotfilename is None:
        parser.print_help()
        return
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    #data= data[0:20]
    #HACK
    indx= (data['J0MAG']-data['K0MAG'] < 0.5)
    data['J0MAG'][indx]= 0.5+data['K0MAG'][indx]
    #Cut outliers
    #data= data[(data['VHELIO'] < 200.)*(data['VHELIO'] > -200.)]
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        elif options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
        if options.dwarf:
            iso= [iso, 
                  isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                    dwarf=True,expsfh=options.expsfh)]
        else:
            iso= [iso]
        if not options.isofile is None:
            isofile= open(options.isofile,'wb')
            pickle.dump(iso,isofile)
            if options.indivfeh:
                pickle.dump(zs,isofile)
            elif options.varfeh:
                pickle.dump(locl,isofile)
            isofile.close()
    df= None
    print "Pre-calculating isochrone distance prior ..."
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,
                       _BINTEGRATENBINS)
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= data['H0MAG'][ii]-dm
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin((thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+(data['J0MAG']-data['K0MAG'])[ii],mh)
        else:
            logpiso[ii,:]= iso[0](numpy.zeros(_BINTEGRATENBINS)
                                  +(data['J0MAG']-data['K0MAG'])[ii],mh)
    if options.dwarf:
        logpisodwarf= numpy.zeros((len(data),_BINTEGRATENBINS))
        dwarfds= numpy.linspace(_BINTEGRATEDMIN_DWARF,_BINTEGRATEDMAX_DWARF,
                                    _BINTEGRATENBINS)
        dm= _dm(dwarfds)
        for ii in range(len(data)):
            mh= data['H0MAG'][ii]-dm
            logpisodwarf[ii,:]= iso[1](numpy.zeros(_BINTEGRATENBINS)
                                       +(data['J0MAG']-data['K0MAG'])[ii],mh)
    else:
        logpisodwarf= None
    #Calculate data means etc.
    #Calculate means
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    avg_plate= numpy.zeros(nlocs)
    sig_plate= numpy.zeros(nlocs)
    siga_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
        avg_plate[ii]= numpy.mean(data['VHELIO'][indx])
        sig_plate[ii]= numpy.std(data['VHELIO'][indx])
        siga_plate[ii]= numpy.std(data['VHELIO'][indx])/numpy.sqrt(numpy.sum(indx))
    #Calculate plate means and variances from the model
    #Load initial parameters from file
    savefile= open(args[0],'rb')
    params= pickle.load(savefile)
    if not options.index is None:
        params= params[options.index]
    savefile.close()
    #First calculate fiducial model
    if not options.dwarf:
        logpisodwarf= None
    fid_logl= numpy.sum(logl.logl(init=params,data=data,options=copy.copy(options))) #Copy options, since logl sets multi=1
    avg_plate_model_fid= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #Plot everything
    bovy_plot.bovy_print(fig_height=6.,fig_width=7.)
    dx= 0.8/5.
    left, bottom, width, height= 0.1, 0.9-dx, 0.8, dx
    axTop= pyplot.axes([left,bottom,width,height])
    allaxes= [axTop]
    fig= pyplot.gcf()
    fig.sca(axTop)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'ko',overplot=True)
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{fiducial}$',top_right=True,size=14.)
    thisax= pyplot.gca()
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    nullfmt   = NullFormatter()         # no labels
    axTop.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Second is powerlaw with beta=0.15
    #fid_slope= params[5-options.nooutliermean+options.dwarf]
    #params[5-options.nooutliermean+options.dwarf]= 0.
    fid_params= copy.copy(params)
    if options.rotcurve.lower() == 'flat':
        params= list(params)
        params.insert(6,0.15)
        params= numpy.array(params)
        fid_rotcurve= options.rotcurve
        options.rotcurve= 'powerlaw'
    elif options.rotcurve.lower() == 'powerlaw':
        params[6]= 0.15
        fid_rotcurve= options.rotcurve
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #params[5-options.nooutliermean+options.dwarf]= fid_slope
    #Undo changes
    params= fid_params
    options.rotcurve= fid_rotcurve
    left, bottom, width, height= 0.1, 0.9-2.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{power\!\!-\!\!law\ rotation\ curve}, \beta = 0.15$',
                        top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Third is powerlaw with beta=-0.15
    #fid_slope= params[5-options.nooutliermean+options.dwarf]
    #params[5-options.nooutliermean+options.dwarf]= 0.
    fid_params= copy.copy(params)
    if options.rotcurve.lower() == 'flat':
        params= list(params)
        params.insert(6,-0.15)
        params= numpy.array(params)
        fid_rotcurve= options.rotcurve
        options.rotcurve= 'powerlaw'
    elif options.rotcurve.lower() == 'powerlaw':
        params[6]= -0.15
        fid_rotcurve= options.rotcurve
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #params[5-options.nooutliermean+options.dwarf]= fid_slope
    #Undo changes
    params= fid_params
    options.rotcurve= fid_rotcurve
    left, bottom, width, height= 0.1, 0.9-3.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{power\!\!-\!\!law\ rotation\ curve}, \beta = -0.15$',
                        top_right=True,size=14.)
    pyplot.ylabel(r'$\bar{V}_{\mathrm{data}}-\bar{V}_{\mathrm{model}}$')
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Second is vc=250
    #Load initial parameters from file
    savefile= open(options.vo250file,'rb')
    params= pickle.load(savefile)
    savefile.close()
    options.fixvo= 250.
    options.fixro= 8.4
    vo250_logl= numpy.sum(logl.logl(init=params,data=data,options=copy.copy(options)))
    avg_plate_modelr84= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    #Load initial parameters from file
    savefile= open(options.vo250r8file,'rb')
    paramsr8= pickle.load(savefile)
    savefile.close()
    options.fixvo= 250.
    options.fixro= 8.
    vo250r8_logl= numpy.sum(logl.logl(init=paramsr8,data=data,options=copy.copy(options)))
    avg_plate_modelr8= calc_model(paramsr8,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    options.fixro= None
    options.fixvo= None
    left, bottom, width, height= 0.1, 0.9-4.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,
                        zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_modelr84,
                        'x',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_modelr84,
                    yerr=siga_plate,marker='x',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_modelr8,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_modelr8,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    #top_right=True,size=14.)
    bovy_plot.bovy_text(r'$\mathrm{best\!\!-\!\!fit}\ V_c(R_0) = 250\ \mathrm{km\ s}^{-1}, R_0 = %.1f\,\mathrm{kpc}, \Delta \chi^2 = %.0f\ (%.1f\sigma)$' % (8.,2.*(fid_logl-vo250r8_logl),special.erfinv(stats.chi2.cdf(2.*(fid_logl-vo250r8_logl),10.))*numpy.sqrt(2.)),
                        top_right=True,size=13.)
    bovy_plot.bovy_text(r'$\mathrm{best\!\!-\!\!fit}\ V_c(R_0) = 250\ \mathrm{km\ s}^{-1}, R_0 = %.1f\,\mathrm{kpc}, \Delta \chi^2 = %.0f\ (%.1f\sigma)$' % (8.4,2.*(fid_logl-vo250_logl),special.erfinv(stats.chi2.cdf(2.*(fid_logl-vo250_logl),10.))*numpy.sqrt(2.)),
                        bottom_right=True,size=13.)
    bovy_plot.bovy_plot([40.],[-15.],'kx',overplot=True)
    bovy_plot.bovy_plot([40.],[12.],'ko',overplot=True)
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    thisax.xaxis.set_major_formatter(nullfmt)
    #pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Fourth = vpec=SBD10
    #Load sbd fit
    #Load initial parameters from file
    savefile= open(options.sbdfile,'rb')
    params= pickle.load(savefile)
    savefile.close()
    options.sbdvpec= True
    options.fitvpec= False
    sbd_logl= numpy.nansum(logl.logl(init=params,data=data,options=copy.copy(options)))
    avg_plate_model= calc_model(params,options,data,
                                logpiso,logpisodwarf,
                                df,nlocs,locations,iso)
    left, bottom, width, height= 0.1, 0.9-5.*dx, 0.8, dx
    thisax= pyplot.axes([left,bottom,width,height])
    allaxes.append(thisax)
    fig.sca(thisax)
    bovy_plot.bovy_plot([0.,360.],[0.,0.],'-',color='0.5',overplot=True,zorder=-1)
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model_fid,
                        'o',overplot=True,color='0.6')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model_fid,
                    yerr=siga_plate,marker='o',color='0.6',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_plot(l_plate,
                        avg_plate-avg_plate_model,
                        'o',overplot=True,color='k')
    pyplot.errorbar(l_plate,avg_plate-avg_plate_model,
                    yerr=siga_plate,marker='o',color='k',
                    linestyle='none',elinestyle='-')
    bovy_plot.bovy_text(r'$\mathrm{best\!\!-\!\!fit}\ \vec{V}_\odot = \vec{V}_c(R_0) + \mathrm{SBD10}, \Delta \chi^2 = %.0f$' % (2.*(fid_logl-sbd_logl)),#,special.erfinv(stats.chi2.cdf(2.*(fid_logl-sbd_logl),10.))*numpy.sqrt(2.)),
                        top_right=True,size=14.)
    #pyplot.ylabel(r'$\langle V_{\mathrm{los}}\rangle_{\mathrm{data}}-\langle V_{\mathrm{los}}\rangle_{\mathrm{model}}$')
    thisax.set_ylim(-19.5,19.5)
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #thisax.xaxis.set_major_formatter(nullfmt)
    pyplot.xlabel(r'$\mathrm{Galactic\ longitude}\ [\mathrm{deg}]$')
    pyplot.xlim(0.,360.)
    bovy_plot._add_ticks()
    #Save
    bovy_plot.bovy_end_print(options.plotfilename)
    print fid_logl, sbd_logl, 2.*(fid_logl-sbd_logl),special.erfinv(stats.chi2.cdf(2.*(fid_logl-sbd_logl),10.))*numpy.sqrt(2.)
    return None