Example #1
0
def plot_rovo(filename, plotfilename):
    if not os.path.exists(filename):
        raise IOError("given filename does not exist")
    savefile = open(filename, 'rb')
    params = pickle.load(savefile)
    savefile.close()
    if _ANALYTIC:  #Calculate by fixing everything except for Ro anv vo
        options = plot_pdfs.set_options(None)
        nros = 15
        noos = 15
        ros = numpy.linspace(7., 13., nros)
        oos = numpy.linspace(20., 30., noos)
        ll = numpy.zeros((noos, nros))
        for ii in range(noos):
            if not _MULTI is None:
                theseparamss = []
                for jj in range(nros):
                    theseparams = copy.copy(params)
                    theseparams[0] = oos[ii] * ros[jj] / _REFV0
                    theseparams[1] = ros[jj] / _REFR0
                    theseparamss.append(theseparams)
                thisll = multi.parallel_map(
                    (lambda x: numpy.sum(
                        logl.logl(init=theseparamss[x], options=options))),
                    range(nros),
                    numcores=numpy.amin(
                        [nros, _MULTI,
                         multiprocessing.cpu_count()]))
                ll[ii, :] = thisll
            else:
                for jj in range(nros):
                    theseparams = copy.copy(params)
                    theseparams[0] = oos[ii] * ros[jj] / _REFV0
                    theseparams[1] = ros[jj] / _REFR0
                    ll[ii, jj] = numpy.sum(
                        logl.logl(init=theseparams, options=options))
        #Normalize
        ll -= logsumexp(ll)
        ll = numpy.exp(ll)
        levels = list(special.erf(0.5 * numpy.arange(1, 4)))
        bovy_plot.bovy_dens2d(
            ll.T,
            origin='lower',
            levels=levels,
            xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
            ylabel=r'$R_0\ [\mathrm{kpc}]$',
            xrange=[20., 35.],
            yrange=[7., 13.],
            contours=True,
            cntrcolors='k',
            onedhists=True,
            cmap='gist_yarg')
    else:
        vos = numpy.array([s[0] for s in params]) * _REFV0
        ros = numpy.array([s[1] for s in params]) * _REFR0
        bovy_plot.bovy_print()
        levels = list(special.erf(0.5 * numpy.arange(1, 4)))
        levels.append(1.01)  #HACK to not plot outliers
        bovy_plot.scatterplot(
            vos / ros,
            ros,
            'k,',
            levels=levels,
            xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
            ylabel=r'$R_0\ [\mathrm{kpc}]$',
            bins=31,
            xrange=[200. / 8., 250. / 8.],
            yrange=[7., 9.],
            contours=True,
            cntrcolors='k',
            onedhists=True,
            cmap='gist_yarg')
    bovy_plot.bovy_end_print(plotfilename)
Example #2
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 #3
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 #4
0
def plot_rovo(filename,plotfilename):
    if not os.path.exists(filename):
        raise IOError("given filename does not exist")
    savefile= open(filename,'rb')
    params= pickle.load(savefile)
    savefile.close()
    if _ANALYTIC: #Calculate by fixing everything except for Ro anv vo
        options= plot_pdfs.set_options(None)
        nros= 15
        noos= 15
        ros= numpy.linspace(7.,13.,nros)
        oos= numpy.linspace(20.,30.,noos)
        ll= numpy.zeros((noos,nros))
        for ii in range(noos):
            if not _MULTI is None:
                theseparamss= []
                for jj in range(nros):
                    theseparams= copy.copy(params)
                    theseparams[0]= oos[ii]*ros[jj]/_REFV0
                    theseparams[1]= ros[jj]/_REFR0
                    theseparamss.append(theseparams)
                thisll= multi.parallel_map((lambda x: numpy.sum(logl.logl(init=theseparamss[x],options=options))),
                                           range(nros),
                                           numcores=numpy.amin([nros,_MULTI,multiprocessing.cpu_count()]))
                ll[ii,:]= thisll
            else:
                for jj in range(nros):
                    theseparams= copy.copy(params)
                    theseparams[0]= oos[ii]*ros[jj]/_REFV0
                    theseparams[1]= ros[jj]/_REFR0
                    ll[ii,jj]= numpy.sum(logl.logl(init=theseparams,
                                                   options=options))
        #Normalize
        ll-= logsumexp(ll)
        ll= numpy.exp(ll)
        levels= list(special.erf(0.5*numpy.arange(1,4)))
        bovy_plot.bovy_dens2d(ll.T,origin='lower',levels=levels,
                              xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
                              ylabel=r'$R_0\ [\mathrm{kpc}]$',
                              xrange=[20.,35.],
                              yrange=[7.,13.],
                              contours=True,
                              cntrcolors='k',
                              onedhists=True,
                              cmap='gist_yarg')
    else:
        vos= numpy.array([s[0] for s in params])*_REFV0
        ros= numpy.array([s[1] for s in params])*_REFR0
        bovy_plot.bovy_print()
        levels= list(special.erf(0.5*numpy.arange(1,4)))
        levels.append(1.01) #HACK to not plot outliers
        bovy_plot.scatterplot(vos/ros,ros,'k,',levels=levels,
                              xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$',
                              ylabel=r'$R_0\ [\mathrm{kpc}]$',
                              bins=31,
                              xrange=[200./8.,250./8.],
                              yrange=[7.,9.],
                              contours=True,
                              cntrcolors='k',
                              onedhists=True,
                              cmap='gist_yarg')
    bovy_plot.bovy_end_print(plotfilename)
Example #5
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 #6
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
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