def checkAbundanceScatterClusters():
    # First read the cluster data
    cldata= read_clusterdata.read_caldata()
    # Read the allStar data to match
    # For each of the calibration open clusters, calculate the offset from the 
    # mean in our FEHTAG and AFETAG
    clusters= ['M71','N2158','N2420','N188','M67','N7789','N6819',
               'N6791']
    fehoffset= []
    afeoffset= []
    for cluster in clusters:
        tdata= cldata[cldata['CLUSTER'] == cluster.upper()]
        tdata= tdata[(tdata['TEFF'] < _TEFFMAX)\
                         *(tdata['TEFF'] > _TEFFMIN)\
                         *(tdata['LOGG'] < 3.5)]
        # Compute the average feh and afe and save the offsets
        medianfeh= numpy.median(tdata['FE_H'])
        medianafe= numpy.median(tdata[define_rcsample._AFETAG])
        fehoffset.extend(tdata['FE_H']-medianfeh)
        afeoffset.extend(tdata[define_rcsample._AFETAG]-medianafe)
        if cluster == 'M67': print medianfeh, medianafe, len(tdata)
    fehoffset= numpy.array(fehoffset)
    afeoffset= numpy.array(afeoffset)
    print 'FE_H scatter %g' % (numpy.nanstd(fehoffset[numpy.fabs(fehoffset) < 0.3]))
    print 'A_FE scatter %g' % (numpy.nanstd(afeoffset[numpy.fabs(afeoffset) < 0.3]))
    gindx= (numpy.fabs(fehoffset) < 0.3)*(numpy.fabs(afeoffset) < 0.3)
    print 'FE_H/A_FE correlation %g' % (numpy.mean(afeoffset[gindx]*fehoffset[gindx])/numpy.nanstd(fehoffset[numpy.fabs(fehoffset) < 0.3])/numpy.nanstd(afeoffset[numpy.fabs(afeoffset) < 0.3]))
    print 'FE_H robust scatter %g' % (1.4826*numpy.median(numpy.fabs(fehoffset)))
    print 'A_FE robust scatter %g' % (1.4826*numpy.median(numpy.fabs(afeoffset)))
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(fehoffset,range=[-0.3,0.3],bins=31,histtype='step')
    bovy_plot.bovy_hist(afeoffset,range=[-0.3,0.3],bins=31,histtype='step',
                        overplot=True)
    bovy_plot.bovy_end_print('test.png')
    return None
def plot_pdfs_l(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                  leading=True,nTrackChunks=_NTRACKCHUNKS,
                  vsun=[0.,30.24*8.,0.],
                  tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                  multi=_NTRACKCHUNKS)
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    #Sample from sdf
    llbd= sdf.sample(n=40000,lb=True)
    tlbd= sdft.sample(n=50000,lb=True)
    b,e= numpy.histogram(llbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    lspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=1.)
    lls= numpy.linspace(t[0],t[-1],_NLS)
    lps= numpy.exp(lspl(lls))
    lps/= numpy.sum(lps)*(lls[1]-lls[0])*2.
    b,e= numpy.histogram(tlbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    tspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=0.5)
    tls= numpy.linspace(t[0],t[-1],_NLS)
    tps= numpy.exp(tspl(tls))
    tps/= numpy.sum(tps)*(tls[1]-tls[0])*2.
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    bovy_plot.bovy_plot(lls,lps,'k-',lw=1.5,
                        xlabel=r'$\mathrm{Galactic\ longitude}\,(\mathrm{deg})$',
                        ylabel=r'$p(l)$',
                        xrange=[65.,250.],
                        yrange=[0.,1.2*numpy.nanmax(numpy.hstack((lps,tps)))])
    bovy_plot.bovy_plot(tls,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    #Transform to (l,b)
    XYZ= bovy_coords.galcenrect_to_XYZ(data[:,1],data[:,3],data[:,2],Xsun=8.)
    lbd= bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2],degree=True)
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    lbd= lbd[indx,:]
    bovy_plot.bovy_hist(lbd[:,0],bins=40,range=[65.,250.],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
Пример #3
0
def plotSkew(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    savefilename= args[0]
    if os.path.exists(savefilename):
        savefile= open(savefilename,'rb')
        skews= pickle.load(savefile)
        gaussskews= pickle.load(savefile)
        type= pickle.load(savefile)
        band= pickle.load(savefile)
        mean= pickle.load(savefile)
        taus= pickle.load(savefile)      
        savefile.close()
    else:
        parser.print_help()
        return
    #Accumulate
    keys= skews.keys()
    allskews= numpy.zeros((len(keys),len(taus)))
    allgaussskews= numpy.zeros((len(keys),gaussskews[keys[0]].shape[0],
                                len(taus)))
    for ii, key in enumerate(keys):
        allskews[ii,:]= -skews[key] #go to regular definition
        allgaussskews[ii,:]= -gaussskews[key]
    #Statistic
    q= 0.99
    statistic= numpy.median
    if not options.indx is None:
        print "indx option not allowed"
        return None
    indx= numpy.all(numpy.isnan(allskews),axis=1)
    allskews= allskews[True-indx,:]
    allgaussskews= allgaussskews[True-indx,:,:]
    #Median
    medianskew= statistic(allskews,axis=0)
    mediangaussskew= statistic(allgaussskews,axis=0)
    #Determine 1-sigma
    sigma= quantile(mediangaussskew,q=q)
    #Plot
    tauindx= 5
    print "Showing tau %f" % (taus[tauindx]*365.25)
    bovy_plot.bovy_print(fig_width=7.)
    bovy_plot.bovy_hist(allskews[:,tauindx],bins=31,
                        color='k',normed=True,histtype='step',
                        xlabel=r'$\mathrm{skew}(\tau = %i\ \mathrm{days})$' % (int(taus[tauindx]*365.25)))
    bovy_plot.bovy_plot([numpy.median(allskews[:,tauindx]),numpy.median(allskews[:,tauindx])],
                        [0.,10.],'k-',overplot=True)
    bovy_plot.bovy_plot([numpy.mean(allskews[:,tauindx]),numpy.mean(allskews[:,tauindx])],
                        [0.,10.],'k--',overplot=True)
    bovy_plot.bovy_end_print(options.plotfilename)
    return None
Пример #4
0
def plot_seguem10(plotfilename):
    savefile= open('../potential-fits/fitall_10ksamples_derived_whalomass.sav','rb')
    data= pickle.load(savefile)
    savefile.close()
    mh= numpy.array([x[8] for x in data])
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(mh,range=[0.,10.],
                        bins=71,histtype='step',color='k',
                        xlabel=r'$M_{\mathrm{halo}}(<10\,\mathrm{kpc})\,(10^{10}\,M_\odot)$',
                        normed=True)
    xs= numpy.linspace(0.,10.,1001)
    bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi*numpy.var(mh[True-numpy.isnan(mh)]))*numpy.exp(-0.5*(xs-numpy.mean(mh[True-numpy.isnan(mh)]))**2./numpy.var(mh[True-numpy.isnan(mh)])),
                        'k-',lw=2,overplot=True)
    bovy_plot.bovy_end_print(plotfilename)
def checkAbundanceScatterClusters():
    # First read the cluster data
    cldata = read_clusterdata.read_caldata()
    # Read the allStar data to match
    # For each of the calibration open clusters, calculate the offset from the
    # mean in our FEHTAG and AFETAG
    clusters = [
        'M71', 'N2158', 'N2420', 'N188', 'M67', 'N7789', 'N6819', 'N6791'
    ]
    fehoffset = []
    afeoffset = []
    for cluster in clusters:
        tdata = cldata[cldata['CLUSTER'] == cluster.upper()]
        tdata= tdata[(tdata['TEFF'] < _TEFFMAX)\
                         *(tdata['TEFF'] > _TEFFMIN)\
                         *(tdata['LOGG'] < 3.5)]
        # Compute the average feh and afe and save the offsets
        medianfeh = numpy.median(tdata['FE_H'])
        medianafe = numpy.median(tdata[define_rcsample._AFETAG])
        fehoffset.extend(tdata['FE_H'] - medianfeh)
        afeoffset.extend(tdata[define_rcsample._AFETAG] - medianafe)
        if cluster == 'M67': print medianfeh, medianafe, len(tdata)
    fehoffset = numpy.array(fehoffset)
    afeoffset = numpy.array(afeoffset)
    print 'FE_H scatter %g' % (numpy.nanstd(
        fehoffset[numpy.fabs(fehoffset) < 0.3]))
    print 'A_FE scatter %g' % (numpy.nanstd(
        afeoffset[numpy.fabs(afeoffset) < 0.3]))
    gindx = (numpy.fabs(fehoffset) < 0.3) * (numpy.fabs(afeoffset) < 0.3)
    print 'FE_H/A_FE correlation %g' % (
        numpy.mean(afeoffset[gindx] * fehoffset[gindx]) /
        numpy.nanstd(fehoffset[numpy.fabs(fehoffset) < 0.3]) /
        numpy.nanstd(afeoffset[numpy.fabs(afeoffset) < 0.3]))
    print 'FE_H robust scatter %g' % (1.4826 *
                                      numpy.median(numpy.fabs(fehoffset)))
    print 'A_FE robust scatter %g' % (1.4826 *
                                      numpy.median(numpy.fabs(afeoffset)))
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(fehoffset, range=[-0.3, 0.3], bins=31, histtype='step')
    bovy_plot.bovy_hist(afeoffset,
                        range=[-0.3, 0.3],
                        bins=31,
                        histtype='step',
                        overplot=True)
    bovy_plot.bovy_end_print('test.png')
    return None
def plot_pdfs_x(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    txs= numpy.linspace(3.,12.4,_NLS)
    tlogps= multi.parallel_map((lambda x: sdft.callMarg([txs[x]/8.,None,None,None,None,None],
                                                        interp=True,ngl=_NGL,
                                                        nsigma=3)),
                              range(_NLS),
                              numcores=numpy.amin([_NLS,
                                                   multiprocessing.cpu_count()]))
    tlogps= numpy.array(tlogps)
    tlogps[numpy.isnan(tlogps)]= -100000000000000000.
    tps= numpy.exp(tlogps-logsumexp(tlogps))
    tps/= numpy.nansum(tps)*(txs[1]-txs[0])
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(txs,tps,'k-',lw=1.5,
                        xlabel=r'$X\,(\mathrm{kpc})$',
                        ylabel=r'$p(X)$',
                        xrange=[3.,12.4],
                        yrange=[0.,1.2*numpy.nanmax(tps)])
    bovy_plot.bovy_plot(txs,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= thetar-numpy.pi < -(5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    data= data[indx,:]
    bovy_plot.bovy_hist(data[:,1],bins=20,range=[3.,12.4],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
Пример #7
0
def plotloglhist(options,args):
    #Go through all of the bins
    if options.sample.lower() == 'g':
        npops= 62
    elif options.sample.lower() == 'k':
        npops= 30
    for ii in range(npops):
        if _NOTDONEYET:
            spl= options.restart.split('.')
        else:
            spl= args[0].split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        savefile= open(newname,'rb')
        try:
            if not _NOTDONEYET:
                params= pickle.load(savefile)
                mlogl= pickle.load(savefile)
            logl= pickle.load(savefile)
        except:
            continue
        finally:
            savefile.close()
        if _NOTDONEYET:
            logl[(logl == 0.)]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(logl.flatten()[(logl.flatten() >-1000000.)],
                            xrange=[numpy.nanmax(logl)-50.,numpy.nanmax(logl)],
                            xlabel=r'$\log \mathcal{L}$',
                            histtype='step',color='k')
        #Plotname
        spl= options.outfilename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        bovy_plot.bovy_end_print(newname)
    return None
Пример #8
0
def simplePlot(location=4242,
               plotfile=None,
               predict=False,
               nv=11,
               dmax=10. / 8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data = readVclosData(**kwargs)
    data = data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range = [-200., 200.]
    hist, xvec, p = bovy_plot.bovy_hist(
        data['VHELIO'],
        range=range,
        bins=31,
        histtype='step',
        color='k',
        xlabel=
        r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs = numpy.linspace(range[0], range[1], nv)
        pred_dist = _calc_pred(pred_vs, location, numpy.mean(data['GLON']),
                               dmax)
        data_int = numpy.sum(hist) * (xvec[1] - xvec[0])
        pred_dist *= data_int / numpy.sum(pred_dist) / (pred_vs[1] -
                                                        pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,
                            pred_dist,
                            '-',
                            color='0.65',
                            overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location + '\n' +
                        r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,
                        size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
Пример #9
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
Пример #10
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
Пример #11
0
def simplePlot(location=4242,plotfile=None,predict=False,nv=11,dmax=10./8.,
               **kwargs):
    """
    NAME:
       simplePlot
    PURPOSE:
       make a simple histogram for a given location
    INPUT:
       location - location ID
       +readVclosData inputs
    OPTIONAL INPUT:
       plotfile= if set, save plot to this file
    OUTPUT:
       plot to display or file
    HISTORY:
       2012-01-25 - Written - Bovy (IAS)
    """
    #Read data
    data= readVclosData(**kwargs)
    data= data[(data['LOCATION'] == location)]
    if not plotfile is None:
        bovy_plot.bovy_print()
    range= [-200.,200.]
    hist, xvec, p= bovy_plot.bovy_hist(data['VHELIO'],range=range,bins=31,
                                       histtype='step',color='k',
                                       xlabel=r'$\mathrm{heliocentric}\ v_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
    #Prediction
    if predict:
        pred_vs= numpy.linspace(range[0],range[1],nv)
        pred_dist= _calc_pred(pred_vs,location,numpy.mean(data['GLON']),dmax)
        data_int= numpy.sum(hist)*(xvec[1]-xvec[0])
        pred_dist*= data_int/numpy.sum(pred_dist)/(pred_vs[1]-pred_vs[0])
        bovy_plot.bovy_plot(pred_vs,pred_dist,'-',color='0.65',overplot=True)
    #Add text
    bovy_plot.bovy_text(r'$\mathrm{location}\ =\ %i$' % location
                        +'\n'
                        +r'$l\ \approx\ %.0f^\circ$' % numpy.mean(data['GLON']),
                        top_right=True,size=14.)
    if not plotfile is None:
        bovy_plot.bovy_end_print(plotfile)
Пример #12
0
                                                               logpiso,
                                                             logpisodwarf,iso)),
                                       range(options.nvlos),
                                       numcores=numpy.amin([len(vlos),multiprocessing.cpu_count(),options.multi]))
     else:
         for ii in range(options.nvlos):
             print ii
             pvlosalljhk[ii]= pvlosplate(params,vlos[ii],alljhkdata,df,options,
                                         logpiso,logpisodwarf,iso)
     pvlosalljhk-= logsumexp(pvlosalljhk)
     pvlosalljhk= numpy.exp(pvlosalljhk)
 #Plot data
 bovy_plot.bovy_print()
 hist, xvec, p= bovy_plot.bovy_hist(thesedata['VHELIO'],
                                    range=[-200.,200.],
                                    bins=31,
                                    histtype='step',color='k',
                                    xlabel=r'$\mathrm{heliocentric}\ V_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$')
 #Normalize prediction
 data_int= numpy.sum(hist)*(xvec[1]-xvec[0])
 pvlos*= data_int/numpy.sum(pvlos)/(vlos[1]-vlos[0])
 bovy_plot.bovy_plot(vlos,pvlos,'-',color='0.6',overplot=True,lw=3.)
 if _PLOTZERO:
     pvloszero*= data_int/numpy.sum(pvloszero)/(vlos[1]-vlos[0])
     bovy_plot.bovy_plot(vlos,pvloszero,'--',color='0.65',overplot=True,lw=2.)
 if _PLOTALLJHK:
     pvlosalljhk*= data_int/numpy.sum(pvlosalljhk)/(vlos[1]-vlos[0])
     bovy_plot.bovy_plot(vlos,pvlosalljhk,'--',color='0.65',overplot=True,lw=2.)
 #Add text
 bovy_plot.bovy_text(#r'$\mathrm{location}\ =\ %i$' % location
                     #+'\n'
Пример #13
0
def plot_fehafe(basefilename):
    #First read the sample
    data= apread.rcsample()
    data= data[data['SNR'] >= 70.]
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #R and z ranges to plot
    Rmins= [5.,7.,9.]
    Rmaxs= [7.,9.,11.]
    zmins= [0.,0.5,1.]
    zmaxs= [0.5,1.,2.]
    nRbins= len(Rmins)
    nzbins= len(zmins)
    for ii in range(nRbins):
        for jj in range(nzbins):
            #Cut data to relevant range
            tindx= (data['RC_GALR'] > Rmins[ii])\
                *(data['RC_GALR'] <= Rmaxs[ii])\
                *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\
                *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj])
            tdata= data[tindx]
            bovy_plot.bovy_print()
            if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX:
                bovy_plot.scatterplot(tdata['METALS'],
                                      tdata['ALPHAFE'],
                                      'k.',
                                      levels=[0.68,.90],
                                      #special.erf(numpy.arange(1,3)/numpy.sqrt(2.)),
                                      xrange=[-1.2,0.7],
                                      yrange=[-0.12,0.42],
                                      xlabel=r'$[\mathrm{Fe/H}]$',
                                      ylabel=r'$[\alpha/\mathrm{H}]$',
                                      onedhists=True,bins=31,onedhistsbins=21)
            else:
                axScatter,axHistx, axHisty=\
                    bovy_plot.bovy_plot(tdata['METALS'],
                                        tdata['ALPHAFE'],
                                        'k.',
                                        xrange=[-1.2,0.7],
                                        yrange=[-0.12,0.42],
                                        xlabel=r'$[\mathrm{Fe/H}]$',
                                        ylabel=r'$[\alpha/\mathrm{H}]$',
                                        onedhists=True,bins=21)
            if _ADDBOVYRIX:
                add_bovy_rix(axScatter,Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])
            if not _NOLINE:
                #Overplot ridge line
                bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)],
                                    '-',lw=2.,color='y',overplot=True)
            bovy_plot.bovy_text(r'$%i < R / \mathrm{kpc} \leq %i$' % (Rmins[ii],Rmaxs[ii]) +'\n'+r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]),
                                    top_left=True,size=16.)
            bovy_plot.bovy_end_print(basefilename+'_%iR%i_%.1fz%.1f.' % (Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])+_EXT)
    #Plot z bins only
    zmins= [0.,0.5,1.,2.]
    zmaxs= [0.5,1.,2.,4.]
    nzbins= len(zmins)
    for jj in range(nzbins):
        #Cut data to relevant range
        tindx= (data['RC_GALR'] > 4.)\
            *(data['RC_GALR'] <= 9.)\
                *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\
                *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj])
        tdata= data[tindx]
        bovy_plot.bovy_print()
        if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX:
            bovy_plot.scatterplot(tdata['METALS'],
                                  tdata['ALPHAFE'],
                                  'k.',
                                  levels=[0.68,.90],
                                  xrange=[-1.2,0.7],
                                  yrange=[-0.12,0.42],
                                  xlabel=r'$[\mathrm{Fe/H}]$',
                                  ylabel=r'$[\alpha/\mathrm{H}]$',
                                  onedhists=True,bins=31,onedhistsbins=31)
        else:
            axScatter,axHistx, axHisty=\
                bovy_plot.bovy_plot(tdata['METALS'],
                                    tdata['ALPHAFE'],
                                    'k.',
                                    xrange=[-1.2,0.7],
                                    yrange=[-0.12,0.42],
                                    xlabel=r'$[\mathrm{Fe/H}]$',
                                    ylabel=r'$[\alpha/\mathrm{H}]$',
                                    onedhists=True,bins=21)
        if _ADDBOVYRIX:
            add_bovy_rix(axScatter,4.,9.,zmins[jj],zmaxs[jj])
        #Overplot ridge line
        bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)],
                            '-',lw=2.,color='y',overplot=True)
        bovy_plot.bovy_text(r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]),
                                top_left=True,size=16.)
        bovy_plot.bovy_end_print(basefilename+'_%.1fz%.1f.' % (zmins[jj],zmaxs[jj])+_EXT)
    #Plot scatter in the high-alpha sequence
    #Histograms in 3 R bins
    bovy_plot.bovy_print(fig_width=7.)
    overplot= False
    colors= ['y','k','r']
    labelposx= 0.235
    labelposy= [13.,11.,9.]
    for ii in range(nRbins):
        tindx= (data['RC_GALR'] > Rmins[ii])\
            *(data['RC_GALR'] <= Rmaxs[ii])\
            *(numpy.fabs(data['RC_GALZ']) <= 3.)
        tdata= data[tindx]
        hindx= determine_highalpha(tdata)
        tdata= tdata[hindx]
        bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']),
                            color=colors[ii],histtype='step',
                            bins=28,range=[-0.275,0.25],yrange=[0.,15.],
                            weights=numpy.ones(len(tdata)),
                            xlabel=r'$\delta[\alpha\mathrm{/Fe}]$',
                            overplot=overplot,normed=True)
        dafe= tdata['ALPHAFE']-ridge1(tdata['METALS'])
        dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)]
        txa, txm, txc= run_xd(dafe)
        print txm.flatten(), numpy.sqrt(txc.flatten()), txa[0]*len(dafe)
        bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2.,
                            color=colors[ii],overplot=True)
        bovy_plot.bovy_text(labelposx,labelposy[ii],
                            r'$%i < R \leq %i: \sigma = %.3f$' % (Rmins[ii],Rmaxs[ii],numpy.sqrt(txc[0,0,0])),
                            size=16.,color=colors[ii],ha='right')
        overplot= True
    bovy_plot.bovy_end_print(basefilename+'_afefehhist.%s' % _EXT)
    #High SN
    bovy_plot.bovy_print(fig_width=7.)
    overplot= False
    for ii in range(nRbins):
        tindx= (data['RC_GALR'] > Rmins[ii])\
            *(data['RC_GALR'] <= Rmaxs[ii])\
            *(numpy.fabs(data['RC_GALZ']) <= 3.)\
            *(data['SNR'] >= 150.)
        tdata= data[tindx]
        hindx= determine_highalpha(tdata)
        tdata= tdata[hindx]
        bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']),
                            color=colors[ii],histtype='step',
                            bins=19,range=[-0.275,0.15],yrange=[0.,19.5],
                            weights=numpy.ones(len(tdata)),
                            xlabel=r'$\delta[\alpha\mathrm{/Fe}]$',
                            normed=True,
                            overplot=overplot)
        dafe= tdata['ALPHAFE']-ridge1(tdata['METALS'])
        dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)]
        txa, txm, txc= run_xd(dafe)
        print txm.flatten(), numpy.sqrt(txc.flatten())
        bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2.,
                            color=colors[ii],overplot=True)
        overplot= True
    bovy_plot.bovy_end_print(basefilename+'_afefehhist_highsn.%s' % _EXT)
    return None
Пример #14
0
def plot_2dkinematics(basesavefilename,datafilename=None):
    #Plot 2D los field
    #First read the sample
    if not datafilename is None:
        data= fitsio.read(datafilename)
    else:
        data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
    data= data[indx]
    pix= pixelize_sample.pixelXY(data)
    vmin, vmax= -75., 75.
    bovy_plot.bovy_print()
    pix.plot('VHELIO_AVG',
             zlabel=r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
             vmin=vmin,vmax=vmax)
    bovy_plot.bovy_text(r'$\mathrm{typical\ uncertainty\!:}\ 3\,\mathrm{km\,s}^{-1}$',
                        bottom_left=True,size=18.)
    bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',top_right=True,size=18.)
    bovy_plot.bovy_end_print(basesavefilename+'_XY.'+_EXT)
    #R,phi
    pix= pixelize_sample.pixelXY(data,rphi=True,
                                 ymin=-22.5,ymax=37.5,
#                                 dx=0.3,dy=2.)
#                                 dx=3.,dy=20.)
                                 dx=1.,dy=5.)
    bovy_plot.bovy_print()
    pix.plot('VHELIO_AVG',
             zlabel=r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
             vmin=vmin,vmax=vmax)
    #bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.)
    bovy_plot.bovy_end_print(basesavefilename+'_RPHI.'+_EXT)
    #Plot the dispersion / sqrt(n)
    pix= pixelize_sample.pixelXY(data,
                                 dx=1.,dy=1.)
    bovy_plot.bovy_print()
    pix.plot('VHELIO_AVG',
             func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
             zlabel=r'$\delta\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
             vmin=0.,vmax=10.)
    #bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.)
    bovy_plot.bovy_end_print(basesavefilename+'_RPHI_vlosunc.'+_EXT)
    #Plot the dispersion
    bovy_plot.bovy_print()
    pix.plot('VHELIO_AVG',
             func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x))),
             zlabel=r'$\mathrm{MAD}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
             vmin=0.,vmax=40.)
    #bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.)
    bovy_plot.bovy_end_print(basesavefilename+'_RPHI_vlosdisp.'+_EXT)
    #Now plot the los velocity corrected for the Solar motion
    #XY
    vmin, vmax= -250., 250.
    bovy_plot.bovy_print()
    resv= pix.plot(lambda x: vlosgal(x),
                   zlabel=r'$\mathrm{median}\ V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax,returnz=True)
    bovy_plot.bovy_end_print(basesavefilename+'_Vrot_XY.'+_EXT)
    pix= pixelize_sample.pixelXY(data,rphi=True,
                                 ymin=-22.5,ymax=37.5,
                                 dx=1.,dy=5.)
    #R,phi
    vmin, vmax= -250., 250.
    bovy_plot.bovy_print()
    resv= pix.plot(lambda x: vlosgal(x),
                   zlabel=r'$\mathrm{median}\ V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax,returnz=True)
    #Plot tangent point
    rs= numpy.linspace(6.,8.,101)
    bovy_plot.bovy_plot(rs,numpy.arccos(rs/8.)*180./numpy.pi,'k--',lw=2.,
                        overplot=True)
    bovy_plot.bovy_plot(rs,-numpy.arccos(rs/8.)*180./numpy.pi,'k--',lw=2.,
                        overplot=True)
    bovy_plot.bovy_end_print(basesavefilename+'_Vrot_RPHI.'+_EXT)
    #Now plot the residuals wrt the Bovy et al. (2012) disk model
    #R,phi
    vmin, vmax= -20., 20.
    bovy_plot.bovy_print()
    resv= pix.plot(lambda x: dvlosgal(x,beta=0.,vc=220.),
                   zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax,returnz=True)
    medindx= True-numpy.isnan(resv)
    meanresv= numpy.mean(resv[medindx])
    sigresv= numpy.std(resv[medindx])
    bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (meanresv,sigresv,round(numpy.sqrt(numpy.sum(medindx)))),
                        top_left=True,size=16.)
    bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12_RPHI.'+_EXT)
    #XY
    pixXY= pixelize_sample.pixelXY(data,
                                 xmin=5.,xmax=13,
                                 ymin=-3.,ymax=4.,
                                 dx=1.,dy=1.)
    vmin, vmax= -20., 20.
    bovy_plot.bovy_print()
    pixXY.plot(lambda x: dvlosgal(x,beta=0.,vc=220.),
               zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
               vmin=vmin,vmax=vmax,returnz=False)
    medindx= True-numpy.isnan(resv)
    meanresv= numpy.mean(resv[medindx])
    sigresv= numpy.std(resv[medindx])
    bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (meanresv,sigresv,round(numpy.sqrt(numpy.sum(medindx)))),
                        top_left=True,size=16.)
    bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12_XY.'+_EXT)
    #Plot a histogram of the residuals
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(resv[medindx],color='k',bins=11,xrange=[-25.,25.],
                        yrange=[0.,15.],
                        histtype='step',normed=False,
                        xlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$')
    xs= numpy.linspace(-25.,25.,1001)
    bovy_plot.bovy_plot(xs,
                        50./11.*numpy.sum(medindx)/numpy.sqrt(2.*numpy.pi)/sigresv\
                            *numpy.exp(-0.5*(xs-meanresv)**2./sigresv**2.),
                        'k-',lw=2,overplot=True)
    bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12_hist.'+_EXT) 
   #Now plot the residuals wrt the Bovy et al. (2012) disk model w/ Vc-240 and standard solar motion
    #R,phi
    vmin, vmax= -20., 20.
    bovy_plot.bovy_print()
    resv= pix.plot(lambda x: dvlosgal(x,beta=0.,vc=240.,vtsun=252.),
                   zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax,returnz=True)
    medindx= True-numpy.isnan(resv)
    #bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (numpy.median(resv[medindx]),numpy.median(numpy.fabs(resv[medindx]-numpy.median(resv[medindx])))*1.4826,round(numpy.sqrt(numpy.sum(medindx)))),
#                        top_left=True,size=16.)
    bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12Vc240VsSBD_RPHI.'+_EXT)
    #Now plot the residuals wrt the Bovy et al. (2012) disk model w/ Vc-220 and standard solar motion
    #R,phi
    vmin, vmax= -20., 20.
    bovy_plot.bovy_print()
    resv= pix.plot(lambda x: dvlosgal(x,beta=0.,vc=220.,vtsun=232.),
                   zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax,returnz=True)
    medindx= True-numpy.isnan(resv)
#    bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (numpy.median(resv[medindx]),numpy.median(numpy.fabs(resv[medindx]-numpy.median(resv[medindx])))*1.4826,round(numpy.sqrt(numpy.sum(medindx)))),
#                        top_left=True,size=16.)
    bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12Vc220VsSBD_RPHI.'+_EXT)
    #FFT
    dx= 1.
    pix= pixelize_sample.pixelXY(data,
                                 xmin=5.,xmax=13,
                                 ymin=-3.,ymax=4.,
                                 dx=dx,dy=dx)
    resv= pix.plot(lambda x: dvlosgal(x),
                   zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax,returnz=True)
    resvunc= pix.plot('VHELIO_AVG',
                      func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                      zlabel=r'$\delta\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',
                      vmin=0.,vmax=10.,returnz=True)
    import psds
    binsize= 1.5
    psd2d= psds.power_spectrum(resv,
                               binsize=binsize,wavenumber=True)
    #Simulate the noise
    newresv= numpy.random.normal(size=resv.shape)*resvunc
    newresvuni= numpy.random.normal(size=resv.shape)*5.
    psd2dnoise= psds.power_spectrum(newresv,
                                    binsize=binsize,wavenumber=True)
    psd2duni= psds.power_spectrum(newresvuni,
                                  binsize=binsize,wavenumber=True)
    bovy_plot.bovy_print()
    ks= psd2d[0][1:]/dx
    bovy_plot.bovy_plot(ks,numpy.sqrt(psd2d[1]/numpy.prod(resv.shape)/16.\
                                          /(ks[1]-ks[0]))[1:],'ko-',
                        xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                        ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1}\,\mathrm{kpc}^{1/2})$',
                        xrange=[0.,1./dx/2.],
                        yrange=[0.,10.],
                        semilogy=False)
    bovy_plot.bovy_plot(ks,numpy.sqrt(psd2dnoise[1]/numpy.prod(resv.shape)/16.\
                                          /(ks[1]-ks[0]))[1:],
                        '-',color='0.5',overplot=True,lw=2.)
    bovy_plot.bovy_plot(ks,numpy.sqrt(psd2duni[1]/numpy.prod(resv.shape)/16.\
                                          /(ks[1]-ks[0]))[1:],
                        '-',color='b',overplot=True,lw=2.)
    bovy_plot.bovy_end_print(basesavefilename+'_FFTPSD.'+_EXT)
    return None
Пример #15
0
def plotCompareData(sample, savename, plotname):
    locs = ['highb', 'outdisk', 'meddisk', 'indisk']
    indices = [highbIndx, outDiskIndx, betwDiskIndx, inDiskIndx]
    data_indices = [
        data_highbIndx, data_outDiskIndx, data_betwDiskIndx, data_inDiskIndx
    ]
    # Full prediction for numbers
    Xs, pd = compareDataModel.predict_spacedist(bf_brexp,
                                                numpy.array(locations),
                                                copy.deepcopy(effsel_mar),
                                                distmods,
                                                type='tribrokenexpflare',
                                                coord='dm')
    for loc, index, data_index in zip(locs, indices, data_indices):
        bovy_plot.bovy_print(axes_labelsize=20,
                             text_fontsize=20,
                             xtick_labelsize=20,
                             ytick_labelsize=20)
        # High |b|
        # Marshall is fiducial
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_brexp,
            numpy.array(locations)[index],
            copy.deepcopy(effsel_mar)[index],
            distmods,
            type='tribrokenexpflare',
            coord='dm')
        if (sample.lower() == 'solar' and \
                (loc.lower() == 'outdisk' or loc.lower() == 'highb')) \
                or (sample.lower() == 'highfeh' and loc.lower() == 'highb'):
            yrange = [
                0., 1.6 * numpy.amax(pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]))
            ]
        else:
            yrange = [
                0., 1.4 * numpy.amax(pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]))
            ]
        bovy_plot.bovy_hist(ldata['RC_DM_H'][data_index],
                            histtype='stepfilled',
                            normed=True,
                            lw=_LW,
                            range=[7., 15.5],
                            bins=round(numpy.sqrt(numpy.sum(data_index)) * 2.),
                            yrange=yrange,
                            ec='k',
                            fc='0.75',
                            xlabel=r'$\mu$')
        line_mar = bovy_plot.bovy_plot(Xs,
                                       pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]),
                                       color='r',
                                       lw=2. * _LW,
                                       overplot=True,
                                       zorder=12)
        bovy_plot.bovy_text(r'$%i\%% = %i / %i\ \mathrm{stars}$' \
                                % (int(round(float(numpy.sum(data_index))/len(ldata)*100.)),
                                   numpy.sum(data_index),
                                   len(ldata))
                            +'\n'+r'$%i\%% = %i / %i\ \mathrm{predicted}$' \
                                % (int(round(numpy.sum(pdt)/numpy.sum(pd)*100.)),
                                   numpy.sum(pdt)/numpy.sum(pd)*len(ldata),len(ldata)),
                            top_left=True,size=16.)
        # Green
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_brexp_g15,
            numpy.array(locations)[index],
            copy.deepcopy(effsel)[index],
            distmods,
            type='tribrokenexpflare',
            coord='dm')
        line_g15 = bovy_plot.bovy_plot(Xs,
                                       pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]),
                                       color='b',
                                       lw=_LW,
                                       overplot=True,
                                       zorder=13)
        # Drimmel
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_brexp_drim,
            numpy.array(locations)[index],
            copy.deepcopy(effsel_drim)[index],
            distmods,
            type='tribrokenexpflare',
            coord='dm')
        line_drim = bovy_plot.bovy_plot(Xs,
                                        pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]),
                                        color='gold',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=12)
        # Sale
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_brexp_sale,
            numpy.array(locations)[index],
            copy.deepcopy(effsel_sale)[index],
            distmods,
            type='tribrokenexpflare',
            coord='dm')
        line_sale = bovy_plot.bovy_plot(Xs,
                                        pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]),
                                        color='c',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=12)
        # Zero
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_brexp_zero,
            numpy.array(locations)[index],
            copy.deepcopy(effsel_zero)[index],
            distmods,
            type='tribrokenexpflare',
            coord='dm')
        line_zero = bovy_plot.bovy_plot(Xs,
                                        pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]),
                                        color='k',
                                        ls='-',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=10)
        # Marshall + exp
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_exp,
            numpy.array(locations)[index],
            copy.deepcopy(effsel_mar)[index],
            distmods,
            type='expplusconst',
            coord='dm')
        line_exp = bovy_plot.bovy_plot(Xs,
                                       pdt / numpy.sum(pdt) / (Xs[1] - Xs[0]),
                                       color='r',
                                       lw=2 * _LW,
                                       overplot=True,
                                       zorder=10,
                                       ls=':')
        # Marshall + twoexp
        Xs, pdt = compareDataModel.predict_spacedist(
            bf_twoexp,
            numpy.array(locations)[index],
            copy.deepcopy(effsel_mar)[index],
            distmods,
            type='tribrokentwoexp',
            coord='dm')
        line_twoexp = bovy_plot.bovy_plot(Xs,
                                          pdt / numpy.sum(pdt) /
                                          (Xs[1] - Xs[0]),
                                          color='r',
                                          lw=2 * _LW,
                                          overplot=True,
                                          zorder=11,
                                          ls='--')
        if sample.lower() == 'lowlow' or sample.lower() == 'highalpha':
            if loc.lower() == 'highb':
                pyplot.annotate(r'$|b| > 10^\circ$', (0.5, 1.085),
                                xycoords='axes fraction',
                                horizontalalignment='center',
                                verticalalignment='top',
                                size=20.)
            elif loc.lower() == 'indisk':
                pyplot.annotate(r'$l < 70^\circ, |b| \leq 10^\circ$',
                                (0.5, 1.085),
                                xycoords='axes fraction',
                                horizontalalignment='center',
                                verticalalignment='top',
                                size=20.)
            elif loc.lower() == 'meddisk':
                pyplot.annotate(
                    r'$70^\circ \leq l \leq 140^\circ, |b| \leq 10^\circ$',
                    (0.5, 1.085),
                    xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',
                    size=20.)
            elif loc.lower() == 'outdisk':
                pyplot.annotate(
                    r'$140^\circ < l < 250^\circ, |b| \leq 10^\circ$',
                    (0.5, 1.085),
                    xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',
                    size=20.)
            # Legend
            if loc.lower() == 'meddisk':
                pyplot.legend((line_mar[0], line_exp[0], line_twoexp[0]),
                              (r'$\mathrm{Marshall\ et\ al.\ (2006)}$' + '\n' +
                               r'$\mathrm{broken\ exp.\ w/\ flare}$',
                               r'$\mathrm{single\ exp.}$',
                               r'$\mathrm{broken\ exp.\ w/\ 2}\ h_Z$'),
                              loc='lower right',
                              bbox_to_anchor=(.66, .42),
                              numpoints=8,
                              prop={'size': 14},
                              frameon=False)
            elif loc.lower() == 'outdisk':
                pyplot.legend(
                    (line_g15[0], line_sale[0], line_drim[0], line_zero[0]),
                    (r'$\mathrm{Green\ et\ al.\ (2015)}$',
                     r'$\mathrm{Sale\ et\ al.\ (2014)}$',
                     r'$\mathrm{Drimmel\ et\ al.\ (2003)}$',
                     r'$\mathrm{zero\ extinction}$'),
                    loc='lower right',
                    bbox_to_anchor=(.66, .42),
                    numpoints=8,
                    prop={'size': 14},
                    frameon=False)
        if loc.lower() == 'highb':
            if sample.lower() == 'lowlow':
                bovy_plot.bovy_text(r'$\mathrm{low\ [Fe/H]}$',
                                    top_right=True,
                                    size=18.)
            elif sample.lower() == 'solar':
                bovy_plot.bovy_text(r'$\mathrm{solar}$',
                                    top_right=True,
                                    size=18.)
            elif sample.lower() == 'highfeh':
                bovy_plot.bovy_text(r'$\mathrm{high\ [Fe/H]}$',
                                    top_right=True,
                                    size=18.)
            elif sample.lower() == 'highalpha':
                bovy_plot.bovy_text(r'$\mathrm{high}\ [\alpha/\mathrm{Fe]}$',
                                    top_right=True,
                                    size=18.)
        bovy_plot.bovy_end_print(plotname.replace('LOC', loc))
    return None
Пример #16
0
def plotPixelFitVel(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin,
                              distfac=options.distfac)
    if not options.bmin is None:
        #Cut on |b|
        raw= raw[(numpy.fabs(raw.b) > options.bmin)]
    #print len(raw)
    #Bin the data   
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    #ndata= 0
    #maxndata= 0
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            if afeindx+fehindx*binned.npixafe() >= len(fits):
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            thisfit= fits[afeindx+fehindx*binned.npixafe()]
            if thisfit is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            #if len(data) > maxndata: maxndata= len(data)
            #ndata+= len(data)
            if options.model.lower() == 'hwr':
                if options.type == 'sz':
                    plotthis[ii,jj]= numpy.exp(thisfit[1])
                elif options.type == 'sz2':
                    plotthis[ii,jj]= numpy.exp(2.*thisfit[1])
                elif options.type == 'hs':
                    plotthis[ii,jj]= numpy.exp(thisfit[4])
                elif options.type == 'hsm':
                    plotthis[ii,jj]= numpy.exp(-thisfit[4])
                elif options.type == 'pbad':
                    plotthis[ii,jj]= thisfit[0]
                elif options.type == 'slopes':
                    plotthis[ii,jj]= thisfit[2]
                elif options.type == 'slope':
                    plotthis[ii,jj]= thisfit[2]
                elif options.type == 'chi2dof':
                    plotthis[ii,jj]= thisfit[6]
                elif options.type.lower() == 'afe' \
                        or options.type.lower() == 'feh' \
                        or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    plotthis.append([tightbinned.feh(ii),
                                     tightbinned.afe(jj),
                                     numpy.exp(thisfit[1]),
                                     numpy.exp(thisfit[3]),
                                     len(data)])
    #print ndata
    #print maxndata
    #Set up plot
    #print numpy.nanmin(plotthis), numpy.nanmax(plotthis)
    if options.type == 'sz':
        if options.vr:
            vmin, vmax= 40.,80.
            zlabel= r'$\sigma_R(z = \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$'
        else:
            vmin, vmax= 10.,60.
            zlabel= r'$\sigma_z(z_{1/2})\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'sz2':
        if options.vr:
            vmin, vmax= 40.**2.,80.**2.
            zlabel= r'$\sigma_R^2(z= \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$'
        else:
            vmin, vmax= 15.**2.,50.**2.
            zlabel= r'$\sigma_z^2(z= \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'hs':
        if options.vr:
            vmin, vmax= 3.,25.
            zlabel= r'$R_\sigma\ [\mathrm{kpc}]$'
        else:
            vmin, vmax= 3.,15.
            zlabel= r'$h_\sigma\ [\mathrm{kpc}]$'
    elif options.type == 'hsm':
        if options.vr:
            vmin, vmax= 0.,0.3
            zlabel= r'$R^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
        else:
            vmin, vmax= 0.,0.3
            zlabel= r'$R^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$'
    elif options.type == 'slope':
        vmin, vmax= -5.,5.
        zlabel= r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$'
    elif options.type == 'pbad':
        vmin, vmax= 0.,0.1
        zlabel= r'$P_{\mathrm{bad}}$'
    elif options.type == 'chi2dof':
        vmin, vmax= 0.5,1.5
        zlabel= r'$\chi^2/\mathrm{dof}$'
    elif options.type == 'afe':
        vmin, vmax= 0.05,.4
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.5,0.
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.6]
        yrange=[-0.1,0.6]
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        print "Update!! Never used until now (afe etc. type fitting is in plotsz2hz"
        return None
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        #Gather hR and hz
        hz, hr,afe, feh, ndata= [], [], [], [], []
        for ii in range(len(plotthis)):
            hz.append(plotthis[ii][2])
            hr.append(plotthis[ii][3])
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][4])
        hz= numpy.array(hz)
        hr= numpy.array(hr)
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata))
        #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        yrange= [150,1200]
        xrange= [1.2,5.]
        bovy_plot.bovy_plot(hr,hz,s=ndata,c=plotc,
                            cmap='jet',
                            ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$',
                            xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$',
                            clabel=zlabel,
                            xrange=xrange,yrange=yrange,
                            vmin=vmin,vmax=vmax,
                            scatter=True,edgecolors='none',
                            colorbar=True)
    elif options.type.lower() == 'slopes':
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(plotthis.flatten(),
                            range=[-5.,5.],
                            bins=11,
                            histtype='step',
                            color='k',
                            xlabel=r'$\sigma_z(z)\ \mathrm{slope\ [km\ s}^{-1}\ \mathrm{kpc}^{-1}]$')
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              contours=False,
                              colorbar=True,shrink=0.78)
    if options.observed:
        bovy_plot.bovy_text(r'$\mathrm{observed}$',
                            top_right=True,size=18.)
    bovy_plot.bovy_end_print(options.plotfile)
    return None
Пример #17
0
def plot_fake_data(parser):
    """
    NAME:
       plot_fake_data
    PURPOSE:
       plot the fake data created by create_fake_data
    INPUT:
       parser - from optparse
    OUTPUT:
       stuff as specified by the options
    HISTORY:
       2011-04-20 - Written - Bovy (NYU)
    """
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        sys.exit(-1)
    #Set up DF
    dfc= dehnendf(beta=options.beta,profileParams=(options.rd,options.rs,options.so),correct=True,niter=20)
    #Open pickle
    picklefile= open(args[0],'rb')
    out= pickle.load(picklefile)
    picklefile.close()
    if not options.vlosdname is None:
        #Plot distribution of vlos vs. d
        vloss=nu.array([o.vlos(obs=[1.,0.,0.,0.,1.,0.],ro=1.,vo=1.) \
                            for o in out]).flatten()
        ds= nu.array([o.dist(obs=[1.,0.,0.],ro=1.) \
                          for o in out]).flatten()
        #Also calculate the expected relation
        ntheory= 1001
        dx= nu.linspace(0.,2.,ntheory)
        vtheory= nu.zeros(ntheory)
        l= options.los*_DEGTORAD
        for ii in range(ntheory):
            R= nu.sqrt(1.+dx[ii]**2.-2.*dx[ii]*nu.cos(l))
            if 1./nu.cos(l) < dx[ii] and nu.cos(l) > 0.:
                phi= nu.pi-m.asin(dx[ii]/R*nu.sin(l))
            else:
                phi= m.asin(dx[ii]/R*nu.sin(l))
            vtheory[ii]= (R**options.beta-dfc.asymmetricdrift(R))*m.sin(phi+l)-m.sin(l) #last term is the LSR
        bovy_plot.bovy_print()
        bovy_plot.scatterplot(ds,vloss,'.',bins=options.scatterbins,
                              xlabel=r'$d / R_0$',
                              ylabel=r'$v_{los} / v_0$')
        bovy_plot.bovy_plot(dx,vtheory,overplot=True)
        bovy_plot.bovy_text(r'$l = %i^\circ$' % round(options.los),
                            top_left=True)
        bovy_plot.bovy_end_print(options.vlosdname)
    if not options.vtname is None:
        vts= nu.array([o[1]-1. for o in out]).flatten() #subtract vc
        #Calculate expected
        ntheory= 1001
        vx= nu.linspace(-1.,1.,ntheory)
        y= nu.zeros(ntheory)
        for ii in range(ntheory):
            y[ii]= dfc(Orbit([1.,0.,vx[ii]+1.]))
        y/= nu.sum(y)*(vx[1]-vx[0])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(vts,bins=options.histbins,normed=True,
                            xlabel=r'$v_T / v_0 - 1$')
        bovy_plot.bovy_plot(vx,y,overplot=True)
        bovy_plot.bovy_end_print(options.vtname)
    if not options.vrname is None:
        vrs= nu.array([o[0] for o in out]).flatten() #subtract vc
        #Calculate expected
        ntheory= 1001
        vx= nu.linspace(-1.,1.,ntheory)
        y= nu.zeros(ntheory)
        vT= 1.-dfc.asymmetricdrift(1.)
        for ii in range(ntheory):
            y[ii]= dfc(Orbit([1.,vx[ii],vT]))
        y/= nu.sum(y)*(vx[1]-vx[0])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(vrs,bins=options.histbins,normed=True,
                            xlabel=r'$v_R / v_0$')
        bovy_plot.bovy_plot(vx,y,overplot=True)
        bovy_plot.bovy_end_print(options.vrname)
    if not options.vrvtname is None:
        vts= nu.array([o[1]-1. for o in out]).flatten() #subtract vc
        vrs= nu.array([o[0] for o in out]).flatten() #subtract vc
        bovy_plot.bovy_print()
        bovy_plot.scatterplot(vrs,vts,'.',bins=options.scatterbins,
                              xlabel=r'$v_R / v_0$',
                              ylabel=r'$v_T / v_0 - 1$')
        bovy_plot.bovy_end_print(options.vrvtname)
Пример #18
0
def plot_mapflarepdf(savename, plotname):
    # Load the samples
    with open('../mapfits/tribrokenexpflare.sav', 'rb') as savefile:
        bf = numpy.array(pickle.load(savefile))
        samples = numpy.array(pickle.load(savefile))
    maps = define_rcsample.MAPs()
    # Loop through the low-alpha MAPs and compute the XD decomposition
    if 'lowalpha' in savename:
        plotmaps = [9, 16, 23, 29, 36, 43, 50, 57, 64, 71]
    else:
        plotmaps = [19, 26, 32, 39, 45]
    if not os.path.exists(savename):
        ngauss = 2
        allxamp = numpy.empty((len(plotmaps), ngauss))
        allxmean = numpy.empty((len(plotmaps), ngauss, 1))
        allxcovar = numpy.empty((len(plotmaps), ngauss, 1, 1))
        cnt = 0
        for ii, map in enumerate(maps.map()):
            if not ii in plotmaps: continue
            print ii
            # Fit PDFs with XD
            xamp = numpy.array([0.45, 0.5])
            xmean = numpy.array([
                numpy.mean(samples[ii, 4]) +
                numpy.random.normal() * numpy.std(samples[ii, 4]),
                numpy.mean(samples[ii, 4]) +
                numpy.random.normal() * numpy.std(samples[ii, 4])
            ])[:, numpy.newaxis]
            xcovar = numpy.reshape(
                numpy.tile(numpy.var(samples[ii, 4]), (2, 1)), (2, 1, 1))
            XD.extreme_deconvolution(samples[ii, 4][:, numpy.newaxis],
                                     numpy.zeros((len(samples[ii, 4]), 1)),
                                     xamp, xmean, xcovar)
            allxamp[cnt] = xamp
            allxmean[cnt] = xmean
            allxcovar[cnt] = xcovar
            cnt += 1
        save_pickles(savename, allxamp, allxmean, allxcovar)
    else:
        with open(savename, 'rb') as savefile:
            allxamp = pickle.load(savefile)
            allxmean = pickle.load(savefile)
            allxcovar = pickle.load(savefile)
    # Now plot
    cmap = cm.coolwarm
    xrange = [-0.37, 0.25]
    if 'lowalpha' in savename:
        #        xrange= [-0.4,0.2]
        yrange = [0., 30.]
        combDiv = 2.
        colorFunc = lambda x: cmap((x + 0.6) * 0.95 / 0.9 + 0.05)
    else:
        #        xrange= [-0.3,0.3]
        yrange = [0., 13.5]
        colorFunc = lambda x: cmap((x + 0.5) * 0.95 / 0.5 + 0.05)
        combDiv = 1.5
    overplot = False
    plotXDFit = True
    cnt = 0
    bovy_plot.bovy_print(axes_labelsize=18,
                         text_fontsize=18,
                         xtick_labelsize=14,
                         ytick_labelsize=14)
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        tfeh = round(numpy.median(map['FE_H']) * 20.) / 20.
        if tfeh == 0.25: tfeh = 0.3
        if tfeh == -0.1: tfeh = -0.1
        bovy_plot.bovy_hist(
            samples[ii, 4],
            range=xrange,
            bins=51,
            overplot=overplot,
            yrange=yrange,
            histtype='step',
            normed=True,
            zorder=2,
            color=colorFunc(tfeh),
            xlabel=r'$R_{\mathrm{flare}}^{-1}\,(\mathrm{kpc}^{-1})$')
        if plotXDFit:
            txs = numpy.linspace(xrange[0], xrange[1], 1001)
            pyplot.plot(
                txs,
                1. / numpy.sqrt(2. * numpy.pi) *
                (allxamp[cnt, 0] / numpy.sqrt(allxcovar[cnt, 0, 0, 0]) *
                 numpy.exp(-0.5 * (txs - allxmean[cnt, 0, 0])**2. /
                           allxcovar[cnt, 0, 0, 0]) +
                 allxamp[cnt, 1] / numpy.sqrt(allxcovar[cnt, 1, 0, 0]) *
                 numpy.exp(-0.5 * (txs - allxmean[cnt, 1, 0])**2. /
                           allxcovar[cnt, 1, 0, 0])),
                color=colorFunc(tfeh),
                zorder=1)
        overplot = True
        cnt += 1
    txs = numpy.linspace(xrange[0], xrange[1], 1001)
    comb = numpy.ones_like(txs)
    for ii in range(len(plotmaps)):
        comb *= 1. / numpy.sqrt(2. * numpy.pi) * (
            allxamp[ii, 0] / numpy.sqrt(allxcovar[ii, 0, 0, 0]) *
            numpy.exp(-0.5 *
                      (txs - allxmean[ii, 0, 0])**2. / allxcovar[ii, 0, 0, 0])
            + allxamp[ii, 1] / numpy.sqrt(allxcovar[ii, 1, 0, 0]) *
            numpy.exp(-0.5 *
                      (txs - allxmean[ii, 1, 0])**2. / allxcovar[ii, 1, 0, 0]))
    comb /= numpy.sum(comb) * (txs[1] - txs[0])
    pyplot.plot(txs, comb / combDiv, 'k-', lw=2., zorder=20)
    pyplot.plot([0., 0.], [0., 50.], 'k--', lw=1.5, zorder=0)
    t = pyplot.text(
        xrange[0] + 0.25 * (xrange[1] - xrange[0]) + 0.03 *
        ('highalpha' in savename),
        0.8 * yrange[1],
        r'$R_{\mathrm{flare}}^{-1} = %.2f \pm %.2f\,\mathrm{kpc}^{-1}$' %
        (numpy.sum(comb * txs) / numpy.sum(comb),
         numpy.sqrt(
             numpy.sum(comb * txs**2.) / numpy.sum(comb) -
             (numpy.sum(comb * txs) / numpy.sum(comb))**2.)),
        size=18.)
    t.set_bbox(dict(color='w', edgecolor='none'))
    if 'lowalpha' in savename:
        bovy_plot.bovy_text(
            r'$\mathrm{low-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
            top_left=True,
            size=16.)
    else:
        bovy_plot.bovy_text(
            r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
            top_left=True,
            size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
Пример #19
0
                   profileParams=(1./3.,1.,0.4))
     vs= dfc.sampleVRVT(1.,n=100000,nsigma=5)
     vts04= vs[:,1].flatten()
     save_pickles(savefilename,vts01,vts02,vts04)
 xs= numpy.linspace(-1.,2.,1001)
 bf= optimize.fmin(optm,[.8,0.4,-0.3],(vts04,))
 print bf[2]
 ys= skewnormal(xs,bf[0],numpy.exp(bf[1]),bf[2])
 bovy_plot.bovy_print()
 bovy_plot.bovy_plot(xs,ys,'k-',zorder=2,
                     xlabel=r'$v_T / v_0$',
                     ylabel=r'$\mathrm{normalized\ distribution}$',
                     xrange=[-.5,1.5],
                     yrange=[0.,6.])
 bovy_plot.bovy_hist(vts04,bins=101,normed=True,
                     overplot=True,
                     histtype='step',
                     color='k')
 bf= optimize.fmin(optm,[9.,0.2,-0.1],(vts02,))
 print bf[2]
 ys= skewnormal(xs,bf[0],numpy.exp(bf[1]),bf[2])
 bovy_plot.bovy_hist(vts02,bins=101,normed=True,
                     histtype='step',
                     overplot=True,
                     color='k')
 bovy_plot.bovy_plot(xs,ys,'k-',overplot=True)
 bf= optimize.fmin(optm,[1.,0.1,0.1],(vts01,))
 print bf[2]
 ys= skewnormal(xs,bf[0],numpy.exp(bf[1]),bf[2])
 bovy_plot.bovy_hist(vts01,bins=101,normed=True,
                     histtype='step',
                     overplot=True,
def plot_stream_times(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                     'gd1_evol_hitres_aa_01312.dat'),
                        delimiter=',')
    #Calculate times at which stars were stripped, angles
    thetar= data[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    thetar= thetar[indx]
    thetap= data[:,7]
    thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
    thetap= thetap[indx]
    thetaz= data[:,8]
    thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
    thetaz= thetaz[indx]
    #center around 0 (instead of pi)
    thetar-= numpy.pi
    thetap-= numpy.pi
    thetaz-= numpy.pi
    #Frequencies
    Or= data[:,3]
    Op= data[:,4]
    Oz= data[:,5]
    dOr= Or[indx]-numpy.median(Or)
    dOp= Op[indx]-numpy.median(Op)
    dOz= Oz[indx]-numpy.median(Oz)
    #Times
    dangle= numpy.vstack((thetar,thetap,thetaz))
    dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
    dts= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
    if 'hist' in plotfilename:
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(dts,range=[0.,6.],bins=13,
                            xlabel=r'$t_s\ (\mathrm{Gyr})$',
                            histtype='step',color='k',normed=True,lw=2.)
        bovy_plot.bovy_hist(dts,range=[0.,6.],bins=61,normed=True,
                            overplot=True,ls='dotted',histtype='step',
                            color='0.5',lw=2.)
        includeorbit= False #bc pericenter passage doesn't seem to work
        if includeorbit:
            npts= 10001
            pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
            ts= numpy.linspace(0.,5./bovy_conversion.time_in_Gyr(220.,8.),
                               npts)
            #Calculate progenitor orbit around this point
            pox= numpy.median(data[:,1])
            poy= numpy.median(data[:,3])
            poz= numpy.median(data[:,2])
            povx= numpy.median(data[:,4])
            povy= numpy.median(data[:,6])
            povz= numpy.median(data[:,5])
            pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)
            pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,
                                                     pphi,pZ,cyl=True)
            o= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])
            o.integrate(ts,pot)
            rs= numpy.sqrt(o.R(ts)**2.+o.z(ts)**2.)
            #Find local minima
            periIndx= numpy.r_[True, rs[1:] < rs[:-1]] & numpy.r_[rs[:-1] < rs[1:], True]
            for ii in range(numpy.sum(periIndx)):
                bovy_plot.bovy_plot([ts[periIndx][ii]*bovy_conversion.time_in_Gyr(220.,8.),
                                     ts[periIndx][ii]*bovy_conversion.time_in_Gyr(220.,8.)],
                                    [0.,1.],overplot=True,ls='--',lw=1.,
                                    color='0.5')
    elif 'dO' in plotfilename:
        bovy_plot.bovy_print()
        bovy_plot.bovy_plot(dts,
                            numpy.sqrt(numpy.sum(dO**2.,axis=0)),
                            'k.',
                            xrange=[0.,6.],
                            yrange=[0.1,0.35],
                            xlabel=r'$t_s\ (\mathrm{Gyr})$',
                            ylabel=r'$|\Delta \mathbf{\Omega}|\ (\mathrm{Gyr}^{-1})$')
    elif 'da' in plotfilename:
        bovy_plot.bovy_print()
        bovy_plot.bovy_plot(dts,
                            numpy.sqrt(numpy.sum(dangle**2.,axis=0)),
                            'k.',
                            xrange=[0.,6.],
                            yrange=[0.,1.5],
                            xlabel=r'$t_s\ (\mathrm{Gyr})$',
                            ylabel=r'$|\Delta \boldsymbol\theta|$')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Пример #21
0
def calc_es():
    savefilename = 'myes.sav'
    if os.path.exists(savefilename):
        savefile = open(savefilename, 'rb')
        mye = pickle.load(savefile)
        e = pickle.load(savefile)
        savefile.close()
    else:
        #Read data
        dialect = csv.excel
        dialect.skipinitialspace = True
        reader = csv.reader(open('../data/Dierickx-etal-tab2.txt', 'r'),
                            delimiter=' ',
                            dialect=dialect)
        vxvs = []
        es = []
        vphis = []
        vxs = []
        vys = []
        vzs = []
        ls = []
        for row in reader:
            thisra = float(row[3])
            thisdec = float(row[4])
            thisd = float(row[17]) / 1000.
            thispmra = float(row[13])
            thispmdec = float(row[15])
            thisvlos = float(row[11])
            thise = float(row[26])
            vxvs.append(
                [thisra, thisdec, thisd, thispmra, thispmdec, thisvlos])
            es.append(thise)
            vphis.append(float(row[25]))
            vxs.append(float(row[19]))
            vys.append(float(row[21]))
            vzs.append(float(row[23]))
            ls.append(float(row[5]))
        vxvv = nu.array(vxvs)
        e = nu.array(es)
        vphi = nu.array(vphis)
        vx = nu.array(vxs)
        vy = nu.array(vys)
        vz = nu.array(vzs)
        l = nu.array(ls)

        #Define potential
        lp = LogarithmicHaloPotential(normalize=1.)
        mp = MiyamotoNagaiPotential(a=0.5, b=0.0375, amp=1., normalize=.6)
        np = NFWPotential(a=4.5, normalize=.35)
        hp = HernquistPotential(a=0.6 / 8, normalize=0.05)
        ts = nu.linspace(0., 20., 10000)

        mye = nu.zeros(len(e))
        for ii in range(len(e)):
            #Integrate the orbit
            o = Orbit(vxvv[ii, :], radec=True, vo=220., ro=8.)
            o.integrate(ts, lp)
            mye[ii] = o.e()

        #Save
        savefile = open(savefilename, 'wb')
        pickle.dump(mye, savefile)
        pickle.dump(e, savefile)
        savefile.close()

    #plot
    plot.bovy_print()
    plot.bovy_plot(nu.array([0., 1.]),
                   nu.array([0., 1.]),
                   'k-',
                   xlabel=r'$\mathrm{Dierickx\ et\ al.}\ e$',
                   ylabel=r'$\mathrm{galpy}\ e$')
    plot.bovy_plot(e, mye, 'k,', overplot=True)
    plot.bovy_end_print('myee.png')

    plot.bovy_print()
    plot.bovy_hist(e, bins=30, xlabel=r'$\mathrm{Dierickx\ et\ al.}\ e$')
    plot.bovy_end_print('ehist.png')

    plot.bovy_print()
    plot.bovy_hist(mye, bins=30, xlabel=r'$\mathrm{galpy}\ e$')
    plot.bovy_end_print('myehist.png')
Пример #22
0
                gauxd_mean[irad, :] = initmean[sortindx, 0]
                gauxd_std[irad, :] = np.sqrt(initcovar[sortindx, 0, 0])
                gauxd_rr[irad] = rr

                # for plot
                if FigGauMod == True:
                    xs = np.linspace(-50., 50., 1001)
                    ys = np.sum(np.atleast_2d( \
                        initamp/np.sqrt(initcovar[:,0,0])).T\
                        *np.exp(-0.5*(xs-np.atleast_2d(initmean[:,0]).T)**2. \
                        /np.atleast_2d(initcovar[:,0,0]).T),axis=0)\
                        /np.sqrt(2.*np.pi)
                    _ = bovy_plot.bovy_hist(vals,
                                            bins=41,
                                            range=[-50., 50.],
                                            histtype='step',
                                            lw=2.,
                                            normed=True,
                                            overplot=True)
                    plt.plot(xs, ys)
                    for ii in range(ngauss):
                        ys = (initamp[ii]/np.sqrt(initcovar[ii,0,0]))\
                            *np.exp(-0.5*(xs-initmean[ii,0])**2. \
                            /initcovar[ii,0,0])/np.sqrt(2.*np.pi)
                        plt.plot(xs, ys)
                    # print("Combined <v^2>, sqrt(<v^2>):",combined_sig2( \
                    #    initamp,initmean[:,0],initcovar[:,0,0]),
                    #    np.sqrt(combined_sig2(initamp,initmean[:,0],initcovar[:,0,0])))
                    plt.xlabel(r'$V\,(\mathrm{km\,s}^{-1})$')
                    filename = 'samp' + str(isamp) + 'v' + str(
                        ivel) + 'r' + cirad + '.png'
def plotVelComparisonDFMulti(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    gafes, gfehs, left_legend= getMultiComparisonBins(options)
    M= len(gfehs)
    if options.andistances:
        distancefacs= numpy.zeros_like(fehs)
        gdistancefacs= numpy.zeros_like(gfehs)
        for jj in range(M):
            #Find pop corresponding to this bin
            ii= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
            print ii
            #Get the relevant data
            data= binned(fehs[ii],afes[ii])
            distancefacs[ii]= AnDistance.AnDistance(data.dered_g-data.dered_r,
                                                    data.feh)
            gdistancefacs[jj]= distancefacs[ii]
            options.fixdm= numpy.log10(distancefacs[ii])*5.
            #Apply distance factor to the data
            newraw= read_rawdata(options)
            newbinned= pixelAfeFeh(newraw,dfeh=options.dfeh,dafe=options.dafe)
            thisdataIndx= binned.callIndx(fehs[ii],afes[ii])
            binned.data.xc[thisdataIndx]= newbinned.data.xc[thisdataIndx]
            binned.data.yc[thisdataIndx]= newbinned.data.yc[thisdataIndx]
            binned.data.zc[thisdataIndx]= newbinned.data.zc[thisdataIndx]
            binned.data.plate[thisdataIndx]= newbinned.data.plate[thisdataIndx]
            binned.data.dered_r[thisdataIndx]= newbinned.data.dered_r[thisdataIndx]
    else:
        distancefacs=numpy.ones_like(fehs)
        gdistancefacs=numpy.ones_like(gfehs)
    ##########POTENTIAL PARAMETERS####################
    potparams1= numpy.array([numpy.log(2.5/8.),options.fixvc/220.,
                             numpy.log(400./8000.),0.2,0.])
    if options.group.lower() == 'aenhanced':
        potparams2= numpy.array([numpy.log(2.8/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.266666666,0.])
        potparams3= numpy.array([numpy.log(2.8/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.8,0.])
    elif options.group.lower() == 'aintermediate':
        potparams2= numpy.array([numpy.log(3.0/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.3333333333333,0.])
        potparams3= numpy.array([numpy.log(3.0/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.933333333333,0.])
    elif options.group.lower() == 'apoor':
        potparams2= numpy.array([numpy.log(2.6/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),0.4,0.])
        potparams3= numpy.array([numpy.log(2.6/8.),options.fixvc/220.,
                                 numpy.log(400./8000.),1.0,0.])
    options.potential=  'dpdiskplhalofixbulgeflatwgasalt'
    #Check whether fits exist, if not, pop
    removeBins= numpy.ones(M,dtype='bool')
    for jj in range(M):
        #Find pop corresponding to this bin
        pop= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
        #Load savefile
        if not options.init is None:
            #Load initial parameters from file
            savename= options.init
            spl= savename.split('.')
            newname= ''
            for ll in range(len(spl)-1):
                newname+= spl[ll]
                if not ll == len(spl)-2: newname+= '.'
            newname+= '_%i.' % pop
            newname+= spl[-1]
            if not os.path.exists(newname):
                removeBins[jj]= False
        else:
            raise IOError("base filename not specified ...")
    if numpy.sum(removeBins) == 0:
        raise IOError("None of the group bins have been fit ...")
    elif numpy.sum(removeBins) < M:
        #Some bins have not been fit yet, and have to be remove
        gfehs= list((numpy.array(gfehs))[removeBins])
        gafes= list((numpy.array(gafes))[removeBins])
        print "Only using %i bins out of %i ..." % (numpy.sum(removeBins),M)
        M= len(gfehs)
    data= []
    zs= []
    velps= numpy.zeros((len(binned.data),options.nv))
    velps[:,:]= numpy.nan
    velps2= numpy.zeros((len(binned.data),options.nv))
    velps2[:,:]= numpy.nan
    velps3= numpy.zeros((len(binned.data),options.nv))
    velps3[:,:]= numpy.nan
    cumulndata= 0
    if options.type.lower() == 'vz':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-180.,180.,options.nv)
            xrange=[-180.,180.]
            bins= 39
        elif options.group == 'aintermediate':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 33
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-120.,120.,options.nv)
            xrange=[-140.,140.]
            bins= 26
        xlabel=r'$V_Z\ (\mathrm{km\,s}^{-1})$'
    elif options.type.lower() == 'vr':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-220.,220.,options.nv)
            xrange=[-220.,220.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 26
        xlabel=r'$V_R\ (\mathrm{km\,s}^{-1})$'
    elif options.type.lower() == 'vt':
        if options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        xlabel=r'$V_T\ (\mathrm{km\,s}^{-1})$'
    alts= True
    if not options.multi is None:
        #Generate list of temporary files
        tmpfiles= []
        for jj in range(M): 
            tfile, tmpfile= tempfile.mkstemp()
            os.close(tfile) #Close because it's open
            tmpfiles.append(tmpfile)
        try:
            dummy= multi.parallel_map((lambda x: run_calc_model_multi(x,M,gfehs,gafes,fehs,afes,options,
                                                                      vs,
                                                                      potparams1,potparams2,potparams3,
                                                                      distancefacs,
                                                                      binned,alts,True,tmpfiles)),
                                      range(M),
                                      numcores=numpy.amin([M,
                                                           multiprocessing.cpu_count(),
                                                           options.multi]))
            #Now read all of the temporary files
            for jj in range(M):
                tmpfile= open(tmpfiles[jj],'rb')
                tvelps= pickle.load(tmpfile)
                if tvelps is None:
                    continue
                tvelps2= pickle.load(tmpfile)
                tvelps3= pickle.load(tmpfile)
                data.extend(pickle.load(tmpfile))
                zs.extend(pickle.load(tmpfile))
                tndata= pickle.load(tmpfile)
                velps[cumulndata:cumulndata+tndata,:]= tvelps
                velps2[cumulndata:cumulndata+tndata,:]= tvelps2
                velps3[cumulndata:cumulndata+tndata,:]= tvelps3
                cumulndata+= tndata
                tmpfile.close()
        finally:
            for jj in range(M):
                os.remove(tmpfiles[jj])
    else:
        for jj in range(M):
            try:
                tvelps, tvelps2, tvelps3, tdata, tzs, tndata= run_calc_model_multi(jj,M,gfehs,gafes,fehs,afes,options,
                                                                                   vs,
                                                                                                                                potparams1,potparams2,potparams3,
                                                                      distancefacs,
                                                                                                                                binned,alts,
                                                                                                                                False,None)
            except TypeError:
                continue
            velps[cumulndata:cumulndata+tndata,:]= tvelps
            velps2[cumulndata:cumulndata+tndata,:]= tvelps2
            velps3[cumulndata:cumulndata+tndata,:]= tvelps3
            data.extend(tdata)
            zs.extend(tzs)
            cumulndata+= tndata
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data,bins=26,normed=True,color='k',
                        histtype='step',
                        xrange=xrange,xlabel=xlabel)
    plotp= numpy.nansum(velps[:cumulndata,:],axis=0)/cumulndata
    print numpy.sum(plotp)*(vs[1]-vs[0])
    bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
    if alts:
        plotp= numpy.nansum(velps2,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
        plotp= numpy.nansum(velps3,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
    if not left_legend is None:
        bovy_plot.bovy_text(left_legend,top_left=True,size=_legendsize)
    bovy_plot.bovy_text(r'$\mathrm{full\ subsample}$'
                        +'\n'+
                        '$%i \ \ \mathrm{stars}$' % 
                        len(data),top_right=True,
                        size=_legendsize)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_all.'+options.ext)
    if options.all: return None
    #Plot zranges
    #First determine the ranges that have nstars in them
    rranges_nstars= 1000
    zs= numpy.array(zs)
    data= numpy.array(data)
    tdata_z= sorted(numpy.fabs(zs))
    nbins= numpy.ceil(len(tdata_z)/float(rranges_nstars))
    rranges_nstars= int(numpy.floor(float(len(tdata_z))/nbins))
    accum= rranges_nstars
    zranges= [0.0]
    while accum < len(tdata_z):
        zranges.append(tdata_z[accum])
        accum+= rranges_nstars
    zranges.append(5.0)
    print zranges
    #zranges= [0.5,1.,1.5,2.,3.,4.]
    nzranges= len(zranges)-1
    sigzsd= numpy.empty(nzranges)
    esigzsd= numpy.empty(nzranges)
    sigzs1= numpy.empty(nzranges)
    sigzs2= numpy.empty(nzranges)
    sigzs3= numpy.empty(nzranges)
    for ii in range(nzranges):
        indx= (numpy.fabs(zs) >= zranges[ii])*(numpy.fabs(zs) < zranges[ii+1])
        plotp= numpy.nansum(velps[indx,:],axis=0)/numpy.sum(indx)
        yrange= [0.,1.35*numpy.nanmax(plotp)]
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(data[indx],bins=26,normed=True,color='k',
                            histtype='step',
                            yrange=yrange,
                            xrange=xrange,xlabel=xlabel)
        sigzsd[ii]= numpy.std(data[indx][(numpy.fabs(data[indx]) < 100.)])
        esigzsd[ii]= sigzsd[ii]/numpy.sqrt(float(len(data[indx][(numpy.fabs(data[indx]) < 100.)])))
        sigzs1[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
        bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
        if alts:
            plotp= numpy.nansum(velps2[indx,:],axis=0)/numpy.sum(indx)
            sigzs2[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
            plotp= numpy.nansum(velps3[indx,:],axis=0)/numpy.sum(indx)
            sigzs3[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
        bovy_plot.bovy_text(r'$ %i\ \mathrm{pc} \leq |Z| < %i\ \mathrm{pc}$' % (int(1000*zranges[ii]),int(1000*zranges[ii+1])),
#                            +'\n'+
#                            '$%i \ \ \mathrm{stars}$' % (numpy.sum(indx)),
                            top_right=True,
                            size=_legendsize)
        bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_z%.1f_z%.1f.' % (zranges[ii],zranges[ii+1])+options.ext)
    #Plot velocity dispersion as a function of |Z|
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzsd,
                        'ko',
                        xlabel=r'$|Z|\ (\mathrm{kpc})$',
                        ylabel=r'$\sigma_z\ (\mathrm{km\,s}^{-1})$',
                        xrange=[0.,4.],
                        yrange=[0.,60.])
    pyplot.errorbar(((numpy.roll(zranges,-1)+zranges)/2.)[:-1],sigzsd,
                    yerr=esigzsd,
                    marker='o',color='k',linestyle='none')
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzs1,
                        'r+',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzs2,
                        'cx',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:-1]),sigzs3,
                        'gd',overplot=True,ms=10.)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_szvsz.' +options.ext)
    return None
Пример #24
0
def fitMass():
    #Read data
    vcircdata= numpy.loadtxt('vcirc.txt',comments='#',delimiter='|')
    vcircdata[:,0]/= _REFR0
    vcircdata[:,1]/= _REFV0
    vcircdata[:,2]/= _REFV0
    #Set-up
    bp= HernquistPotential(a=0.6/_REFR0,normalize=1./3.)
    if _dexp:
        dp= DoubleExponentialDiskPotential(normalize=1./3.,
                                           hr=3.25/_REFR0,
                                           hz=0.3/_REFR0)
    else:
        dp= MiyamotoNagaiPotential(normalize=1./3.,
                                   a=3.25/_REFR0,
                                   b=0.3/_REFR0)
    hp= NFWPotential(normalize=1./3.,
                     a=5./_REFR0)
    init= numpy.array([0.6,0.35,218./_REFV0,15./_REFR0,3.25/_REFR0])
    #print _convertrho
    out= optimize.fmin_powell(obj,init,args=(vcircdata,bp,dp,hp),
                              callback=cb)
    print out
    #Calculate mass
    #Halo mass
    halo= halomass(out)
    bulge= halomass(out)
    disk= diskmass(out)
    print halo, disk, bulge, totalmass(out)
    #Sample
    samples= bovy_mcmc.markovpy(out,0.05,
                                (lambda x: -obj(x,vcircdata,bp,dp,hp)),
                                (),
                                isDomainFinite=[[True,True],
                                                [True,True],
                                                [True,True],
                                                [True,True],
                                                [True,True]],
                                domain=[[0.,1.],
                                        [0.,1.],
                                        [0.,2.],
                                        [0.,10.],
                                        [0.,2.]],
                                nwalkers=8,
                                nsamples=10000)
    print "Done with sampling ..."
    print numpy.mean(numpy.array(samples),axis=0)
    print numpy.std(numpy.array(samples),axis=0)
    samples= numpy.random.permutation(samples)[0:500]
    #halo
    totalmasssamples= []
    for s in samples:
        totalmasssamples.append(halomass(s))
    totalmasssamples= numpy.array(totalmasssamples)
    print "halo mass: ", numpy.mean(totalmasssamples), numpy.std(totalmasssamples)
    print sixtyeigthinterval(halomass(out),totalmasssamples,quantile=.68)
    #total
    totalmasssamples= []
    for s in samples:
        totalmasssamples.append(totalmass(s))
    totalmasssamples= numpy.array(totalmasssamples)
    print "total mass: ", numpy.mean(totalmasssamples), numpy.std(totalmasssamples)
    print sixtyeigthinterval(totalmass(out),totalmasssamples,quantile=.68)
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(totalmasssamples,bins=16,range=[0.,2.])
    bovy_plot.bovy_end_print('totalmass.png')
    return None
    #disk
    totalmasssamples= []
    for s in samples:
        totalmasssamples.append(diskmass(s))
    totalmasssamples= numpy.array(totalmasssamples)
    print "disk mass: ", numpy.mean(totalmasssamples), numpy.std(totalmasssamples)
    #bulge
    totalmasssamples= []
    for s in samples:
        totalmasssamples.append(bulgemass(s))
    totalmasssamples= numpy.array(totalmasssamples)
    print "bulge mass: ", numpy.mean(totalmasssamples), numpy.std(totalmasssamples)
    return None
Пример #25
0
def plotVelComparisonDF(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    if not options.singlefeh is None:
        if True: #Just to keep indentation the same
            #Set up single feh
            indx= binned.callIndx(options.singlefeh,options.singleafe)
            if numpy.sum(indx) == 0:
                raise IOError("Bin corresponding to singlefeh and singleafe is empty ...")
            allraw= copy.copy(raw)
            raw= copy.copy(binned.data[indx])
            #newerrstuff= []
            #for ii in range(len(binned.data)):
            #    if indx[ii]: newerrstuff.append(errstuff[ii])
            #errstuff= newerrstuff
            print "Using %i data points ..." % (numpy.sum(indx))
            #Bin again
            binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
            fehs, afes= [], []
            for ii in range(len(binned.fehedges)-1):
                for jj in range(len(binned.afeedges)-1):
                    data= binned(binned.feh(ii),binned.afe(jj))
                    if len(data) < options.minndata:
                        continue
                    fehs.append(binned.feh(ii))
                    afes.append(binned.afe(jj))
            nabundancebins= len(fehs)
            fehs= numpy.array(fehs)
            afes= numpy.array(afes)
    if options.singles:
        run_abundance_singles_plotdens(options,args,fehs,afes)
        return None
    normintstuff= setup_normintstuff(options,raw,binned,fehs,afes,allraw)
    ##########POTENTIAL PARAMETERS####################
    potparams1= numpy.array([numpy.log(2.6/8.),230./220.,numpy.log(400./8000.),0.266666666,0.])
    potparams2= numpy.array([numpy.log(2.8/8.),230./220,numpy.log(400./8000.),0.266666666666,0.])
    #potparams2= numpy.array([numpy.log(2.5/8.),1.,numpy.log(400./8000.),0.466666,0.,2.])
    potparams3= numpy.array([numpy.log(2.6/8.),230./220.,
                             numpy.log(400./8000.),0.5333333,0.])
    pop= 0 #assume first population
    #Load savefile
    if not options.init is None:
        #Load initial parameters from file
        savename= options.init
#        spl= savename.split('.')
#        newname= ''
#        for ll in range(len(spl)-1):
#            newname+= spl[ll]
#            if not ll == len(spl)-2: newname+= '.'
#        newname+= '_%i.' % pop
#        newname+= spl[-1]
        savefile= open(savename,'rb')
        try:
            if not _NOTDONEYET:
                params= pickle.load(savefile)
                mlogl= pickle.load(savefile)
            logl= pickle.load(savefile)
        except:
            if savetopickle:
                save_pickles(tmpfiles[jj],None)
                return None
            else:
                return None
        finally:
            savefile.close()
    else:
        raise IOError("base filename not specified ...")
    logl[numpy.isnan(logl)]= -numpy.finfo(numpy.dtype(numpy.float64)).max   
    #Set DF parameters as the maximum at R_d=2.4, f_h=0.4
    #######DF PARAMETER RANGES###########
    lnhr, lnsr, lnsz, rehr, resr, resz= approxFitResult(fehs[0],afes[0],
                                                        relerr=True)
    #if rehr > 0.3: rehr= 0.3 #regularize
    if True: rehr= 0.3 #regularize
    #if resr > 0.3: resr= 0.3
    #if resz > 0.3: resz= 0.3
    if True: resr= 0.3
    if True: resz= 0.3
    hrs= numpy.linspace(-1.85714286,0.9,options.nhrs)
    #hrs= numpy.linspace(lnhr-1.5*rehr,lnhr+1.5*rehr,options.nhrs)
    if _VARYHSZ:
        srs= numpy.linspace(numpy.log(0.5),numpy.log(2.),options.nsrs)#hsz now
    else:
        srs= numpy.linspace(lnsr-0.6*resz,lnsr+0.6*resz,options.nsrs)#USE ESZ
    szs= numpy.linspace(lnsz-0.6*resz,lnsz+0.6*resz,options.nszs)
    #hrs= numpy.linspace(lnhr-0.3,lnhr+0.3,options.nhrs)
    #srs= numpy.linspace(lnsr-0.1,lnsr+0.1,options.nsrs)
    #szs= numpy.linspace(lnsz-0.1,lnsz+0.1,options.nszs)
    dvts= numpy.linspace(-0.35,0.05,options.ndvts)
    #dvts= numpy.linspace(-0.05,0.05,options.ndvts)
    pouts= numpy.linspace(10.**-5.,.5,options.npouts)
    #indx= numpy.unravel_index(numpy.argmax(logl[3,0,0,3,:,:,:,:,:,0,0]),
    indx= numpy.unravel_index(numpy.argmax(logl[3,0,0,4,:,:,:,0]),
                              logl[3,0,0,4,:,:,:,0].shape)
    #tparams= numpy.array([dvts[indx[3]],hrs[indx[0]],
    if _VARYHSZ:
        tparams= numpy.array([0.,hrs[indx[0]],
                              #srs[indx[1]-2.*(indx[1] != 0)],
                              #szs[indx[2]-2.*(indx[2] != 0)],
                              lnsr,
                              szs[indx[2]],
                              numpy.log(8./_REFR0),
                              srs[indx[1]],
                              0.0,#logl[3,0,0,10,indx[0],indx[1],indx[2],2],#pouts[indx[4]],
                              0.,0.,0.,0.,0.])
    else:
        tparams= numpy.array([0.,hrs[indx[0]],
                              #srs[indx[1]-2.*(indx[1] != 0)],
                              #szs[indx[2]-2.*(indx[2] != 0)],
                              srs[indx[1]],
                              szs[indx[2]],
                              numpy.log(8./_REFR0),
                              numpy.log(7./_REFR0),0.,#pouts[indx[4]],
                              0.,0.,0.,0.,0.])
    options.potential=  'dpdiskplhalofixbulgeflatwgasalt'
    tparams= set_potparams(potparams1,tparams,options,1)
    data= []
    zs= []
    velps= numpy.zeros((len(binned.data),options.nv))
    velps[:,:]= numpy.nan
    velps2= numpy.zeros((len(binned.data),options.nv))
    velps2[:,:]= numpy.nan
    velps3= numpy.zeros((len(binned.data),options.nv))
    velps3[:,:]= numpy.nan
    cumulndata= 0
    if options.type.lower() == 'vz':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-180.,180.,options.nv)
            xrange=[-180.,180.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-120.,120.,options.nv)
            xrange=[-120.,120.]
            bins= 26
        xlabel=r'$V_Z\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vr':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-220.,220.,options.nv)
            xrange=[-220.,220.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 26
        xlabel=r'$V_R\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vt':
        if options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        xlabel=r'$V_T\ [\mathrm{km\,s}^{-1}]$'
    thisdata= binned(fehs[pop],afes[pop])
    velps[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs,normintstuff=normintstuff)
    alts= True
    if alts:
        indx= numpy.unravel_index(numpy.argmax(logl[4,0,0,4,:,:,:,0]),
                                  logl[4,0,0,4,:,:,:,0].shape)
        #tparams= numpy.array([dvts[indx[3]],hrs[indx[0]],
        if not _VARYHSZ:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-1.*(indx[1] != 0)],
                                  #szs[indx[2]-1.*(indx[2] != 0)],
                                  srs[indx[1]],
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  numpy.log(7./_REFR0),0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.,0.])
        else:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-1.*(indx[1] != 0)],
                                  #szs[indx[2]-1.*(indx[2] != 0)],
                                  lnsr,
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  srs[indx[1]],0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.,0.])
        #options.potential= 'dpdiskplhalodarkdiskfixbulgeflatwgasalt'
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        tparams= set_potparams(potparams2,tparams,options,1)
        print "Working on model 2 ..."
        velps2[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
        indx= numpy.unravel_index(numpy.argmax(logl[3,0,0,8,:,:,:,0]),
                                  logl[3,0,0,8,:,:,:,0].shape)
        #tparams= numpy.array([dvts[indx[3]],hrs[indx[0]],
        if _VARYHSZ:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-2.*(indx[1] != 0)],
                                  #szs[indx[2]-2.*(indx[2] != 0)],
                                  lnsr,
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  srs[indx[1]],0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.])
        else:
            tparams= numpy.array([0.,hrs[indx[0]],
                                  #srs[indx[1]-2.*(indx[1] != 0)],
                                  #szs[indx[2]-2.*(indx[2] != 0)],
                                  srs[indx[1]],
                                  szs[indx[2]],
                                  numpy.log(8./_REFR0),
                                  numpy.log(7./_REFR0),0.,#pouts[indx[4]],
                                  0.,0.,0.,0.,0.])
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        tparams= set_potparams(potparams3,tparams,options,1)
        print "Working on model 3 ..."
        velps3[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
    #Also add the correct data
    vo= get_vo(tparams,options,1)
    ro= get_ro(tparams,options)
    if 'vr' in options.type.lower() or 'vt' in options.type.lower():
        R= ((ro*_REFR0-thisdata.xc)**2.+thisdata.yc**2.)**(0.5)
        cosphi= (_REFR0*ro-thisdata.xc)/R
        sinphi= thisdata.yc/R
        vR= -(thisdata.vxc-_VRSUN)*cosphi+(thisdata.vyc+_VTSUN)*sinphi
        vT= (thisdata.vxc-_VRSUN)*sinphi+(thisdata.vyc+_VTSUN)*cosphi
    if options.type.lower() == 'vz':
        data.extend(thisdata.vzc+_VZSUN)
    elif options.type.lower() == 'vr':
        data.extend(vR)
    elif options.type.lower() == 'vt':
        data.extend(vT)
    zs.extend(thisdata.zc)
    cumulndata+= len(thisdata)
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data,bins=26,normed=True,color='k',
                        histtype='step',
                        xrange=xrange,xlabel=xlabel)
    plotp= numpy.nansum(velps,axis=0)/cumulndata
    print numpy.sum(plotp)*(vs[1]-vs[0])
    bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
    if alts:
        plotp= numpy.nansum(velps2,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
        plotp= numpy.nansum(velps3,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
    bovy_plot.bovy_text(r'$\mathrm{full\ subsample}$'
                        +'\n'+
                        '$%i \ \ \mathrm{stars}$' % 
                        len(data),top_right=True,
                        size=_legendsize)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_all.'+options.ext)
    if options.all: return None
    #Plot zranges
    zranges= numpy.array([0.5,1.,1.5,2.,3.,4.])
    nzranges= len(zranges)-1
    zs= numpy.array(zs)
    data= numpy.array(data)
    sigzsd= numpy.empty(nzranges)
    esigzsd= numpy.empty(nzranges)
    sigzs1= numpy.empty(nzranges)
    sigzs2= numpy.empty(nzranges)
    sigzs3= numpy.empty(nzranges)
    for ii in range(nzranges):
        indx= (numpy.fabs(zs) >= zranges[ii])*(numpy.fabs(zs) < zranges[ii+1])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(data[indx],bins=26,normed=True,color='k',
                            histtype='step',
                            xrange=xrange,xlabel=xlabel)
        sigzsd[ii]= numpy.std(data[indx][(numpy.fabs(data[indx]) < 100.)])
        esigzsd[ii]= sigzsd[ii]/numpy.sqrt(float(len(data[indx][(numpy.fabs(data[indx]) < 100.)])))
        plotp= numpy.nansum(velps[indx,:],axis=0)/numpy.sum(indx)
        sigzs1[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
        bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
        if alts:
            plotp= numpy.nansum(velps2[indx,:],axis=0)/numpy.sum(indx)
            sigzs2[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
            plotp= numpy.nansum(velps3[indx,:],axis=0)/numpy.sum(indx)
            sigzs3[ii]= numpy.sqrt(numpy.sum(vs**2.*plotp)/numpy.sum(plotp)-(numpy.sum(vs*plotp)/numpy.sum(plotp))**2.)
            bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
        bovy_plot.bovy_text(r'$ %i\ \mathrm{pc} \leq |Z| < %i\ \mathrm{pc}$' % (int(1000*zranges[ii]),int(1000*zranges[ii+1]))
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            (numpy.sum(indx)),top_right=True,
                            size=_legendsize)
        bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_z%.1f_z%.1f.' % (zranges[ii],zranges[ii+1])+options.ext)
    #Plot velocity dispersion as a function of |Z|
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzsd,
                        'ko',
                        xlabel=r'$|Z|\ (\mathrm{kpc})$',
                        ylabel=r'$\sigma_z\ (\mathrm{km\,s}^{-1})$',
                        xrange=[0.,4.],
                        yrange=[0.,60.])
    pyplot.errorbar(((numpy.roll(zranges,-1)+zranges)/2.)[:5],sigzsd,
                    yerr=esigzsd,
                    marker='o',color='k',linestyle='none')
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzs1,
                        'r+',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzs2,
                        'cx',overplot=True,ms=10.)
    bovy_plot.bovy_plot((((numpy.roll(zranges,-1)+zranges)/2.)[:5]),sigzs3,
                        'gd',overplot=True,ms=10.)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.type+'dist_szvsz.'+options.ext)
    return None
Пример #26
0
     else:
         for ii in range(options.nvlos):
             print ii
             pvlosalljhk[ii] = pvlosplate(params, vlos[ii],
                                          alljhkdata, df, options,
                                          logpiso, logpisodwarf,
                                          iso)
     pvlosalljhk -= logsumexp(pvlosalljhk)
     pvlosalljhk = numpy.exp(pvlosalljhk)
 #Plot data
 bovy_plot.bovy_print()
 hist, xvec, p = bovy_plot.bovy_hist(
     thesedata['VHELIO'],
     range=[-200., 200.],
     bins=31,
     histtype='step',
     color='k',
     xlabel=
     r'$\mathrm{heliocentric}\ V_{\mathrm{los}}\ [\mathrm{km\ s}^{-1}]$'
 )
 #Normalize prediction
 data_int = numpy.sum(hist) * (xvec[1] - xvec[0])
 pvlos *= data_int / numpy.sum(pvlos) / (vlos[1] - vlos[0])
 bovy_plot.bovy_plot(vlos,
                     pvlos,
                     '-',
                     color='0.6',
                     overplot=True,
                     lw=3.)
 if _PLOTZERO:
     pvloszero *= data_int / numpy.sum(pvloszero) / (vlos[1] -
Пример #27
0
 #Now plot the selection function in real-space
 bovy_plot.bovy_print(fig_width=6.)
 apo.plot_selfunc_xy(vmax=15.)
 bovy_plot.bovy_end_print(basefilename+'sfxy.%s' % _EXT)
 bovy_plot.bovy_print(fig_width=6.)
 apo.plot_selfunc_xy(type='rz',vmax=15.)
 bovy_plot.bovy_end_print(basefilename+'sfrz.%s' % _EXT)
 #Now calculate the KS probabilities and plot the histogram
 ksshort= apo.check_consistency('short','short')
 ksmedium= apo.check_consistency('medium','medium')
 kslong= apo.check_consistency('long','long')
 xrange= [0.,1.]
 bovy_plot.bovy_print()
 bovy_plot.bovy_hist(ksshort,range=xrange,bins=21,
                     xlabel=r'$\mathrm{KS\ probability}$',#\ that\ the\ spectroscopic\ sample}$'+'\n'+r'$\mathrm{was\ drawn\ from\ the\ photometric\ sample}$'+'\n'+r'$\times\ \mathrm{the\ model\ selection\ function}$',
                     ylabel=r'$\mathrm{distribution}$',
                     yrange=[0.,4.],
                     ec='k',histtype='step',normed=True)
 bovy_plot.bovy_hist(ksmedium,range=xrange,normed=True,
                     bins=11,overplot=True,
                     ec='k',histtype='step',
                     ls='dashed')
 bovy_plot.bovy_hist(kslong,range=xrange,normed=True,
                     bins=11,overplot=True,
                     ec='k',histtype='step',
                     ls='dashdot')
 #Add proxies for legend
 from matplotlib.lines import Line2D
 lineshort= Line2D([0.],[0.],linestyle='-',color='k')
 linemedium= Line2D([0.],[0.],linestyle='--',color='k')
 linelong= Line2D([0.],[0.],linestyle='-.',color='k')
def main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit Combination Pal5 and GD1 to MW Potential Script Function.

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

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

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

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

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

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

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

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

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

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

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

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

    plt.figure()
    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=15.0,
        ytick_labelsize=15.0,
    )
    su.plot_mcmc_c(
        s,
        True,
        cs,
        bf_params,
        savefig=fpath + "mwpot14varyc-bf-combo_pal5_gd1-dependence.pdf",
    )
    if save_figures:
        plt.savefig(
            os.path.join(
                os.getenv("PAPERSDIR"),
                "2016-mwhalo-shape",
                "mwpot14-varyc-wp5g1.pdf",
            ),
            bbox_inches="tight",
        )

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

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

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

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

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

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

        file.write("\nMass Constraints:")

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

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

    bovy_plot.scatterplot(
        hmass,
        s[-1, ::skip],
        "k,",
        onedhists=True,
        bins=31,
        xrange=[0.5, 1.5],
        yrange=[0.5, 1.5],
        xlabel=r"$M_{\mathrm{halo}} (r<20\,\mathrm{kpc})\,(M_\odot)$",
        ylabel=r"$c/a$",
    )
    plt.savefig(fpath + "scatterplot.pdf")
Пример #29
0
def plotCompareData(sample,savename,plotname):
    locs= ['highb','outdisk','meddisk','indisk']
    indices= [highbIndx,outDiskIndx,betwDiskIndx,inDiskIndx]
    data_indices= [data_highbIndx,data_outDiskIndx,
                   data_betwDiskIndx,data_inDiskIndx]
    # Full prediction for numbers
    Xs,pd= compareDataModel.predict_spacedist(bf_brexp,
                                              numpy.array(locations),
                                              copy.deepcopy(effsel_mar),
                                              distmods,
                                              type='tribrokenexpflare',coord='dm')
    for loc, index, data_index in zip(locs,indices,data_indices):
        bovy_plot.bovy_print(axes_labelsize=20,text_fontsize=20,
                             xtick_labelsize=20,ytick_labelsize=20)
        # High |b|
        # Marshall is fiducial
        Xs,pdt= compareDataModel.predict_spacedist(bf_brexp,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel_mar)[index],
                                                   distmods,type='tribrokenexpflare',
                                                   coord='dm')
        if (sample.lower() == 'solar' and \
                (loc.lower() == 'outdisk' or loc.lower() == 'highb')) \
                or (sample.lower() == 'highfeh' and loc.lower() == 'highb'):
            yrange=[0.,
                    1.6*numpy.amax(pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]))]
        else:
            yrange=[0.,
                    1.4*numpy.amax(pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]))]
        bovy_plot.bovy_hist(ldata['RC_DM_H'][data_index],
                            histtype='stepfilled',
                            normed=True,
                            lw=_LW,
                            range=[7.,15.5],
                            bins=round(numpy.sqrt(numpy.sum(data_index))*2.),
                            yrange=yrange,
                            ec='k',fc='0.75',
                            xlabel=r'$\mu$')
        line_mar= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                      color='r',
                                      lw=2.*_LW,overplot=True,zorder=12)
        bovy_plot.bovy_text(r'$%i\%% = %i / %i\ \mathrm{stars}$' \
                                % (int(round(float(numpy.sum(data_index))/len(ldata)*100.)),
                                   numpy.sum(data_index),
                                   len(ldata))
                            +'\n'+r'$%i\%% = %i / %i\ \mathrm{predicted}$' \
                                % (int(round(numpy.sum(pdt)/numpy.sum(pd)*100.)),
                                   numpy.sum(pdt)/numpy.sum(pd)*len(ldata),len(ldata)),
                            top_left=True,size=16.)
        # Green
        Xs,pdt= compareDataModel.predict_spacedist(bf_brexp_g15,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel)[index],
                                                   distmods,type='tribrokenexpflare',
                                                   coord='dm')
        line_g15= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                      color='b',
                                      lw=_LW,overplot=True,zorder=13)
        # Drimmel
        Xs,pdt= compareDataModel.predict_spacedist(bf_brexp_drim,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel_drim)[index],
                                                   distmods,type='tribrokenexpflare',
                                                   coord='dm')
        line_drim= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                       color='gold',
                                       lw=_LW,overplot=True,zorder=12)
        # Sale
        Xs,pdt= compareDataModel.predict_spacedist(bf_brexp_sale,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel_sale)[index],
                                                   distmods,type='tribrokenexpflare',
                                                   coord='dm')
        line_sale= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                       color='c',
                                       lw=_LW,overplot=True,zorder=12)
        # Zero
        Xs,pdt= compareDataModel.predict_spacedist(bf_brexp_zero,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel_zero)[index],
                                                   distmods,type='tribrokenexpflare',
                                                   coord='dm')
        line_zero= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                       color='k',
                                       ls='-',lw=_LW,overplot=True,zorder=10)
        # Marshall + exp
        Xs,pdt= compareDataModel.predict_spacedist(bf_exp,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel_mar)[index],
                                                   distmods,type='expplusconst',
                                                   coord='dm')
        line_exp= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                      color='r',
                                      lw=2*_LW,overplot=True,zorder=10,ls=':')
        # Marshall + twoexp
        Xs,pdt= compareDataModel.predict_spacedist(bf_twoexp,
                                                   numpy.array(locations)[index],
                                                   copy.deepcopy(effsel_mar)[index],
                                                   distmods,type='tribrokentwoexp',
                                                   coord='dm')
        line_twoexp= bovy_plot.bovy_plot(Xs,pdt/numpy.sum(pdt)/(Xs[1]-Xs[0]),
                                         color='r',
                                         lw=2*_LW,overplot=True,zorder=11,
                                         ls='--')
        if sample.lower() == 'lowlow' or sample.lower() == 'highalpha':
            if loc.lower() == 'highb':
                pyplot.annotate(r'$|b| > 10^\circ$',
                                (0.5,1.085),xycoords='axes fraction',
                                horizontalalignment='center',
                                verticalalignment='top',
                                size=20.)
            elif loc.lower() == 'indisk':
                pyplot.annotate(r'$l < 70^\circ, |b| \leq 10^\circ$',
                                (0.5,1.085),xycoords='axes fraction',
                                horizontalalignment='center',
                                verticalalignment='top',
                                size=20.)
            elif loc.lower() == 'meddisk':
                pyplot.annotate(r'$70^\circ \leq l \leq 140^\circ, |b| \leq 10^\circ$',
                                (0.5,1.085),xycoords='axes fraction',
                                horizontalalignment='center',
                                verticalalignment='top',
                                size=20.)
            elif loc.lower() == 'outdisk':
                pyplot.annotate(r'$140^\circ < l < 250^\circ, |b| \leq 10^\circ$',
                                (0.5,1.085),xycoords='axes fraction',
                                horizontalalignment='center',
                                verticalalignment='top',
                                size=20.)
            # Legend
            if loc.lower() == 'meddisk':
                pyplot.legend((line_mar[0],line_exp[0],line_twoexp[0]),
                              (r'$\mathrm{Marshall\ et\ al.\ (2006)}$'
                               +'\n'+r'$\mathrm{broken\ exp.\ w/\ flare}$',
                               r'$\mathrm{single\ exp.}$',
                               r'$\mathrm{broken\ exp.\ w/\ 2}\ h_Z$'),
                              loc='lower right',bbox_to_anchor=(.66,.42),
                              numpoints=8,
                              prop={'size':14},
                              frameon=False)
            elif loc.lower() == 'outdisk':
                pyplot.legend((line_g15[0],line_sale[0],line_drim[0],
                               line_zero[0]),
                              (r'$\mathrm{Green\ et\ al.\ (2015)}$',
                               r'$\mathrm{Sale\ et\ al.\ (2014)}$',
                               r'$\mathrm{Drimmel\ et\ al.\ (2003)}$',
                               r'$\mathrm{zero\ extinction}$'),
                              loc='lower right',bbox_to_anchor=(.66,.42),
                              numpoints=8,
                              prop={'size':14},
                              frameon=False)
        if loc.lower() == 'highb':
            if sample.lower() == 'lowlow':
                bovy_plot.bovy_text(r'$\mathrm{low\ [Fe/H]}$',
                                    top_right=True,size=18.)
            elif sample.lower() == 'solar':
                bovy_plot.bovy_text(r'$\mathrm{solar}$',
                                    top_right=True,size=18.)
            elif sample.lower() == 'highfeh':
                bovy_plot.bovy_text(r'$\mathrm{high\ [Fe/H]}$',
                                    top_right=True,size=18.)
            elif sample.lower() == 'highalpha':
                bovy_plot.bovy_text(r'$\mathrm{high}\ [\alpha/\mathrm{Fe]}$',
                                    top_right=True,size=18.)
        bovy_plot.bovy_end_print(plotname.replace('LOC',loc))
    return None
Пример #30
0
def plotVelComparisonDFMulti(options,args):
    #Read data etc.
    print "Reading the data ..."
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    gafes, gfehs, left_legend= getMultiComparisonBins(options)
    if options.usemedianpotential:
        potparams= get_median_potential(options,nabundancebins)
        print "Median potential parameters: ", potparams
    M= len(gfehs)
    #Check whether fits exist, if not, pop
    removeBins= numpy.ones(M,dtype='bool')
    for jj in range(M):
        #Find pop corresponding to this bin
        pop= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
        #Load savefile
        if not options.init is None:
            #Load initial parameters from file
            savename= options.init
            spl= savename.split('.')
            newname= ''
            for ll in range(len(spl)-1):
                newname+= spl[ll]
                if not ll == len(spl)-2: newname+= '.'
            newname+= '_%i.' % pop
            newname+= spl[-1]
            if not os.path.exists(newname):
                removeBins[jj]= False
        else:
            raise IOError("base filename not specified ...")
    if numpy.sum(removeBins) == 0:
        raise IOError("None of the group bins have been fit ...")
    elif numpy.sum(removeBins) < M:
        #Some bins have not been fit yet, and have to be remove
        gfehs= list((numpy.array(gfehs))[removeBins])
        gafes= list((numpy.array(gafes))[removeBins])
        print "Only using %i bins out of %i ..." % (numpy.sum(removeBins),M)
        M= len(gfehs)
    data= []
    zs= []
    velps= numpy.zeros((len(binned.data),options.nv))
    velps[:,:]= numpy.nan
    velps2= numpy.zeros((len(binned.data),options.nv))
    velps2[:,:]= numpy.nan
    velps3= numpy.zeros((len(binned.data),options.nv))
    velps3[:,:]= numpy.nan
    cumulndata= 0
    if options.type.lower() == 'vz':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-180.,180.,options.nv)
            xrange=[-180.,180.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-120.,120.,options.nv)
            xrange=[-120.,120.]
            bins= 26
        xlabel=r'$V_Z\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vr':
        if options.group == 'aenhanced':
            vs= numpy.linspace(-220.,220.,options.nv)
            xrange=[-220.,220.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(-150.,150.,options.nv)
            xrange=[-150.,150.]
            bins= 26
        xlabel=r'$V_R\ [\mathrm{km\,s}^{-1}]$'
    elif options.type.lower() == 'vt':
        if options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        else: # options.group == 'aenhanced':
            vs= numpy.linspace(0.01,350.,options.nv)
            xrange=[0.,350.]
            bins= 39
        xlabel=r'$V_T\ [\mathrm{km\,s}^{-1}]$'
    for jj in range(M):
        print "Working on group %i / %i ..." % (jj+1,M)
        #Find pop corresponding to this bin
        pop= numpy.argmin((gfehs[jj]-fehs)**2./0.1+(gafes[jj]-afes)**2./0.0025)
        #Load savefile
        if not options.init is None:
            #Load initial parameters from file
            savename= options.init
            spl= savename.split('.')
            newname= ''
            for ll in range(len(spl)-1):
                newname+= spl[ll]
                if not ll == len(spl)-2: newname+= '.'
            newname+= '_%i.' % pop
            newname+= spl[-1]
            savefile= open(newname,'rb')
            tparams= pickle.load(savefile)
            savefile.close()
        else:
            raise IOError("base filename not specified ...")
        if options.usemedianpotential:
            tparams= set_potparams(potparams,tparams,options,1)
        print tparams
        thisdata= binned(fehs[pop],afes[pop])
        velps[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
        alts= True
        if alts:
            if not options.usemedianpotential:
                potparams= get_potparams(tparams,options,1)
            if options.potential.lower() == 'flatlog':
                tparams= set_potparams([potparams[0]*1.05,potparams[1]],
                                       tparams,options,1)
                velps2[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
                tparams= set_potparams([potparams[0]*0.95,potparams[1]],
                                       tparams,options,1)
                velps3[cumulndata:cumulndata+len(thisdata),:]= calc_model(tparams,options,thisdata,vs)
        #Also add the correct data
        vo= get_vo(tparams,options,1)
        ro= get_ro(tparams,options)
        if 'vr' in options.type.lower() or 'vt' in options.type.lower():
            R= ((ro*_REFR0-thisdata.xc)**2.+thisdata.yc**2.)**(0.5)
            cosphi= (_REFR0*ro-thisdata.xc)/R
            sinphi= thisdata.yc/R
            vR= -(thisdata.vxc-_VRSUN)*cosphi+(thisdata.vyc+_VTSUN)*sinphi
            vT= (thisdata.vxc-_VRSUN)*sinphi+(thisdata.vyc+_VTSUN)*cosphi
        if options.type.lower() == 'vz':
            data.extend(thisdata.vzc+_VZSUN)
        elif options.type.lower() == 'vr':
            data.extend(vR)
        elif options.type.lower() == 'vt':
            data.extend(vT)
        zs.extend(thisdata.zc)
        cumulndata+= len(thisdata)
    bovy_plot.bovy_print()
    bovy_plot.bovy_hist(data,bins=26,normed=True,color='k',
                        histtype='step',
                        xrange=xrange,xlabel=xlabel)
    plotp= numpy.nansum(velps,axis=0)/cumulndata
    print numpy.sum(plotp)*(vs[1]-vs[0])
    bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
    if alts:
        plotp= numpy.nansum(velps2,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
        plotp= numpy.nansum(velps3,axis=0)/cumulndata
        bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
    if not left_legend is None:
        bovy_plot.bovy_text(left_legend,top_left=True,size=_legendsize)
    bovy_plot.bovy_text(r'$\mathrm{full\ subsample}$'
                        +'\n'+
                        '$%i \ \ \mathrm{stars}$' % 
                        len(data),top_right=True,
                        size=_legendsize)
    bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_all.'+options.ext)
    if options.all: return None
    #Plot zranges
    zranges= [0.5,1.,1.5,2.,3.,4.]
    nzranges= len(zranges)-1
    zs= numpy.array(zs)
    data= numpy.array(data)
    for ii in range(nzranges):
        indx= (numpy.fabs(zs) >= zranges[ii])*(numpy.fabs(zs) < zranges[ii+1])
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(data[indx],bins=26,normed=True,color='k',
                            histtype='step',
                            xrange=xrange,xlabel=xlabel)
        plotp= numpy.nansum(velps[indx,:],axis=0)/numpy.sum(indx)
        bovy_plot.bovy_plot(vs,plotp,'k-',overplot=True)
        if alts:
            plotp= numpy.nansum(velps2[indx,:],axis=0)/numpy.sum(indx)
            bovy_plot.bovy_plot(vs,plotp,'k--',overplot=True)
            plotp= numpy.nansum(velps3[indx,:],axis=0)/numpy.sum(indx)
            bovy_plot.bovy_plot(vs,plotp,'k:',overplot=True)
        bovy_plot.bovy_text(r'$ %i\ \mathrm{pc} \leq |Z| < %i\ \mathrm{pc}$' % (int(1000*zranges[ii]),int(1000*zranges[ii+1]))
                            +'\n'+
                            '$%i \ \ \mathrm{stars}$' % 
                            (numpy.sum(indx)),top_right=True,
                            size=_legendsize)
        bovy_plot.bovy_end_print(args[0]+'model_data_g_'+options.group+'_'+options.type+'dist_z%.1f_z%.1f.' % (zranges[ii],zranges[ii+1])+options.ext)
    return None
Пример #31
0
def verysimplenfwfit(plotfilename,wcprior=False,wmassprior=False):
    #Fit
    p= optimize.fmin_powell(chi2,[-0.5,0.7],args=(wcprior,wmassprior))
    print mvir(p), conc(p)*numpy.exp(p[1])*8.
    vo= numpy.exp(p[0])
    a= numpy.exp(p[1])
    nfw= potential.NFWPotential(normalize=1.,a=a)
    rs= numpy.linspace(0.01,350.,1001)
    masses= numpy.array([nfw.mass(r/8.) for r in rs])
    bovy_plot.bovy_print(fig_width=6.)
    bovy_plot.bovy_plot(rs,
                        masses*bovy_conversion.mass_in_1010msol(220.*vo,8.)/100.,
                        'k-',loglog=True,
                        xlabel=r'$R\,(\mathrm{kpc})$',
                        ylabel=r'$M(<R)\,(10^{12}\,M_\odot)$',
                        yrange=[0.01,1.2],
                        xrange=[3.,400.])
    if _USE_ALL_XUE:
        plotx= [10.]
        plotx.extend(list(_XUER))
        ploty= [4.5/100.]
        ploty.extend(list(_XUEMASS/100.))
        plotyerr= [1.5/100]
        plotyerr.extend(list(_XUEMASS_ERR/100.))
        pyplot.errorbar(plotx,ploty,yerr=plotyerr,marker='o',ls='none',
                        color='k')
    else:
        pyplot.errorbar([10.,60.],[4.5/100.,3.5/10.],yerr=[1.5/100.,0.7/10.],
                        marker='o',ls='none',color='k')
    pyplot.errorbar([150.],[7.5/10.],[2.5/10.],marker='None',color='k')
    dx= .5
    arr= FancyArrowPatch(posA=(7.,4./100.),posB=(numpy.exp(numpy.log(7.)+dx),numpy.exp(numpy.log(4./100.)+1.5*dx)),arrowstyle='->',connectionstyle='arc3,rad=%4.2f' % (0.),shrinkA=2.0, shrinkB=2.0,mutation_scale=20.0, mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    #Sample MCMC to get virial mass uncertainty
    samples= bovy_mcmc.markovpy(p,
                                0.05,
                                lnlike,
                                (wcprior,wmassprior),
                                isDomainFinite=[[False,False],[False,False]],
                                domain=[[0.,0.],[0.,0.]],
                                nsamples=10000,
                                nwalkers=6)
    mvirs= numpy.array([mvir(x) for x in samples])
    concs= numpy.array([conc(x) for x in samples])
    indx= True-numpy.isnan(mvirs)
    mvirs= mvirs[indx]
    indx= True-numpy.isnan(concs)
    concs= concs[indx]
    rvirs= concs[indx]*numpy.array([numpy.exp(x[1]) for x in samples])*8.
    bovy_plot.bovy_text(r'$M_{\mathrm{vir}} = %.2f\pm%.2f\times10^{12}\,M_\odot$' % (numpy.median(mvirs),1.4826*numpy.median(numpy.fabs(mvirs-numpy.median(mvirs)))) +'\n'+
                        r'$r_{\mathrm{vir}} = %i\pm%i\,\mathrm{kpc}$' % (numpy.median(rvirs),1.4826*numpy.median(numpy.fabs(rvirs-numpy.median(rvirs))))+'\n'+
                        r'$c = %.1f\pm%.1f$' % (numpy.median(concs),1.4826*numpy.median(numpy.fabs(concs-numpy.median(concs)))),
                        top_left=True,size=18.)
    #Create inset with PDF
    insetAxes= pyplot.axes([0.55,0.22,0.3,0.3])
    pyplot.sca(insetAxes)
    bovy_plot.bovy_hist(mvirs,range=[0.,3.],bins=51,histtype='step',
                        color='k',
                        normed=True,
                        overplot=True)
    insetAxes.set_xlim(0.,3.)
    insetAxes.set_ylim(0.,1.49)
    insetAxes.set_xlabel(r'$M_{\mathrm{vir}}\,(10^{12}\,M_\odot)$')
    bovy_plot._add_ticks()
    bovy_plot.bovy_end_print(plotfilename)
Пример #32
0
def calc_es():
    savefilename= 'myes.sav'
    if os.path.exists(savefilename):
        savefile= open(savefilename,'rb')
        mye= pickle.load(savefile)
        e= pickle.load(savefile)
        savefile.close()
    else:
       #Read data
        dialect= csv.excel
        dialect.skipinitialspace=True
        reader= csv.reader(open('../data/Dierickx-etal-tab2.txt','r'),delimiter=' ',dialect=dialect)
        vxvs= []
        es= []
        vphis= []
        vxs= []
        vys= []
        vzs= []
        ls= []
        for row in reader:
            thisra= float(row[3])
            thisdec= float(row[4])
            thisd= float(row[17])/1000.
            thispmra= float(row[13])
            thispmdec= float(row[15])
            thisvlos= float(row[11])
            thise= float(row[26])
            vxvs.append([thisra,thisdec,thisd,thispmra,thispmdec,thisvlos])
            es.append(thise)
            vphis.append(float(row[25]))
            vxs.append(float(row[19]))
            vys.append(float(row[21]))
            vzs.append(float(row[23]))
            ls.append(float(row[5]))
        vxvv= nu.array(vxvs)
        e= nu.array(es)
        vphi= nu.array(vphis)
        vx= nu.array(vxs)
        vy= nu.array(vys)
        vz= nu.array(vzs)
        l= nu.array(ls)

        #Define potential
        lp= LogarithmicHaloPotential(normalize=1.)
        mp= MiyamotoNagaiPotential(a=0.5,b=0.0375,amp=1.,normalize=.6)
        np= NFWPotential(a=4.5,normalize=.35)
        hp= HernquistPotential(a=0.6/8,normalize=0.05)
        ts= nu.linspace(0.,20.,10000)
        
        mye= nu.zeros(len(e))
        for ii in range(len(e)):
           #Integrate the orbit
            o= Orbit(vxvv[ii,:],radec=True,vo=220.,ro=8.)
            o.integrate(ts,lp)
            mye[ii]= o.e()
            

        #Save
        savefile= open(savefilename,'wb')
        pickle.dump(mye,savefile)
        pickle.dump(e,savefile)
        savefile.close()

    #plot
    plot.bovy_print()
    plot.bovy_plot(nu.array([0.,1.]),nu.array([0.,1.]),'k-',
                   xlabel=r'$\mathrm{Dierickx\ et\ al.}\ e$',
                   ylabel=r'$\mathrm{galpy}\ e$')
    plot.bovy_plot(e,mye,'k,',overplot=True)
    plot.bovy_end_print('myee.png')

    plot.bovy_print()
    plot.bovy_hist(e,bins=30,xlabel=r'$\mathrm{Dierickx\ et\ al.}\ e$')
    plot.bovy_end_print('ehist.png')

    plot.bovy_print()
    plot.bovy_hist(mye,bins=30,xlabel=r'$\mathrm{galpy}\ e$')
    plot.bovy_end_print('myehist.png')
Пример #33
0
def plot_distancedist(basesavefilename):
    #First read the sample
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Histogram
    bovy_plot.bovy_print(fig_width=6.)
    bovy_plot.bovy_hist(data['RC_DIST'],
                        histtype='step',
                        color='k',
                        lw=1.5,
                        bins=51,
                        xrange=[0.,10.],
                        xlabel=r'$\mathrm{distance}\,(\mathrm{kpc})$',
                        ylabel=r'$\mathrm{Number\ of\ stars}$',zorder=10)
    ax= pyplot.gca()
    ax2= ax.twinx()
    pyplot.sca(ax2)
    bovy_plot.bovy_plot(sorted(data['RC_DIST']),
                        numpy.linspace(1./len(data),1.,len(data)),
                        'k-',
                        overplot=True)
    ax2.set_xlim(0.,10.)
    ax2.set_ylim(0.,1.)
    bovy_plot._add_ticks()
    ax2.set_ylabel(r'$\mathrm{cumulative\ distribution}$')
    bovy_plot.bovy_end_print(basesavefilename+'_hist.'+_EXT)
    #RZ
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['RC_GALR'],data['RC_GALZ'],
                        'k.',ms=2.,
                        xrange=[0.,16.],
                        yrange=[-3.,3.],
                        xlabel=r'$R\,(\mathrm{kpc})$',
                        ylabel=r'$Z\,(\mathrm{kpc})$',
                        onedhists=True)
    xarr, dx=1.5, -1.
    from matplotlib.patches import FancyArrowPatch
    _legendsize= 16
    arr= FancyArrowPatch(posA=(xarr+0.05,0.),
                         posB=(xarr+dx*10./8.,0.),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (0.), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    bovy_plot.bovy_text(xarr+7.*dx/8.,-0.45,r'$\mathrm{GC}$',
                        size=_legendsize)
    arr= FancyArrowPatch(posA=(1.5,-0.05),
                         posB=(1.5,.75),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (0.), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                                 mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    bovy_plot.bovy_text(1.59,0.2,r'$\mathrm{NGP}$',
                        size=_legendsize)
    bovy_plot.bovy_end_print(basesavefilename+'_RZ.'+_EXT)
    #XY
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data['RC_GALR']*numpy.cos(data['RC_GALPHI']),
                        data['RC_GALR']*numpy.sin(data['RC_GALPHI']),
                        'k.',
                        xrange=[0.,16.],
                        yrange=[5.,-5.],
                        xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$',
                        ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$',
                        onedhists=True,ms=2.)
    xarr, dx= 2.2, -2.
    arr= FancyArrowPatch(posA=(xarr,0.),
                         posB=(xarr+dx,0.),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (0.), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax = pyplot.gca()
    ax.add_patch(arr)
    bovy_plot.bovy_text(xarr+7.*dx/8.,-0.25,r'$\mathrm{GC}$',
                        size=_legendsize)
    xcen, ycen, dr, t= -2., 0., 4., 14.*numpy.pi/180.
    arr= FancyArrowPatch(posA=(xcen+dr*numpy.cos(t),
                               ycen+dr*numpy.sin(t)),
                         posB=(xcen+dr*numpy.cos(-t),
                               ycen+dr*numpy.sin(-t)),
                         arrowstyle='<-', 
                         connectionstyle='arc3,rad=%4.2f' % (2.*t), 
                         shrinkA=2.0, shrinkB=2.0,
                         mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_end_print(basesavefilename+'_XY.'+_EXT)
Пример #34
0
def plot_mapflarepdf(savename,plotname):
    # Load the samples
    with open('../mapfits/tribrokenexpflare.sav','rb') as savefile:
        bf= numpy.array(pickle.load(savefile))
        samples= numpy.array(pickle.load(savefile))
    maps= define_rcsample.MAPs()
    # Loop through the low-alpha MAPs and compute the XD decomposition
    if 'lowalpha' in savename:
        plotmaps= [9,16,23,29,36,43,50,57,64,71]
    else:
        plotmaps= [19,26,32,39,45]
    if not os.path.exists(savename):
        ngauss= 2
        allxamp= numpy.empty((len(plotmaps),ngauss))
        allxmean= numpy.empty((len(plotmaps),ngauss,1))
        allxcovar= numpy.empty((len(plotmaps),ngauss,1,1))
        cnt= 0
        for ii, map in enumerate(maps.map()):
            if not ii in plotmaps: continue
            print ii
            # Fit PDFs with XD
            xamp= numpy.array([0.45,0.5])
            xmean= numpy.array([numpy.mean(samples[ii,4])
                                +numpy.random.normal()*numpy.std(samples[ii,4]),
                                numpy.mean(samples[ii,4])
                                +numpy.random.normal()*numpy.std(samples[ii,4])])[:,numpy.newaxis]
            xcovar= numpy.reshape(numpy.tile(numpy.var(samples[ii,4]),(2,1)),
                                  (2,1,1))
            XD.extreme_deconvolution(samples[ii,4][:,numpy.newaxis],
                                     numpy.zeros((len(samples[ii,4]),1)),
                                     xamp,xmean,xcovar)
            allxamp[cnt]= xamp
            allxmean[cnt]= xmean
            allxcovar[cnt]= xcovar
            cnt+= 1
        save_pickles(savename,allxamp,allxmean,allxcovar)
    else:
        with open(savename,'rb') as savefile:
            allxamp= pickle.load(savefile)
            allxmean= pickle.load(savefile)
            allxcovar= pickle.load(savefile)
    # Now plot
    cmap= cm.coolwarm
    xrange= [-0.37,0.25]
    if 'lowalpha' in savename:
#        xrange= [-0.4,0.2]
        yrange= [0.,30.]
        combDiv= 2.
        colorFunc= lambda x: cmap((x+0.6)*0.95/0.9+0.05)
    else:
#        xrange= [-0.3,0.3]
        yrange= [0.,13.5]
        colorFunc= lambda x: cmap((x+0.5)*0.95/0.5+0.05)
        combDiv= 1.5
    overplot= False
    plotXDFit= True
    cnt= 0
    bovy_plot.bovy_print(axes_labelsize=18,text_fontsize=18,
                         xtick_labelsize=14,ytick_labelsize=14)
    for ii, map in enumerate(maps.map()):
        if not ii in plotmaps: continue
        tfeh= round(numpy.median(map['FE_H'])*20.)/20.
        if tfeh == 0.25: tfeh= 0.3
        if tfeh == -0.1: tfeh= -0.1
        bovy_plot.bovy_hist(samples[ii,4],
                            range=xrange,bins=51,overplot=overplot,
                            yrange=yrange,
                            histtype='step',normed=True,zorder=2,
                            color=colorFunc(tfeh),
                            xlabel=r'$R_{\mathrm{flare}}^{-1}\,(\mathrm{kpc}^{-1})$')
        if plotXDFit:
            txs= numpy.linspace(xrange[0],xrange[1],1001)
            pyplot.plot(txs,1./numpy.sqrt(2.*numpy.pi)*(allxamp[cnt,0]/numpy.sqrt(allxcovar[cnt,0,0,0])*numpy.exp(-0.5*(txs-allxmean[cnt,0,0])**2./allxcovar[cnt,0,0,0])
                                                 +allxamp[cnt,1]/numpy.sqrt(allxcovar[cnt,1,0,0])*numpy.exp(-0.5*(txs-allxmean[cnt,1,0])**2./allxcovar[cnt,1,0,0])),
                        color=colorFunc(tfeh),
                        zorder=1)
        overplot=True
        cnt+= 1
    txs= numpy.linspace(xrange[0],xrange[1],1001)
    comb= numpy.ones_like(txs)
    for ii in range(len(plotmaps)):
        comb*= 1./numpy.sqrt(2.*numpy.pi)*(allxamp[ii,0]/numpy.sqrt(allxcovar[ii,0,0,0])*numpy.exp(-0.5*(txs-allxmean[ii,0,0])**2./allxcovar[ii,0,0,0])
                                           +allxamp[ii,1]/numpy.sqrt(allxcovar[ii,1,0,0])*numpy.exp(-0.5*(txs-allxmean[ii,1,0])**2./allxcovar[ii,1,0,0]))
    comb/= numpy.sum(comb)*(txs[1]-txs[0])
    pyplot.plot(txs,comb/combDiv,'k-',lw=2.,zorder=20)
    pyplot.plot([0.,0.],[0.,50.],'k--',lw=1.5,zorder=0)
    t= pyplot.text(xrange[0]+0.25*(xrange[1]-xrange[0])+0.03*('highalpha' in savename),
                        0.8*yrange[1],
                        r'$R_{\mathrm{flare}}^{-1} = %.2f \pm %.2f\,\mathrm{kpc}^{-1}$' % (numpy.sum(comb*txs)/numpy.sum(comb), numpy.sqrt(numpy.sum(comb*txs**2.)/numpy.sum(comb)-(numpy.sum(comb*txs)/numpy.sum(comb))**2.)),
                        size=18.)
    t.set_bbox(dict(color='w',edgecolor='none'))
    if 'lowalpha' in savename:
        bovy_plot.bovy_text(r'$\mathrm{low-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                            top_left=True,
                            size=16.)
    else:
        bovy_plot.bovy_text(r'$\mathrm{high-}[\alpha/\mathrm{Fe}]\ \mathrm{MAPs}$',
                            top_left=True,
                            size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
def plot_stream_aa(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                     'gd1_evol_hitres_aa_01312.dat'),
                        delimiter=',')
    includeorbit= True
    includetrack= True
    fmt= 'k,'
    if includeorbit:
        #Read progenitor actions
        progfile= '../sim/gd1_evol_hitres_progaai.dat'
        progaa= numpy.loadtxt(progfile,delimiter=',')
    if includetrack:
        #Setup stream model
        lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
        aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
        obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                          0.88719443,-0.47713334,0.12019596])
        sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                      leading=True,nosetup=True,
                      tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.))
    if 'araz' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,6]
        ploty= data[indx,8]
        plotx= (numpy.pi+(plotx-numpy.median(data[:,6]))) % (2.*numpy.pi)
        ploty= (numpy.pi+(ploty-numpy.median(data[:,8]))) % (2.*numpy.pi)
        xrange=[numpy.pi-1.,numpy.pi+1.]
        yrange=[numpy.pi-1.,numpy.pi+1.]
        xlabel=r'$\theta_R$'
        ylabel=r'$\theta_Z$'
    elif 'arap' in plotfilename and not 'aparaperp' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,6]
        ploty= data[indx,7]
        plotx= (numpy.pi+(plotx-numpy.median(data[:,6]))) % (2.*numpy.pi)
        ploty= (numpy.pi+(ploty-numpy.median(data[:,7]))) % (2.*numpy.pi)
        xrange=[numpy.pi-1.,numpy.pi+1.]
        yrange=[numpy.pi-1.,numpy.pi+1.]
        xlabel=r'$\theta_R$'
        ylabel=r'$\theta_\phi$'
    elif 'oroz' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,3]*bovy_conversion.freq_in_Gyr(220.,8.)
        ploty= data[indx,5]*bovy_conversion.freq_in_Gyr(220.,8.)
        xrange=[15.45,15.95]
        yrange=[11.7,12.05]
        xlabel=r'$\Omega_R\,(\mathrm{Gyr}^{-1})$'
        ylabel=r'$\Omega_Z\,(\mathrm{Gyr}^{-1})$'
    elif 'orop' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,3]*bovy_conversion.freq_in_Gyr(220.,8.)
        ploty= data[indx,4]*bovy_conversion.freq_in_Gyr(220.,8.)
        xrange=[15.45,15.95]
        yrange=[-10.98,-10.65]
        xlabel=r'$\Omega_R\,(\mathrm{Gyr}^{-1})$'
        ylabel=r'$\Omega_\phi\,(\mathrm{Gyr}^{-1})$'
    elif 'jrjz' in plotfilename:       
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,0]*8.
        ploty= data[indx,2]*8.
        xrange=[1.2,1.42]
        yrange=[3.98,4.18]
        xlabel=r'$J_R\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
        ylabel=r'$J_Z\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
    elif 'jrjp' in plotfilename:       
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,0]*8.
        ploty= data[indx,1]*8.
        xrange=[1.2,1.42]
        yrange=[-14.64,-14.23]
        xlabel=r'$J_R\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
        ylabel=r'$L_Z\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
    elif 'dohist' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        dO1d= numpy.dot(dOdir,dO)
        print "Misalignment:", numpy.arccos(numpy.sum(dOdir*progaa[-1,3:6])/numpy.sqrt(numpy.sum(dOdir**2.)*numpy.sum(progaa[-1,3:6]**2.)))/numpy.pi*180.-180.
        dO1d[dO1d < 0.]*= -1.
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(dO1d,range=[0.,0.4],bins=61,
                            normed=True,
                            xlabel=r'$\Large|\Delta \mathbf{\Omega}_\parallel\Large|\,(\mathrm{Gyr}^{-1})$',
                            histtype='step',color='k',zorder=10)
        #Overplot best-fit Gaussian
        xs= numpy.linspace(0.,0.4,1001)
        print numpy.mean(dO1d), numpy.std(dO1d)
        bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi)/numpy.std(dO1d)\
                                *numpy.exp(-(xs-numpy.mean(dO1d))**2./2./numpy.var(dO1d)),
                            '--',color='k',overplot=True,lw=2.,zorder=2)
        bestfit= optimize.fmin_powell(gausstimesvalue,
                                      numpy.array([numpy.log(numpy.mean(dO1d)*2.),
                                                   numpy.log(numpy.std(dO1d))]),
                                      args=(dO1d,))
        print numpy.exp(bestfit)
        bovy_plot.bovy_plot(xs,gausstimesvalue(bestfit,xs,nologsum=True),
                            '-',color='0.4',overplot=True,lw=2.,zorder=1)
        bovy_plot.bovy_end_print(plotfilename)
        return None
    elif 'dahist' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Gram-Schmidt to get the perpendicular directions
        v2= numpy.array([1.,0.,0.])
        v3= numpy.array([0.,1.,0.])
        u2= v2-numpy.sum(dOdir*v2)*dOdir
        u2/= numpy.sqrt(numpy.sum(u2**2.))
        u3= v3-numpy.sum(dOdir*v3)*dOdir-numpy.sum(u2*v3)*u2
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        dts= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
        #Rewind angles
        dangle-= dO*dts
        newdangle= numpy.empty_like(dangle)
        newdangle[0,:]= numpy.dot(dOdir,dangle)
        newdangle[1,:]= numpy.dot(u2,dangle)
        newdangle[2,:]= numpy.dot(u3,dangle)
        bovy_plot.bovy_print()
        xmin= -0.015
        bovy_plot.bovy_hist(newdangle[2,:].flatten(),range=[xmin,-xmin],bins=61,
                            xlabel=r'$|\Delta \mathbf{\theta}|$',
                            normed=True,lw=2.,
                            color='k',zorder=10,
                            histtype='step')
        #Overplot best-fit Gaussian
        xs= numpy.linspace(xmin,-xmin,1001)
        bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi)/numpy.std(newdangle[1:,:])\
                                *numpy.exp(-(xs-numpy.mean(newdangle[1:,:]))**2./2./numpy.var(newdangle[1:,:])),
                            '--',color='k',overplot=True,lw=2.,zorder=0)
        print "along", numpy.mean(newdangle[0,:]), numpy.std(newdangle[0,:])
        print "perpendicular 1", numpy.mean(newdangle[1,:]), numpy.std(newdangle[1,:])
        print "perpendicular 2", numpy.mean(newdangle[2,:]), numpy.std(newdangle[2,:])
        bovy_plot.bovy_end_print(plotfilename)
        return None
    elif 'aparopar' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= numpy.fabs(numpy.dot(dO.T,dOdir))
        xrange=[0.,1.3]
        yrange=[0.1,0.3]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$\Large|\Delta \mathbf{\Omega}_\parallel\Large|\,(\mathrm{Gyr}^{-1})$'
        fmt= 'k.'
    elif 'aparoperp' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= numpy.sqrt(numpy.sum(dO**2.,axis=0)\
                              -(numpy.dot(dO.T,dOdir))**2.)
        print numpy.std(ploty)
        xrange=[0.,1.3]
        yrange=[0.,0.005]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$\Large|\Delta \mathbf{\Omega}_\perp\Large|\,(\mathrm{Gyr}^{-1})$'
        fmt= 'k.'
    elif 'aparaperp' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= numpy.sqrt(numpy.sum(dangle**2.,axis=0)\
                              -(numpy.dot(dangle.T,dOdir))**2.)
        xrange=[0.,1.3]
        yrange=[0.,0.03]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$\Large|\Delta \mathbf{\theta}_\perp\Large|$'
        fmt= 'k.'
    elif 'apartime' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        dts= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= dts
        xrange=[0.,1.3]
        yrange=[0.,5.]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$t_s\,(\mathrm{Gyr})$'
        fmt= 'k.'
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(plotx,ploty,fmt,
                        xlabel=xlabel,
                        ylabel=ylabel,
                        xrange=xrange,
                        yrange=yrange,zorder=5)
    if includeorbit and 'araz' in plotfilename:
        #plot frequency line
        xs= numpy.array(xrange)
        ys= (xs-numpy.pi)*progaa[-1,5]/progaa[-1,3]+numpy.pi
        bovy_plot.bovy_plot(xs,ys,'k--',overplot=True,
                            zorder=0)
    elif includeorbit and 'arap' in plotfilename:
        #plot frequency line
        xs= numpy.array(xrange)
        ys= (xs-numpy.pi)*progaa[-1,4]/progaa[-1,3]+numpy.pi
        bovy_plot.bovy_plot(xs,ys,'k--',overplot=True,
                            zorder=0)
    elif includeorbit and 'oroz' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,3]*bovy_conversion.freq_in_Gyr(220.,8.),
                            progaa[-1,5]*bovy_conversion.freq_in_Gyr(220.,8.),
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    elif includeorbit and 'orop' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,3]*bovy_conversion.freq_in_Gyr(220.,8.),
                            progaa[-1,4]*bovy_conversion.freq_in_Gyr(220.,8.),
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    elif includeorbit and 'jrjz' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,0]*8.,
                            progaa[-1,2]*8.,
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    elif includeorbit and 'jrjp' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,0]*8.,
                            progaa[-1,1]*8.,
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    if includetrack and 'aparopar' in plotfilename:
        #Calculate mean and std of Omegapar as a function of anglepar
        das= numpy.linspace(0.,1.3,1001)
        dOs= numpy.array([sdf.meanOmega(da,oned=True) for da in das])
        sOs= numpy.array([sdf.sigOmega(da) for da in das])
        bovy_plot.bovy_plot(das,dOs*bovy_conversion.freq_in_Gyr(220.,8),
                            '-',color='0.75',lw=2.,overplot=True,zorder=10)
        pyplot.fill_between(das,(dOs+sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            (dOs-sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            color='0.6',zorder=1)
        pyplot.fill_between(das,(dOs+2*sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            (dOs-2*sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            color='0.8',zorder=0)
        #Also plot the apar at which t_d becomes important
        pyplot.plot([sdf.meanOmega(0.01,oned=True)*sdf._tdisrupt,
                     sdf.meanOmega(0.01,oned=True)*sdf._tdisrupt],
                    [0.,0.3],
                    'k--')                     
    elif includetrack and 'apartime' in plotfilename:
        das= numpy.linspace(0.01,1.3,101)
        mts= numpy.array([sdf.meantdAngle(da) for da in das])
        sts= numpy.array([sdf.sigtdAngle(da) for da in das])
        bovy_plot.bovy_plot(das,mts*bovy_conversion.time_in_Gyr(220.,8),
                            '-',color='0.75',lw=2.,overplot=True,zorder=10)
        pyplot.fill_between(das,(mts+2*sts)*bovy_conversion.time_in_Gyr(220.,8),
                            (mts-2*sts)*bovy_conversion.time_in_Gyr(220.,8),
                            color='0.8',zorder=0)
        pyplot.fill_between(das,(mts+sts)*bovy_conversion.time_in_Gyr(220.,8),
                            (mts-sts)*bovy_conversion.time_in_Gyr(220.,8),
                            color='0.6',zorder=1)
    elif includetrack and 'aparaperp' in plotfilename:
        das= numpy.linspace(0.01,1.3,101)
        sas= numpy.array([sdf.sigangledAngle(da) for da in das])*numpy.sqrt(2.)
        sass= numpy.array([sdf.sigangledAngle(da,simple=True) for da in das])*numpy.sqrt(2.)
        pyplot.fill_between(das,0.,
                            (2*sas),
                            color='0.8',zorder=0)
        pyplot.fill_between(das,0.,
                            (sas),
                            color='0.6',zorder=1)
        pyplot.plot(das,sass,'--',color='w',zorder=7,lw=2.)
    #ax= pyplot.gca()
    #ax.set_rasterized(True)
    bovy_plot.bovy_end_print(plotfilename)
def main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit MWPotential with Double-Exponential Disk Script Function.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    plt.figure(figsize=(4, 4))
    dum = bovy_plot.bovy_hist(
        s[9],
        bins=36,
        histtype="step",
        lw=2.0,
        xlabel=r"$c/a$",
        xrange=[0.0, 4.0],
        normed=True,
    )
    sortedc = np.array(sorted(s[9]))
    plt.title("2.5%% and 0.5%% lower limits: %.2f, %.2f" % (
        sortedc[int(np.floor(0.025 * len(sortedc)))],
        sortedc[int(np.floor(0.005 * len(sortedc)))],
    ))
    plt.savefig(fpath + "varyc-dblexp-fitvoro-addgas-samples-shape_hist.pdf")
def main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit GD1 to MW Potential Script Function.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    with open(opath + "fit_potential_gd1.txt", "w") as file:

        sortedc = np.array(sorted(s[cindx]))
        file.write("2.5%% and 0.5%% lower limits: %.2f, %.2f" % (
            sortedc[int(np.floor(0.025 * len(sortedc)))],
            sortedc[int(np.floor(0.005 * len(sortedc)))],
        ))
        file.write("2.5%% and 0.5%% upper limits: %.2f, %.2f" % (
            sortedc[int(np.floor(0.975 * len(sortedc)))],
            sortedc[int(np.floor(0.995 * len(sortedc)))],
        ))
        file.write("Median, 68%% confidence: %.2f, %.2f, %.2f" % (
            np.median(sortedc),
            sortedc[int(np.floor(0.16 * len(sortedc)))],
            sortedc[int(np.floor(0.84 * len(sortedc)))],
        ))
def main(args: Optional[list] = None, opts: Optional[Namespace] = None):
    """Fit MWPotential2014 Script Function.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    plt.figure(figsize=(6, 4))
    dum = bovy_plot.bovy_hist(
        apal5s, range=[0.0, 10.0], lw=2.0, bins=51, histtype="step", normed=True,
    )
    plt.savefig("figures/kuepper_samples_prior.pdf")
    plt.close()
Пример #39
0
def main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit MWPotential2014 Script Function.

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

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

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

    if not os.path.exists(opts.opath):
        os.makedirs(opts.opath)

    if not os.path.exists(opts.fpath):
        os.makedirs(opts.fpath)

    # ----------------------------------------------------------
    # Basic, Bovy (2015) fit with $c=1$

    # -----------------------
    # Using the Clemens CO terminal-velocity data:

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

    # -----------------------
    # Using the McClure-Griffiths & Dickey HI terminal-velocity data instead

    plt.figure(figsize=(16, 5))
    p_b15_mc16 = mw_pot.fit(fitc=False,
                            c=1.0,
                            mc16=True,
                            plots=fpath + "McClure-c_1.pdf")
    plt.close()

    # We ran the initial analysis with Clemens, which we keep here, until we
    # start interpreting the Pal 5 and GD-1 data; then we switch to the
    # McClure-Griffths & Dickey data. The resulting best-fit parameters here
    # are almost the same, well within each others errors.

    # ----------------------------------------------------------
    # Fits with $c \neq 1$

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

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

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

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

    # All look pretty similar...

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

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

    # ----------------------------------------------------------
    # Fits with free $c$

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if save_figures:
        plt.savefig(
            os.path.join(
                os.getenv("PAPERSDIR"),
                "2016-mwhalo-shape",
                "mwpot14-varyc.pdf",
            ),
            bbox_inches="tight",
        )

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

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

    return