Exemplo n.º 1
0
def _get_pal5varyvc():

    pal5varyc, cs = _get_pal5varyc()

    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varyvc.pkl"

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            vcs = pickle.load(savefile)
            pal5varyvc = pickle.load(savefile)
    else:
        vcs = np.arange(200.0, 255.0, 5.0)
        pal5varyvc = np.zeros(
            (len(vcs), 4, pal5varyc[0].shape[1], pal5varyc[0].shape[2]))
        for ii, vc in enumerate(vcs):
            t = pal5_util.predict_pal5obs(p_b15,
                                          1.0,
                                          multi=8,
                                          vo=vc,
                                          singlec=True,
                                          useTM=False)
            for jj in range(4):
                pal5varyvc[ii, jj] = t[jj][0]
        save_pickles(savefilename, vcs, pal5varyvc)

    return pal5varyvc, vcs
Exemplo n.º 2
0
def calc_pred(pred_file,dfc,nls,nds,ls,ds):
    if os.path.exists(pred_file):
        savefile= open(pred_file,'rb')
        ls= pickle.load(savefile)
        avg_pred= pickle.load(savefile)
        ii= pickle.load(savefile)
        savefile.close()
    else:
        avg_pred= numpy.zeros(nls)
        ii= 0
    while ii < len(ls):
        sys.stdout.write('\r'+"Working on %i / %i ...\r" %(ii+1,len(ls)))
        sys.stdout.flush()
        meanvlos= 0.
        norm= 0.
        for jj in range(nds):
            d,l= ds[jj], ls[ii]/180.*numpy.pi
            R,theta,d,l= safe_dl_to_rphi(d,l)
            surfmass= dfc.surfacemassLOS(d,l,deg=False)
            meanvlos+= surfmass*dfc.meanvT(R)*math.sin(theta+l)
            norm+= surfmass
        avg_pred[ii]= meanvlos/norm
        ii+= 1
        save_pickles(pred_file,ls,avg_pred,ii)
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    save_pickles(pred_file,ls,avg_pred,ii)
Exemplo n.º 3
0
def XDapogee(options,args):
    #First load the chains
    savefile= open(args[0],'rb')
    thesesamples= pickle.load(savefile)
    savefile.close()
    vcs= numpy.array([s[0] for s in thesesamples])*_APOGEEREFV0/_REFV0
    dvcdrs= numpy.array([s[6] for s in thesesamples])*30. #To be consistent with this project's dlnvcdlnr 
    print numpy.mean(vcs)
    print numpy.mean(dvcdrs)
    #Now fit XD to the 2D PDFs
    ydata= numpy.zeros((len(vcs),2))
    ycovar= numpy.zeros((len(vcs),2))
    ydata[:,0]= numpy.log(vcs)
    ydata[:,1]= dvcdrs
    vcxamp= numpy.ones(options.g)/options.g
    vcxmean= numpy.zeros((options.g,2))
    vcxcovar= numpy.zeros((options.g,2,2))
    for ii in range(options.g):
        vcxmean[ii,:]= numpy.mean(ydata,axis=0)+numpy.std(ydata,axis=0)*numpy.random.normal(size=(2))/4.
        vcxcovar[ii,0,0]= numpy.var(ydata[:,0])
        vcxcovar[ii,1,1]= numpy.var(ydata[:,1])
    extreme_deconvolution.extreme_deconvolution(ydata,ycovar,
                                                vcxamp,vcxmean,vcxcovar)
    save_pickles(options.plotfile,
                 vcxamp,vcxmean,vcxcovar)
    print vcxamp
    print vcxmean[:,0]
    print vcxmean[:,1]
    return None
Exemplo n.º 4
0
def fitMAPs(type, savefilename):
    setup_selection_function()
    if os.path.exists(savefilename):
        with open(savefilename, 'rb') as savefile:
            bf = pickle.load(savefile)
            samples = pickle.load(savefile)
            bf_g15 = pickle.load(savefile)
            samples_g15 = pickle.load(savefile)
            bf_zero = pickle.load(savefile)
            samples_zero = pickle.load(savefile)
            bii = pickle.load(savefile)
    else:
        bf = []
        samples = []
        bf_g15 = []
        samples_g15 = []
        bf_zero = []
        samples_zero = []
        bii = 0
    maps = define_rcsample.MAPs()
    for ii, map in enumerate(maps.map()):
        if ii < bii: continue
        tbf, ts = fitmap(map, type=type, dmap='marshall06')
        bf.append(tbf)
        samples.append(ts)
        tbf, ts = fitmap(map, type=type, dmap='green15')
        bf_g15.append(tbf)
        samples_g15.append(ts)
        tbf, ts = fitmap(map, type=type, dmap='zero')
        bf_zero.append(tbf)
        samples_zero.append(ts)
        print ii, numpy.median(samples[-1], axis=1)
        save_pickles(savefilename, bf, samples, bf_g15, samples_g15, bf_zero,
                     samples_zero, ii + 1)
    return None
Exemplo n.º 5
0
def test_save_pickles():
    import os
    import tempfile
    import pickle
    from galpy.util import save_pickles
    savethis= numpy.linspace(0.,100.,1001)
    savefile, tmp_savefilename= tempfile.mkstemp()
    try:
        os.close(savefile) #Easier this way 
        save_pickles(tmp_savefilename,savethis)
        savefile= open(tmp_savefilename,'rb')
        restorethis= pickle.load(savefile)
        savefile.close()
        assert numpy.all(numpy.fabs(restorethis-savethis) < 10.**-10.), 'save_pickles did not work as expected'
    finally:
        os.remove(tmp_savefilename)
    #Also test the handling of KeyboardInterrupt
    try:
        save_pickles(tmp_savefilename,savethis,testKeyboardInterrupt=True)
    except KeyboardInterrupt:
        pass
    else:
        raise AssertionError('save_pickles with testKeyboardInterrupt=True did not raise KeyboardInterrupt')
    savefile= open(tmp_savefilename,'rb')
    restorethis= pickle.load(savefile)
    savefile.close()
    assert numpy.all(numpy.fabs(restorethis-savethis) < 10.**-10.), 'save_pickles did not work as expected when KeyboardInterrupted'
    if os.path.exists(tmp_savefilename): os.remove(tmp_savefilename)   
    return None
Exemplo n.º 6
0
def _get_pal5varyc():

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varyc.pkl"
    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            cs = pickle.load(savefile)
            pal5varyc = pickle.load(savefile)
    else:
        cs = np.arange(0.5, 2.3, 0.1)
        pal5varyc = pal5_util.predict_pal5obs(
            p_b15,
            cs,
            multi=8,
            useTM=False,
            interpcs=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25],
        )
        save_pickles(savefilename, cs, pal5varyc)

    return pal5varyc, cs
Exemplo n.º 7
0
def test_save_pickles():
    import os
    import tempfile
    import pickle
    from galpy.util import save_pickles
    savethis = numpy.linspace(0., 100., 1001)
    savefile, tmp_savefilename = tempfile.mkstemp()
    try:
        os.close(savefile)  #Easier this way
        save_pickles(tmp_savefilename, savethis)
        savefile = open(tmp_savefilename, 'rb')
        restorethis = pickle.load(savefile)
        savefile.close()
        assert numpy.all(numpy.fabs(restorethis - savethis) < 10.**-10.
                         ), 'save_pickles did not work as expected'
    finally:
        os.remove(tmp_savefilename)
    #Also test the handling of KeyboardInterrupt
    try:
        save_pickles(tmp_savefilename, savethis, testKeyboardInterrupt=True)
    except KeyboardInterrupt:
        pass
    else:
        raise AssertionError(
            'save_pickles with testKeyboardInterrupt=True did not raise KeyboardInterrupt'
        )
    savefile = open(tmp_savefilename, 'rb')
    restorethis = pickle.load(savefile)
    savefile.close()
    assert numpy.all(
        numpy.fabs(restorethis - savethis) < 10.**-10.
    ), 'save_pickles did not work as expected when KeyboardInterrupted'
    if os.path.exists(tmp_savefilename): os.remove(tmp_savefilename)
    return None
Exemplo n.º 8
0
def calc_pred(pred_file, dfc, nls, nds, ls, ds):
    if os.path.exists(pred_file):
        savefile = open(pred_file, 'rb')
        ls = pickle.load(savefile)
        avg_pred = pickle.load(savefile)
        ii = pickle.load(savefile)
        savefile.close()
    else:
        avg_pred = numpy.zeros(nls)
        ii = 0
    while ii < len(ls):
        sys.stdout.write('\r' + "Working on %i / %i ...\r" % (ii + 1, len(ls)))
        sys.stdout.flush()
        meanvlos = 0.
        norm = 0.
        for jj in range(nds):
            d, l = ds[jj], ls[ii] / 180. * numpy.pi
            R, theta, d, l = safe_dl_to_rphi(d, l)
            surfmass = dfc.surfacemassLOS(d, l, deg=False)
            meanvlos += surfmass * dfc.meanvT(R) * math.sin(theta + l)
            norm += surfmass
        avg_pred[ii] = meanvlos / norm
        ii += 1
        save_pickles(pred_file, ls, avg_pred, ii)
    sys.stdout.write('\r' + _ERASESTR + '\r')
    sys.stdout.flush()
    save_pickles(pred_file, ls, avg_pred, ii)
Exemplo n.º 9
0
def save_stream_model_pickles(fname, config, leading):
    model = streammodel_util.setup_streammodel(obs=config.obs,
                                               age=config.age,
                                               sigv=config.sigv,
                                               timpact=config.timpact,
                                               leading=leading)
    save_pickles(_DATADIR + 'model_pickles/' + fname, model)
    return
Exemplo n.º 10
0
def calc_avg_rcmks(parser):
    options,args= parser.parse_args()
    njks= 101
    nmks= 101
    jks= numpy.linspace(0.5,0.8,njks)
    mks= numpy.linspace(-0.5,-3.,nmks)
    if options.basti:
        zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04])
        zsolar= 0.019
    elif options.parsec:
        zs= numpy.arange(0.0005,0.06005,0.0005)
#        zs= numpy.array([0.01,0.02])
        zsolar= 0.019
    else:
        zs= numpy.arange(0.0005,0.03005,0.0005)
#        zs= numpy.array([0.01,0.02])
        zsolar= 0.019
    if not os.path.exists(options.outfilename):
        logpz= localzdist(zs,zsolar=zsolar)
        logmkp= numpy.zeros((len(zs),njks,nmks))
        logp= numpy.zeros((len(zs),njks,nmks))      
        funcargs= (zs,options,njks,jks,nmks,mks,logpz)
        multOut= multi.parallel_map((lambda x: indiv_calc(x,
                                                          *funcargs)),
                                    range(len(zs)),
                                    numcores=numpy.amin([64,len(zs),
                                                         multiprocessing.cpu_count()]))
        for ii in range(len(zs)):
            logmkp[ii,:,:]= multOut[ii][0,:,:]
            logp[ii,:,:]= multOut[ii][1,:,:]
        save_pickles(options.outfilename,logmkp,logp)
    else:
        savefile= open(options.outfilename,'rb')
        logmkp= pickle.load(savefile)
        logp= pickle.load(savefile)
        savefile.close()
    indx= numpy.isnan(logp)
    logp[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
    logmkp[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
    #Average the peak, so calculate the peak
    for ii in range(len(zs)):
        for jj in range(njks):
            maxmkindx= numpy.argmax(logp[ii,jj,:])
            totlogp= maxentropy.logsumexp(logp[ii,jj,:])
            logmkp[ii,jj,:]= logmkp[ii,jj,maxmkindx]-logp[ii,jj,maxmkindx]+totlogp
            logp[ii,jj,:]= totlogp
    avgmk= numpy.exp(maxentropy.logsumexp(logmkp.flatten())\
                         -maxentropy.logsumexp(logp.flatten()))
    solindx= numpy.argmin(numpy.fabs(zs-0.017))
    avgmksolar= numpy.exp(maxentropy.logsumexp(logmkp[solindx,:,:].flatten())\
                              -maxentropy.logsumexp(logp[solindx,:,:].flatten()))
    print "Average mk: %f" % (-avgmk)
    print "Average mk if solar: %f" % (-avgmksolar)
    return -avgmk
Exemplo n.º 11
0
def plotPriorSurf(plotfilename):
    #Calculate the surface density profile for each trial potential, then plot the range
    if '.png' in plotfilename:
        savefilename= plotfilename.replace('.png','.sav')
    elif '.ps' in plotfilename:
        savefilename= plotfilename.replace('.ps','.sav')
    if not os.path.exists(savefilename):
        options= setup_options(None)
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        options.fitdvt= False
        rs= numpy.linspace(4.2,9.8,101)
        rds= numpy.linspace(2.,3.4,8)
        fhs= numpy.linspace(0.,1.,16)
        surfz= numpy.zeros((len(rs),len(rds)*len(fhs)))+numpy.nan
        ro= 1.
        vo= 230./220.
        dlnvcdlnr= 0.
        zh= 400.
        for jj in range(len(rds)):
            for kk in range(len(fhs)):
                #Setup potential to calculate stuff
                potparams= numpy.array([numpy.log(rds[jj]/8.),vo,numpy.log(zh/8000.),fhs[kk],dlnvcdlnr])
                try:
                    pot= setup_potential(potparams,options,0,returnrawpot=True)
                except RuntimeError:
                    continue
                for ii in range(len(rs)):
                    surfz[ii,jj*len(fhs)+kk]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(rs[ii]/8.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
        #Find minimum and maximum curves
        minsurfz= numpy.nanmin(surfz,axis=1)
        maxsurfz= numpy.nanmax(surfz,axis=1)
        #Save
        save_pickles(savefilename,rs,minsurfz,maxsurfz)
    else:
        savefile= open(savefilename,'rb')
        rs= pickle.load(savefile)
        minsurfz= pickle.load(savefile)
        maxsurfz= pickle.load(savefile)
        savefile.close()
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot([numpy.nan],[numpy.nan],'ko',
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$\Sigma(R,|Z| \leq 1.1\,\mathrm{kpc})\ (M_\odot\,\mathrm{pc}^{-2})$',
                        xrange=[4.,10.],
                        yrange=[10,1050.],
                        semilogy=True)
    pyplot.fill_between(rs,minsurfz,maxsurfz,
                        color='0.50')
    bovy_plot.bovy_text(8.,68.,r'$\odot$',size=16.,verticalalignment='center',
                        horizontalalignment='center')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 12
0
def calc_effsel(args,options,sample=None):
    # Work-horse function to compute the effective selection function, 
    # sample is a data sample of stars to consider for the (JK,Z) sampling
    # Setup selection function
    selectFile= '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile,'rb') as savefile:
            apo= pickle.load(savefile)
    else:
        # Setup selection function
        apo= apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile,apo)
    # Get the full data sample for the locations (need all locations where 
    # stars could be observed, so the whole sample, not just the subsample
    # being analyzed)
    data= get_rcsample()
    locations= list(set(list(data['LOCATION_ID'])))
    # Load the dust map and setup the effective selection function
    if options.dmap.lower() == 'green15':
        dmap3d= mwdust.Green15(filter='2MASS H')
    elif options.dmap.lower() == 'marshall06':
        dmap3d= mwdust.Marshall06(filter='2MASS H')
    elif options.dmap.lower() == 'drimmel03':
        dmap3d= mwdust.Drimmel03(filter='2MASS H')
    elif options.dmap.lower() == 'sale14':
        dmap3d= mwdust.Sale14(filter='2MASS H')
    elif options.dmap.lower() == 'zero':
        dmap3d= mwdust.Zero(filter='2MASS H')
    # Sample the M_H distribution
    if options.samplemh:
        if sample is None: sample= data
        MH= sample['H0']-sample['RC_DM']
        MH= numpy.random.permutation(MH)[:1000] # do 1,000 max
    else:
        MH= -1.49
    apof= apogee.select.apogeeEffectiveSelect(apo,dmap3d=dmap3d,MH=MH)
    # Distances at which to calculate the effective selection function
    distmods= numpy.linspace(options.dm_min,options.dm_max,options.ndm)
    ds= 10.**(distmods/5-2.)
    # Now compute all selection functions
    out= multi.parallel_map((lambda x: _calc_effsel_onelocation(\
                locations[x],apof,apo,ds)),
                            range(len(locations)),
                            numcores=numpy.amin([len(locations),
                                                 multiprocessing.cpu_count(),options.multi]))
    # Save out
    out= numpy.array(out)
    save_pickles(args[0],locations,out,distmods,ds)
    return None
Exemplo n.º 13
0
def plot_distanceintegral(savename,plotname,rmcenter=False,
                          onlygreen=False):
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            area= pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                             numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                             nest=False)
        cosb= numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename,area)
    # Plot the power spectrum
    if True:
        psdx, psd= signal.periodogram(area*dust._GREEN15DISTS**3./numpy.sum(area*dust._GREEN15DISTS**3.),
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                                      detrend=lambda x: x,scaling='spectrum')
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(psdx[1:],psd[1:],
                            'k-',loglog=True,
                            xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$P_k$',
                            xrange=[0.04,4.])
        bovy_plot.bovy_text(r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
                            bottom_left=True,size=16.)
        bovy_plot.bovy_end_print(plotname)               
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(dust._GREEN15DISTMODS,
                            area*dust._GREEN15DISTS**3.,
                            'k-',
                            xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    spl= interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                  area*dust._GREEN15DISTS**3.,
                                                  k=5)
    fthder= [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
    print "Simpson error= %g, volume= %g" % (0.5**4./180.*numpy.mean(numpy.fabs(fthder))/integrate.simps(area*dust._GREEN15DISTS**3.,dx=0.5),numpy.sum(area*dust._GREEN15DISTS**3.))
    return None
Exemplo n.º 14
0
def plot_dustnearplane(plotname,green=False):
    if green: savefile= _SAVEFILE_GREEN
    else: savefile= _SAVEFILE_MARSHALL
    # Grid
    ls= numpy.linspace(15.,70.,_NL)
    bs= numpy.linspace(-2.,2.,_NB)
    if not os.path.exists(savefile):
        # Setup dust map
        if green:
            dmap= mwdust.Green15(filter='2MASS H')
        else:
            dmap= mwdust.Marshall06(filter='2MASS H')
        plotthis= numpy.empty((_NL,_NB))
        rad= 0.5 # deg
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                pa, ah= dmap.dust_vals_disk(ls[ii],bs[jj],7.,rad)
                plotthis[ii,jj]= numpy.sum(pa*ah)/numpy.sum(pa)
        save_pickles(savefile,plotthis)
    else:
        with open(savefile,'rb') as f:
            plotthis= pickle.load(f)
    # Now plot
    bovy_plot.bovy_print(fig_width=8.4,fig_height=4.)
    bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm,
#                          interpolation='nearest',
                          colorbar=True,shrink=0.45,
                          vmin=0.,vmax=2.-0.75*green,aspect=3.,
                          xrange=[ls[-1]+(ls[1]-ls[0])/2.,
                                  ls[0]-(ls[1]-ls[0])/2.],
                          yrange=[bs[0]-(bs[1]-bs[0])/2.,
                                  bs[-1]+(bs[1]-bs[0])/2.],
                          xlabel=r'$l\,\mathrm{(deg)}$',
                          ylabel=r'$b\,\mathrm{(deg)}$',
                          zlabel=r'$A_H\,(\mathrm{mag})$',
                          zorder=0)
    bovy_plot.bovy_text(r'$D = 7\,\mathrm{kpc}$',top_left=True,
                        color='w',size=16.)
    # Overplot fields
    glons= [34.,64.,27.]
    glats= [0.,0.,0.]
    colors= ['w','w','y']
    xs= numpy.linspace(-1.5,1.5,201)
    ys= numpy.sqrt(1.5**2.-xs**2.)
    for glon,glat,c in zip(glons,glats,colors):
        bovy_plot.bovy_plot(xs+glon,ys+glat,'-',overplot=True,zorder=1,lw=2.,
                            color=c)
        bovy_plot.bovy_plot(xs+glon,-ys+glat,'-',overplot=True,zorder=1,lw=2.,
                            color=c)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 15
0
def calc_effsel(args, options, sample=None):
    # Work-horse function to compute the effective selection function,
    # sample is a data sample of stars to consider for the (JK,Z) sampling
    # Setup selection function
    selectFile = '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile, 'rb') as savefile:
            apo = pickle.load(savefile)
    else:
        # Setup selection function
        apo = apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile, apo)
    # Get the full data sample for the locations (need all locations where
    # stars could be observed, so the whole sample, not just the subsample
    # being analyzed)
    data = get_rcsample()
    locations = list(set(list(data['LOCATION_ID'])))
    # Load the dust map and setup the effective selection function
    if options.dmap.lower() == 'green15':
        dmap3d = mwdust.Green15(filter='2MASS H')
    elif options.dmap.lower() == 'marshall06':
        dmap3d = mwdust.Marshall06(filter='2MASS H')
    elif options.dmap.lower() == 'drimmel03':
        dmap3d = mwdust.Drimmel03(filter='2MASS H')
    elif options.dmap.lower() == 'sale14':
        dmap3d = mwdust.Sale14(filter='2MASS H')
    elif options.dmap.lower() == 'zero':
        dmap3d = mwdust.Zero(filter='2MASS H')
    # Sample the M_H distribution
    if options.samplemh:
        if sample is None: sample = data
        MH = sample['H0'] - sample['RC_DM']
        MH = numpy.random.permutation(MH)[:1000]  # do 1,000 max
    else:
        MH = -1.49
    apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=dmap3d, MH=MH)
    # Distances at which to calculate the effective selection function
    distmods = numpy.linspace(options.dm_min, options.dm_max, options.ndm)
    ds = 10.**(distmods / 5 - 2.)
    # Now compute all selection functions
    out= multi.parallel_map((lambda x: _calc_effsel_onelocation(\
                locations[x],apof,apo,ds)),
                            range(len(locations)),
                            numcores=numpy.amin([len(locations),
                                                 multiprocessing.cpu_count(),options.multi]))
    # Save out
    out = numpy.array(out)
    save_pickles(args[0], locations, out, distmods, ds)
    return None
Exemplo n.º 16
0
def testErrs(options,args):
    ndfehs, ndafes= 201,201
    dfehs= numpy.linspace(0.01,0.4,ndfehs)
    dafes= numpy.linspace(0.01,0.3,ndafes)
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        loglike= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        loglike= numpy.zeros((ndfehs,ndafes))
        ii, jj= 0, 0
    while ii < ndfehs:
        while jj < ndafes:
            sys.stdout.write('\r'+"Working on %i / %i" %(ii*ndafes+jj+1,ndafes*ndfehs))
            sys.stdout.flush()
            loglike[ii,jj]= errsLogLike(dfehs[ii],dafes[jj],options)
            jj+= 1
        ii+= 1
        jj= 0
        save_pickles(args[0],loglike,ii,jj)
    save_pickles(args[0],loglike,ii,jj)
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    if options.prior:
        prior= numpy.zeros((ndfehs,ndafes))
        for ii in range(ndfehs):
            prior[ii,:]= -0.5*(dafes-0.1)**2./0.1**2.-0.5*(dfehs[ii]-0.2)**2./0.1**2.
        loglike+= prior
    loglike-= maxentropy.logsumexp(loglike)
    loglike= numpy.exp(loglike)
    loglike/= numpy.sum(loglike)*(dfehs[1]-dfehs[0])*(dafes[1]-dafes[0])
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(loglike.T,origin='lower',
                          cmap='gist_yarg',
                          xlabel=r'\delta_{[\mathrm{Fe/H}]}',
                          ylabel=r'\delta_{[\alpha/\mathrm{Fe}]}',
                          xrange=[dfehs[0],dfehs[-1]],
                          yrange=[dafes[0],dafes[-1]],
                          contours=True,
                          cntrmass=True,
                          onedhists=True,
                          levels= special.erf(0.5*numpy.arange(1,4)))
    if options.prior:
        bovy_plot.bovy_text(r'$\mathrm{with\ Gaussian\ prior:}$'+
                            '\n'+r'$\delta_{[\mathrm{Fe/H}]}= 0.2 \pm 0.1$'
                            +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]}= 0.1 \pm 0.1$',
top_right=True)
    bovy_plot.bovy_end_print(options.plotfile)
Exemplo n.º 17
0
def fitBroadSubsamples(sample, savename):
    # Setup the selection function
    setup_selection_function()
    # Load the data
    load_data(sample)
    # Do the fits
    global bf_exp, bf_brexp, bf_twoexp
    global ml_exp, ml_brexp, ml_twoexp
    global samples_exp, samples_brexp, samples_twoexp
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            bf_exp = pickle.load(savefile)
            bf_brexp = pickle.load(savefile)
            bf_twoexp = pickle.load(savefile)
            ml_exp = pickle.load(savefile)
            ml_brexp = pickle.load(savefile)
            ml_twoexp = pickle.load(savefile)
            samples_exp = pickle.load(savefile)
            samples_brexp = pickle.load(savefile)
            samples_twoexp = pickle.load(savefile)
    else:
        # Perform fits of
        # a) expplusconst
        bf_exp, samples_exp, ml_exp = fit(type='expplusconst')
        # b) brokenexpflare
        bf_brexp, samples_brexp, ml_brexp = fit(type='tribrokenexpflare')
        # c) brokentwoexp
        bf_twoexp, samples_twoexp, ml_twoexp = fit(type='tribrokentwoexp')
        save_pickles(savename, bf_exp, bf_brexp, bf_twoexp, ml_exp, ml_brexp,
                     ml_twoexp, samples_exp, samples_brexp, samples_twoexp)
    # Do the rest of the fits as justfit
    global bf_brexp_g15, ml_brexp_g15, bf_brexp_drim, ml_brexp_drim
    global bf_brexp_sale, ml_brexp_sale, bf_brexp_zero, ml_brexp_zero
    bf_brexp_g15, ml_brexp_g15 = fit(type='tribrokenexpflare',
                                     dmap='green15',
                                     justfit=True,
                                     init=bf_brexp)
    bf_brexp_drim, ml_brexp_drim = fit(type='tribrokenexpflare',
                                       dmap='drimmel03',
                                       justfit=True,
                                       init=bf_brexp)
    bf_brexp_sale, ml_brexp_sale = fit(type='tribrokenexpflare',
                                       dmap='sale14',
                                       justfit=True,
                                       init=bf_brexp)
    bf_brexp_zero, ml_brexp_zero = fit(type='tribrokenexpflare',
                                       dmap='zero',
                                       justfit=True,
                                       init=bf_brexp)
    return None
Exemplo n.º 18
0
    def __init__(self, remodel=False, save=False, leading=False):
        if remodel == True:
            from streampepper_utils import parse_times
            self.sp = pal5_util.setup_pal5model(timpact=parse_times(
                '64sampling', 5),
                                                leading=leading)
            if save:
                self.pepperfilename = './data/pal5_64sample.pkl'
                save_pickles(self.pepperfilename, self.sp)

        if remodel == False:
            self.pepperfilename = 'data/pal5_64sampling_trailing.pkl'
            with open(self.pepperfilename, 'rb') as savefile:
                self.sp = pickle.load(savefile)
        self.sp._useInterp = True
Exemplo n.º 19
0
def plot_distanceareaintegral(savename,
                              plotname,
                              rmcenter=False,
                              onlygreen=False):
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi = healpy.pixelfunc.pix2ang(
            _NSIDE,
            numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
            nest=False)
        cosb = numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceAreaIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename, area)
    # Plot the power spectrum
    area = numpy.array(area)
    if True:
        psdthis = ((area.T * dust._GREEN15DISTS**3.).T / numpy.sum(
            (area.T * dust._GREEN15DISTS**3.), axis=1))
        psdx, psd = signal.periodogram(
            psdthis,
            fs=1. / (dust._GREEN15DISTMODS[1] - dust._GREEN15DISTMODS[0]),
            detrend=lambda x: x,
            scaling='spectrum',
            axis=0)
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        healpy.visufunc.mollview(numpy.log10(psd[-2]),
                                 nest=False,
                                 xsize=4000,
                                 min=-10.,
                                 max=-3.,
                                 cmap='gist_yarg',
                                 title="")
        bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 20
0
def plot_dustinfield(plotname, field, threshold=False):
    savefile = _SAVEFILE_MARSHALL
    savefile = savefile.replace('FIELD', '%i' % field)
    # Grid
    ls = numpy.linspace(-1.75, 1.75, _NL) + field
    bs = numpy.linspace(-1.75, 1.75, _NB)
    if not os.path.exists(savefile):
        # Setup dust map
        dmap = mwdust.Marshall06(filter='2MASS H')
        plotthis = numpy.empty((_NL, _NB))
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                plotthis[ii, jj] = dmap(ls[ii], bs[jj], 7.)
        save_pickles(savefile, plotthis)
    else:
        with open(savefile, 'rb') as f:
            plotthis = pickle.load(f)
    # Remove outside the field
    tls = numpy.tile(ls, (_NB, 1)).T
    tbs = numpy.tile(bs, (_NL, 1))
    plotthis[(tls - field)**2. + tbs**2. > 1.5**2.] = numpy.nan
    if threshold:
        plotthis[plotthis > 1.4] = numpy.nan
    # Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(
        plotthis[::-1].T,
        origin='lower',
        cmap=cm.coolwarm,
        interpolation='nearest',
        vmin=0.,
        vmax=2.,
        aspect=1.,
        xrange=[ls[-1] + (ls[1] - ls[0]) / 2., ls[0] - (ls[1] - ls[0]) / 2.],
        yrange=[bs[0] - (bs[1] - bs[0]) / 2., bs[-1] + (bs[1] - bs[0]) / 2.],
        xlabel=r'$l\,\mathrm{(deg)}$',
        ylabel=r'$b\,\mathrm{(deg)}$',
        zlabel=r'$A_H\,(\mathrm{mag})$',
        zorder=0)
    bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field,
                        top_left=True,
                        color='k',
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 21
0
def calc_delta_MWPotential2014(savefilename,plotfilename):
    Lmin, Lmax= 0.01, 10.
    if not os.path.exists(savefilename):
        #Setup grid
        nL, nE= 101,101
        Ls= 10.**numpy.linspace(numpy.log10(Lmin),numpy.log10(Lmax),nL)
        #Integration times
        ts= numpy.linspace(0.,20.,1001)
        deltas= numpy.empty((nL,nE))
        Einf= evalPot(10.**12.,0.,MWPotential2014)
        print Einf
        for ii in range(nL):
            #Calculate Ec
            Rc= rl(MWPotential2014,Ls[ii])
            print ii, "Rc = ", Rc*8.
            Ec= evalPot(Rc,0.,MWPotential2014)+0.5*Ls[ii]**2./Rc**2.
            Es= Ec+(Einf-Ec)*10.**numpy.linspace(-2.,0.,nE)
            for jj in range(nE):
                #Setup an orbit with this energy and angular momentum
                Er= 2.*(Es[jj]-Ec) #Random energy times 2 = vR^2 + vz^2
                vR= numpy.sqrt(4./5.*Er)
                vz= numpy.sqrt(1./5.*Er)
                o= Orbit([Rc,vR,Ls[ii]/Rc,0.,vz,0.])
                o.integrate(ts,MWPotential2014,method='symplec4_c')
                deltas[ii,jj]= estimateDeltaStaeckel(o.R(ts),o.z(ts),
                                                     pot=MWPotential2014)
        #Save
        save_pickles(savefilename,deltas)
    else:
        savefile= open(savefilename,'rb')
        deltas= pickle.load(savefile)
        savefile.close()
    #Plot
    print numpy.nanmax(deltas)
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(deltas.T,origin='lower',cmap='jet',
                          xrange=[numpy.log10(Lmin),numpy.log10(Lmax)],
                          yrange=[-2,0.],
                          xlabel=r'$\log_{10} L$',
                          ylabel=r'$\log_{10}\left(\frac{E-E_c(L)}{E(\infty)-E_c(L)}\right)$',
                          colorbar=True,shrink=0.78,
                          zlabel=r'$\mathrm{Approximate\ focal\ length}$',
#                          interpolation='nearest',
                          vmin=0.,vmax=0.6)
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 22
0
def fitBroadSubsamples(sample,savename):
    # Setup the selection function
    setup_selection_function()
    # Load the data
    load_data(sample)
    # Do the fits
    global bf_exp, bf_brexp, bf_twoexp
    global ml_exp, ml_brexp, ml_twoexp
    global samples_exp, samples_brexp, samples_twoexp
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            bf_exp= pickle.load(savefile)
            bf_brexp= pickle.load(savefile)
            bf_twoexp= pickle.load(savefile)
            ml_exp= pickle.load(savefile)
            ml_brexp= pickle.load(savefile)
            ml_twoexp= pickle.load(savefile)
            samples_exp= pickle.load(savefile)
            samples_brexp= pickle.load(savefile)
            samples_twoexp= pickle.load(savefile)
    else:
        # Perform fits of
        # a) expplusconst
        bf_exp, samples_exp, ml_exp= fit(type='expplusconst')
        # b) brokenexpflare
        bf_brexp, samples_brexp, ml_brexp= fit(type='tribrokenexpflare')
        # c) brokentwoexp
        bf_twoexp, samples_twoexp, ml_twoexp= fit(type='tribrokentwoexp')
        save_pickles(savename,
                     bf_exp,bf_brexp,bf_twoexp,
                     ml_exp,ml_brexp,ml_twoexp,
                     samples_exp,samples_brexp,samples_twoexp)
    # Do the rest of the fits as justfit
    global bf_brexp_g15, ml_brexp_g15, bf_brexp_drim, ml_brexp_drim
    global bf_brexp_sale, ml_brexp_sale, bf_brexp_zero, ml_brexp_zero
    bf_brexp_g15, ml_brexp_g15= fit(type='tribrokenexpflare',dmap='green15',
                                    justfit=True,init=bf_brexp) 
    bf_brexp_drim, ml_brexp_drim= fit(type='tribrokenexpflare',dmap='drimmel03',
                                      justfit=True,init=bf_brexp)
    bf_brexp_sale, ml_brexp_sale= fit(type='tribrokenexpflare',dmap='sale14',
                                      justfit=True,init=bf_brexp)
    bf_brexp_zero, ml_brexp_zero= fit(type='tribrokenexpflare',dmap='zero',
                                      justfit=True,init=bf_brexp)
    return None
Exemplo n.º 23
0
def resultsToInit(options,args,boot=True):    
    #First calcDFResults
    out= calcDFResults(options,args,boot=boot)
    #Then store
    sol= []
    for ii in range(len(out['feh'])):
        sol.extend([numpy.log(out['hr'][ii]/_REFR0),
                    numpy.log(out['sr'][ii]/_REFV0),
                    numpy.log(out['sz'][ii]/_REFV0),
                    numpy.log(out['hsr'][ii]/_REFR0),
                    numpy.log(out['hsz'][ii]/_REFR0),
                    out['outfrac'][ii]])
    sol.extend([numpy.log(out['rd_m']),
                out['vc_m']/_REFV0,
                numpy.log(out['zh_m']),
                out['dlnvcdlnr_m']*30.,
                out['plhalo_m']])
    #Save
    save_pickles(options.init,sol)
    return None                      
Exemplo n.º 24
0
def plot_dustinfield(plotname,field,threshold=False):
    savefile= _SAVEFILE_MARSHALL
    savefile= savefile.replace('FIELD','%i' % field)
    # Grid
    ls= numpy.linspace(-1.75,1.75,_NL)+field
    bs= numpy.linspace(-1.75,1.75,_NB)
    if not os.path.exists(savefile):
        # Setup dust map
        dmap= mwdust.Marshall06(filter='2MASS H')
        plotthis= numpy.empty((_NL,_NB))
        for jj in range(_NB):
            print jj
            for ii in range(_NL):
                plotthis[ii,jj]= dmap(ls[ii],bs[jj],7.)
        save_pickles(savefile,plotthis)
    else:
        with open(savefile,'rb') as f:
            plotthis= pickle.load(f)
    # Remove outside the field
    tls= numpy.tile(ls,(_NB,1)).T
    tbs= numpy.tile(bs,(_NL,1))
    plotthis[(tls-field)**2.+tbs**2. > 1.5**2.]= numpy.nan
    if threshold:
        plotthis[plotthis > 1.4]= numpy.nan
    # Now plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm,
                          interpolation='nearest',
                          vmin=0.,vmax=2.,aspect=1.,
                          xrange=[ls[-1]+(ls[1]-ls[0])/2.,
                                  ls[0]-(ls[1]-ls[0])/2.],
                          yrange=[bs[0]-(bs[1]-bs[0])/2.,
                                  bs[-1]+(bs[1]-bs[0])/2.],
                          xlabel=r'$l\,\mathrm{(deg)}$',
                          ylabel=r'$b\,\mathrm{(deg)}$',
                          zlabel=r'$A_H\,(\mathrm{mag})$',
                          zorder=0)
    bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field,top_left=True,
                        color='k',size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
Exemplo n.º 25
0
def _get_pal5varypm():

    pal5varyc, cs = _get_pal5varyc()

    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varypm.pkl"

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]

    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            pms = pickle.load(savefile)
            pal5varypm = pickle.load(savefile)
    else:
        pms = np.arange(-0.3, 0.35, 0.05)
        pal5varypm = np.zeros(
            (len(pms), 4, pal5varyc[0].shape[1], pal5varyc[0].shape[2]))
        for ii, pm in enumerate(tqdm(pms)):
            pmra, pmdec = -2.296 + pm, -2.257 + 2.257 / 2.296 * pm
            t = pal5_util.predict_pal5obs(
                p_b15,
                1.0,
                multi=8,
                pmra=pmra,
                pmdec=pmdec,
                singlec=True,
                useTM=False,
            )
            for jj in range(4):
                pal5varypm[ii, jj] = t[jj][0]
        save_pickles(savefilename, pms, pal5varypm)

    return pal5varypm, pms
def plot_distanceareaintegral(savename,plotname,rmcenter=False,
                          onlygreen=False):
    if os.path.exists(savename):
        with open(savename,'rb') as savefile:
            area= pickle.load(savefile)
    else:
        # For samping over the absolute magnitude distribution
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi= healpy.pixelfunc.pix2ang(_NSIDE,
                                             numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                                             nest=False)
        cosb= numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceAreaIntegrand(\
                dust._GREEN15DISTS[x],cosb,Gsamples,rmcenter,onlygreen),
                                 range(len(dust._GREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(dust._GREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename,area)
    # Plot the power spectrum
    area= numpy.array(area)
    if True:       
        psdthis= ((area.T*dust._GREEN15DISTS**3.).T/numpy.sum((area.T*dust._GREEN15DISTS**3.),axis=1))
        psdx, psd= signal.periodogram(psdthis,
                                      fs=1./(dust._GREEN15DISTMODS[1]-dust._GREEN15DISTMODS[0]),
                                      detrend=lambda x: x,scaling='spectrum',
                                      axis=0)
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
        healpy.visufunc.mollview(numpy.log10(psd[-2]),
                                 nest=False,
                                 xsize=4000,min=-10.,max=-3.,
                                 cmap='gist_yarg',
                                 title="")
        bovy_plot.bovy_end_print(plotname)               
    return None
Exemplo n.º 27
0
def calc_pred_sigv(pred_file, avg_file, dfc, nls, nds, ls, ds):
    if os.path.exists(avg_file):
        savefile = open(avg_file, 'rb')
        ls = pickle.load(savefile)
        avg_pred = pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("avg file does not exist ...")
    if os.path.exists(pred_file):
        savefile = open(pred_file, 'rb')
        ls = pickle.load(savefile)
        sigv_pred = pickle.load(savefile)
        ii = pickle.load(savefile)
        savefile.close()
    else:
        sigv_pred = numpy.zeros(nls)
        ii = 0
    while ii < len(ls):
        sys.stdout.write('\r' + "Working on %i / %i ...\r" % (ii + 1, len(ls)))
        sys.stdout.flush()
        meanvlos2 = 0.
        norm = 0.
        for jj in range(nds):
            d, l = ds[jj], ls[ii] / 180. * numpy.pi
            R, theta, d, l = safe_dl_to_rphi(d, l)
            surfmass = dfc.surfacemassLOS(d, l, deg=False)
            vmass = dfc.targetSurfacemass(R)
            meanvlos2 += surfmass / vmass * (
                dfc.vmomentsurfacemass(R, 0, 2) * math.sin(theta + l)**2. +
                dfc.vmomentsurfacemass(R, 2, 0) * math.cos(theta + l)**2.)
            norm += surfmass
        sigv_pred[ii] = math.sqrt(meanvlos2 / norm - avg_pred[ii]**2.)
        print sigv_pred[ii]
        ii += 1
        save_pickles(pred_file, ls, sigv_pred, ii)
    sys.stdout.write('\r' + _ERASESTR + '\r')
    sys.stdout.flush()
    save_pickles(pred_file, ls, sigv_pred, ii)
Exemplo n.º 28
0
def calc_pred_sigv(pred_file,avg_file,dfc,nls,nds,ls,ds):
    if os.path.exists(avg_file):
        savefile= open(avg_file,'rb')
        ls= pickle.load(savefile)
        avg_pred= pickle.load(savefile)
        savefile.close()
    else:
        raise IOError("avg file does not exist ...")
    if os.path.exists(pred_file):
        savefile= open(pred_file,'rb')
        ls= pickle.load(savefile)
        sigv_pred= pickle.load(savefile)
        ii= pickle.load(savefile)
        savefile.close()
    else:
        sigv_pred= numpy.zeros(nls)
        ii= 0
    while ii < len(ls):
        sys.stdout.write('\r'+"Working on %i / %i ...\r" %(ii+1,len(ls)))
        sys.stdout.flush()
        meanvlos2= 0.
        norm= 0.
        for jj in range(nds):
            d,l= ds[jj], ls[ii]/180.*numpy.pi
            R,theta,d,l= safe_dl_to_rphi(d,l)
            surfmass= dfc.surfacemassLOS(d,l,deg=False)
            vmass= dfc.targetSurfacemass(R)
            meanvlos2+= surfmass/vmass*(dfc.vmomentsurfacemass(R,0,2)*math.sin(theta+l)**2.+dfc.vmomentsurfacemass(R,2,0)*math.cos(theta+l)**2.)
            norm+= surfmass
        sigv_pred[ii]= math.sqrt(meanvlos2/norm-avg_pred[ii]**2.)
        print sigv_pred[ii]
        ii+= 1
        save_pickles(pred_file,ls,sigv_pred,ii)
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    save_pickles(pred_file,ls,sigv_pred,ii)
Exemplo n.º 29
0
                              h_m2m=h_m2m,
                              prior=prior,
                              w_prior=w_init,
                              smooth=smooth,
                              st96smooth=st96smooth,
                              fit_omega=fit_omega,
                              sig_omega=sig_omega,
                              nmh_omega=nmh_omega,
                              skipomega=skipomega,
                              number_density=True,
                              xnm_m2m=xnm_m2m,
                              fit_xnm=fit_xnm,
                              skipxnm=skipxnm,
                              sig_xnm=sig_xnm,
                              nmh_xnm=nmh_xnm)
    save_pickles(savefilename, *out)
w_sam, xnm_sam, omega_sam, Q_sam, z_sam, vz_sam = out

### Output the results
print("#####   Results after sampling   #####")
# for test
s_low = -8
s_high = 8
#
print('xnm: best-fit, mean of samples unc.)', xnm_out[-1], numpy.mean(xnm_sam),
      numpy.std(xnm_sam))
xnm_m2m = xnm_out[-1]
omega_mean = numpy.mean(omega_sam)
omega_std = numpy.std(omega_sam)
print('omega: best-fit, mean of samples unc.)',omega_out[-1],omega_mean, \
      omega_std)
Exemplo n.º 30
0
def plot_szszvssz(options,args):
    """Plot sz^out/sz^in as a function of sz for various hr"""
    if len(args) == 0.:
        print "Must provide a savefilename ..."
        print "Returning ..."
        return None
    if os.path.exists(args[0]):
        #Load
        savefile= open(args[0],'rb')
        plotthis= pickle.load(savefile)
        szs= pickle.load(savefile)
        hrs= pickle.load(savefile)
        savefile.close()
    else:
        #Grid of models to test
        if options.subtype.lower() == 'sr':
            szs= numpy.linspace(options.srmin,options.srmax,options.nsz)
        else:
            szs= numpy.linspace(options.szmin,options.szmax,options.nsz)
        hrs= numpy.linspace(options.hrmin,options.hrmax,options.nhr)
        #Tile
        szs= numpy.tile(szs,(options.nhr,1)).T
        hrs= numpy.tile(hrs,(options.nsz,1))
        plotthis= numpy.zeros((options.nsz,options.nhr))
        #Setup potential and aA
        poptions= setup_options(None)
        #poptions.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        #params= [0.,0.,0.,0.,0.,0.,-1.16315,1.,-3.,0.4,0.]
        poptions.potential= 'btii'
        params= None
        #pot= MWPotential
        pot= setup_potential(params,poptions,1)
        if options.aAmethod.lower() == 'staeckel':
            aA= actionAngleStaeckel(pot=pot,delta=0.45,c=True)
        else:
            aA=actionAngleAdiabaticGrid(pot=pot,nR=16,nEz=16,nEr=31,nLz=31,
                                        zmax=1.,Rmax=5.)
        for ii in range(options.nsz):
            for jj in range(options.nhr):
                if options.subtype.lower() == 'sr':
                    qdf= quasiisothermaldf(hrs[ii,jj]/8.,
                                           szs[ii,jj]/220.,
                                           szs[ii,jj]/220./numpy.sqrt(3.),
                                           7./8.,1.,
                                           pot=pot,aA=aA)
                else:
                    qdf= quasiisothermaldf(hrs[ii,jj]/8.,
                                           szs[ii,jj]/220.*numpy.sqrt(3.),
                                           szs[ii,jj]/220.,
                                           7./8.,1.,
                                           pot=pot,aA=aA)
                if options.subtype.lower() == 'sr':
                    plotthis[ii,jj]= numpy.sqrt(qdf.sigmaR2(1.,0.8/8.,
                                                            gl=True))/szs[ii,jj]*220.
                else:
                    plotthis[ii,jj]= numpy.sqrt(qdf.sigmaz2(1.,0.8/8.,
                                                        gl=True))/szs[ii,jj]*220.
                print ii*options.nhr+jj+1, options.nhr*options.nsz, \
                    szs[ii,jj], hrs[ii,jj], plotthis[ii,jj]
        #Save
        save_pickles(args[0],plotthis,szs,hrs)
    #Now plot
    bovy_plot.bovy_print(fig_width=6.,
                         text_fontsize=20.,
                         legend_fontsize=24.,
                         xtick_labelsize=18.,
                         ytick_labelsize=18.,
                         axes_labelsize=24.)
    indx= 0
    lines= []
    colors= [cm.jet(ii/float(options.nhr-1.)*1.+0.) for ii in range(options.nhr)]
    lss= ['-' for ii in range(options.nhr)]#,'--','-.','..']
    labels= []
    if options.subtype.lower() == 'sr':
        lines.append(bovy_plot.bovy_plot(szs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         xrange=[10.,85.],
                                         yrange=[0.8,1.5],
                                         xlabel=r'$\sigma^{\mathrm{in}}_R\ \mathrm{at}\ R = 8\,\mathrm{kpc}$',
                                         ylabel=r'$\sigma^{\mathrm{out}}_R / \sigma^{\mathrm{in}}_R$'))
    else:
        lines.append(bovy_plot.bovy_plot(szs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         xrange=[10.,115.],
                                         yrange=[0.5,1.2],
                                         xlabel=r'$\sigma^{\mathrm{in}}_Z\ \mathrm{at}\ R = 8\,\mathrm{kpc}$',
                                         ylabel=r'$\sigma^{\mathrm{out}}_Z / \sigma^{\mathrm{in}}_Z$'))
    for indx in range(1,options.nhr):
        lines.append(bovy_plot.bovy_plot(szs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         overplot=True))
     #Add colorbar
    map = cm.ScalarMappable(cmap=cm.jet)
    map.set_array(hrs[0,:])
    map.set_clim(vmin=numpy.amin(hrs[0,:]),vmax=numpy.amax(hrs[0,:]))
    cbar= pyplot.colorbar(map,fraction=0.15)
    cbar.set_clim(numpy.amin(hrs[0,:]),numpy.amax(hrs[0,:]))
    cbar.set_label(r'$h_R\, (\mathrm{kpc})$')
    bovy_plot.bovy_end_print(options.plotfilename)
Exemplo n.º 31
0
     mean_savefilename= 'vhelio_l90.sav'
     if os.path.exists(mean_savefilename):
         savefile= open(mean_savefilename,'rb')
         plotds= pickle.load(savefile)
         plotvlos= pickle.load(savefile)
         savefile.close()
     else:
         vlos= numpy.zeros(nds)
         for jj in range(nds):
             print jj
             d,l= ds[jj], 90./180.*numpy.pi
             R,theta,d,l= safe_dl_to_rphi(d,l)
             vlos[jj]= dfc.meanvT(R)*math.sin(theta+l)
         plotds= ds*8.
         plotvlos= vlos*218.-218
         save_pickles(mean_savefilename,
                      plotds,plotvlos)
 #Now calculate the whole vlos distribution at each d
 dist_savefilename= 'vhelio_l90_dist.sav'
 if os.path.exists(dist_savefilename):
     savefile= open(dist_savefilename,'rb')
     plotds= pickle.load(savefile)
     plotvloss= pickle.load(savefile)
     vlos_dist= pickle.load(savefile)
     savefile.close()
 else:
     nvloss= 101
     vloss= numpy.linspace(-0.7,0.25,nvloss)
     vlos_dist= numpy.zeros((nds,nvloss))
     ra, dec= bovy_coords.lb_to_radec(90.,0.,degree=True)
     for ii in range(nds):
         print ii
Exemplo n.º 32
0
def test_windows(options):
    elems = [
        'C', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'S', 'K', 'Ca', 'Ti', 'V', 'Mn',
        'Fe', 'Ni', 'Ce', 'Co', 'Cr', 'Cu', 'Ge', 'Nd', 'P', 'Rb', 'Y'
    ]
    if options.savefilename is None or \
            not os.path.exists(options.savefilename):
        # Set default linelist for Turbospectrum or MOOG
        if options.linelist is None and options.moog:
            linelist = 'moog.201312161124.vac'
        elif options.linelist is None:
            linelist = 'turbospec.201312161124'
        else:
            linelist = options.linelist
        # set up a model atmosphere for the requested atmospheric parameters
        if options.arcturus:
            options.teff = 4286.
            options.logg = 1.66
            options.metals = -0.52
            options.am = 0.4
            options.cm = 0.09
            options.vm = 1.7
        atm = atlas9.Atlas9Atmosphere(teff=options.teff,
                                      logg=options.logg,
                                      metals=options.metals,
                                      am=options.am,
                                      cm=options.cm)
        # create baseline
        if options.moog:
            baseline= \
                apogee.modelspec.moog.synth(modelatm=atm,
                                            linelist=linelist,
                                            lsf='all',cont='aspcap',
                                            vmacro=6.,isotopes='arcturus',
                                            vmicro=options.vm)
        else:
            baseline= \
                apogee.modelspec.turbospec.synth(modelatm=atm,
                                                 linelist=linelist,
                                                 lsf='all',cont='aspcap',
                                                 vmacro=6.,isotopes='arcturus',
                                                 vmicro=options.vm)
        # Loop through elements
        elem_synspec = {}
        # Run through once to simulate all differences
        for elem in elems:
            # First check that this element has windows
            elemPath = apwindow.path(elem, dr=options.dr)
            if not os.path.exists(elemPath): continue
            # Simulate deltaAbu up and down
            print "Working on %s" % (elem.capitalize())
            abu = [atomic_number(elem), -options.deltaAbu, options.deltaAbu]
            if options.moog:
                synspec= \
                    apogee.modelspec.moog.synth(abu,
                                                modelatm=atm,
                                                linelist=linelist,
                                                lsf='all',cont='aspcap',
                                                vmacro=6.,
                                                isotopes='arcturus',
                                                vmicro=options.vm)
            else:
                synspec= \
                    apogee.modelspec.turbospec.synth(abu,
                                                     modelatm=atm,
                                                     linelist=linelist,
                                                     lsf='all',cont='aspcap',
                                                     vmacro=6.,
                                                     isotopes='arcturus',
                                                     vmicro=options.vm)
            elem_synspec[elem] = synspec
        if not options.savefilename is None:
            save_pickles(options.savefilename, baseline, elem_synspec)
    else:
        with open(options.savefilename, 'rb') as savefile:
            baseline = pickle.load(savefile)
            elem_synspec = pickle.load(savefile)
    # Now run through the different elements again and plot windows for each
    # with elements that vary significantly
    colors = sns.color_palette("colorblind")
    plotelems = [
        elem if not elem in ['C', 'N', 'O', 'Fe'] else '%s1' % elem
        for elem in elems
    ]
    plotelems.extend(['C2', 'N2', 'O2', 'Fe2'])
    for pelem in plotelems:
        if '1' in pelem or '2' in pelem: elem = pelem[:-1]
        else: elem = pelem
        if not elem in elem_synspec: continue
        # Figure out which elements have significant variations in these
        # windows and always plot the element that should vary
        elemIndx = apwindow.tophat(elem, dr=options.dr)
        elemWeights = apwindow.read(elem, dr=options.dr)
        elemWeights /= numpy.nansum(elemWeights)
        # Start with the element in question
        splot.windows(1. + options.amplify *
                      (elem_synspec[elem][0] - baseline[0]),
                      pelem,
                      color=colors[0],
                      yrange=[0., 1.4],
                      plot_weights=True,
                      zorder=len(elems))
        splot.windows(1. + options.amplify *
                      (elem_synspec[elem][1] - baseline[0]),
                      pelem,
                      color=colors[0],
                      overplot=True,
                      zorder=len(elems))
        elem_shown = [elem]
        # Run through the rest to figure out the order
        elemVar = numpy.zeros(len(elems))
        for ii, altElem in enumerate(elems):
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            elemVar[ii] = 0.5 * numpy.nansum(
                (elem_synspec[altElem][0] - baseline[0])**2. * elemWeights)
            elemVar[ii] += 0.5 * numpy.nansum(
                (elem_synspec[altElem][1] - baseline[0])**2. * elemWeights)
        jj = 0
        sortindx = numpy.argsort(elemVar)[::-1]
        for altElem in numpy.array(elems)[sortindx]:
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            if numpy.fabs(\
                numpy.nanmax([(elem_synspec[altElem][0]-baseline[0])[elemIndx],
                            (elem_synspec[altElem][1]-baseline[0])[elemIndx]]))\
                            > options.varthreshold:
                jj += 1
                if jj >= len(colors): jj = len(colors) - 1
                elem_shown.append(altElem)
                splot.windows(1. + options.amplify *
                              (elem_synspec[altElem][0] - baseline[0]),
                              pelem,
                              color=colors[jj],
                              overplot=True,
                              zorder=len(elems) - jj)
                splot.windows(1. + options.amplify *
                              (elem_synspec[altElem][1] - baseline[0]),
                              pelem,
                              color=colors[jj],
                              overplot=True,
                              zorder=len(elems) - jj)
        t = pyplot.gca().transData
        fig = pyplot.gcf()
        for s, c in zip(elem_shown, colors[:jj + 1]):
            xc = 0.05
            if elem == 'K' or elem == 'Ce' or elem == 'Ge' or elem == 'Nd' \
                    or elem == 'Rb':
                xc = apwindow.waveregions(elem, dr=options.dr,
                                          pad=3)[0][0] - 15000. + 1.
            text = pyplot.text(xc,
                               1.2,
                               " " + (r"$\mathrm{%s}$" % s) + " ",
                               color=c,
                               transform=t,
                               size=16.,
                               backgroundcolor='w')
            text.draw(fig.canvas.get_renderer())
            ex = text.get_window_extent()
            t = transforms.offset_copy(text._transform,
                                       x=1.5 * ex.width,
                                       units='dots')
        # Save
        bovy_plot.bovy_end_print(options.plotfilename.replace('ELEM', pelem))
    return None
Exemplo n.º 33
0
v2max = 1000.0
dens_final= xnm_out[-1]*hom2m.compute_dens(z_m2m,zsun_true,z_out,h_m2m,w=w_out)
v2_final= hom2m.compute_v2(z_m2m,vz_m2m,zsun_true,z_out,h_m2m,w=w_out)
v_final= hom2m.compute_v(z_m2m,vz_m2m,zsun_true,z_out,h_m2m,w=w_out)

### Save the results in a file
# tempolary set "true" values
omegadm_true = omega_m2m
totmass_true = totmass_init
zh_true = zh_init
sigma_true = sigma_init

savefilename='xnmomega_BB19rhov2obs_colid'+str(cid)+'.sav'
save_pickles(savefilename,w_out,omega_out,xnm_out,z_m2m,vz_m2m,zsun_true,
             vzsun_true,data_dicts,z_pmock,z_vmock,vz_vmock,v_obs,v_obs_noise, \
             w_init,h_m2m,omega_m2m,xnm_m2m,zsun_m2m,\
             dens_init,v2_init,v_init,\
             nstep,step,tdyn,eps,Q,wevol,windx)

### Plot output
bovy_plot.bovy_print(axes_labelsize=19.,text_fontsize=14.,xtick_labelsize=15.,ytick_labelsize=15., fig_height=6.,fig_width=15.)
# density
plt.subplot(2,3,1)
bovy_plot.bovy_plot(z_out,dens_init,'-',semilogy=True,color=init_color,
                   xlabel=r'$\tilde{z}$',ylabel=r'$\nu_{\mathrm{obs}}(\tilde{z})$',
                   xrange=[zmin, zmax],yrange=[densmin,densmax],gcf=True)
bovy_plot.bovy_plot(z_obs,dens_obs,'o',semilogy=True,overplot=True,color=constraint_color)
bovy_plot.bovy_plot(z_out,dens_final,'-',semilogy=True,overplot=True,zorder=0,color=final_color)
plt.errorbar(z_obs,dens_obs,yerr=dens_obs_noise,marker='None',ls='none',color=constraint_color)
plt.yscale('log',nonposy='clip')
# gca().yaxis.set_major_formatter(FuncFormatter(
Exemplo n.º 34
0
def plot_vs_jkz(parser):
    options,args= parser.parse_args()
    if options.basti:
        zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04])
    elif options.parsec:
        zs= numpy.arange(0.0005,0.06005,0.0005)
    else:
        zs= numpy.arange(0.0005,0.03005,0.0005)
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        plotthis= pickle.load(savefile)
        jks= pickle.load(savefile)
        zs= pickle.load(savefile)
        savefile.close()
    else:
        njks= 101
        jks= numpy.linspace(0.5,0.8,njks)
        plotthis= numpy.zeros((njks,len(zs)))
        funcargs= (zs,options,njks,jks)
        multOut= multi.parallel_map((lambda x: indiv_calc(x,
                                                          *funcargs)),
                                    range(len(zs)),
                                    numcores=numpy.amin([64,len(zs),
                                                         multiprocessing.cpu_count()]))
        for ii in range(len(zs)):
            plotthis[:,ii]= multOut[ii]
        #Save
        save_pickles(args[0],plotthis,jks,zs)
    #Plot
    if options.type == 'sig':
        if options.band.lower() == 'age':
            if options.relative:
                raise NotImplementedError("relative age not implemented yet")
            else:
                vmin, vmax= 0.,.5
                zlabel= r'$\mathrm{FWHM} / 2\sqrt{2\,\ln 2}$'
        else:
            if options.relative:
                vmin, vmax= 0.8,1.2
                zlabel= r'$\mathrm{FWHM}/\mathrm{FWHM}_{\mathrm{fiducial}}$'
            else:
                vmin, vmax= 0., 0.4
                zlabel= r'$\mathrm{FWHM} / 2\sqrt{2\,\ln 2}$'
    elif options.type == 'mode':
        if options.band.lower() == 'age':
            if options.relative:
                raise NotImplementedError("relative age not implemented yet")
            else:
                vmin, vmax= 0.,1.
                zlabel= r'$\Delta\displaystyle\arg\!\max_{\substack{\log_{10}\mathrm{Age}}}{p(\log_{10}\mathrm{Age}|[J-K_s]_0)}$'
        else:
            if options.relative:
                vmin, vmax= -0.05,0.05
                zlabel= r'$\Delta\displaystyle\arg\!\max_{\substack{K_s}}{p(M_{K_s}|[J-K_s]_0)}$'
            else:
                vmin, vmax= -1.8, -1.5
                if options.band.lower() == 'h':
                    zlabel= r'$\displaystyle\arg\!\max_{\substack{H}}{p(M_{H}|[J-K_s]_0)}$'
                else:
                    zlabel= r'$\displaystyle\arg\!\max_{\substack{K_s}}{p(M_{K_s}|[J-K_s]_0)}$'
    if options.basti:#Remap the Zs
        zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04])
        regularzs= numpy.arange(0.0005,0.04005,0.0005)
        njks= len(jks)
        regularplotthis= numpy.zeros((njks,len(regularzs)))
        for jj in range(len(regularzs)):
            #Find z
            thisindx= numpy.argmin(numpy.fabs(regularzs[jj]-zs))
            for ii in range(njks):
                regularplotthis[ii,jj]= plotthis[ii,thisindx]
        zs= regularzs
        plotthis= regularplotthis
    if options.relative and os.path.exists(options.infilename):
        savefile= open(options.infilename,'rb')
        plotthisrel= pickle.load(savefile)
        savefile.close()
        if options.basti:
            plotthisrel= plotthisrel[:,:80]
        elif not options.parsec:
            plotthisrel= plotthisrel[:,:60]
        if options.type == 'mode':
            plotthis-= plotthisrel
        elif options.type == 'sig':
            plotthis/= plotthisrel
    bovy_plot.bovy_print()
    if options.type == 'sig':
        plotthis[numpy.isnan(plotthis)]= vmax
    if options.relative:
        #Only plot between the cuts
        for ii in range(plotthis.shape[0]):
            indx= zs >= rcmodel.jkzcut(jks[ii],upper=True)
            indx+= zs <= rcmodel.jkzcut(jks[ii],upper=False)
            plotthis[ii,indx]= numpy.nan
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          xrange=[jks[0],jks[-1]],
                          yrange=[zs[0],zs[-1]],
                          vmin=vmin,vmax=vmax,
                          xlabel=r'$(J-K_s)_0$',
                          ylabel=r'$Z$',
                          interpolation='nearest',
                          colorbar=True,
                          shrink=0.78,
                          zlabel=zlabel)
    #Overplot cuts
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks),
                        'w--',lw=2.,overplot=True)
    bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks,upper=True),
                        'w--',lw=2.,overplot=True)
    if options.basti:
        pyplot.annotate(r'$\mathrm{BaSTI}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif not options.parsec:
        pyplot.annotate(r'$\mathrm{Padova}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif options.imfmodel == 'kroupa2003':
        pyplot.annotate(r'$\mathrm{Kroupa\ (2003)\ IMF}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif 'expsfh' in args[0]:
        pyplot.annotate(r'$\mathrm{p(\mathrm{Age}) \propto e^{\mathrm{Age}/(8\,\mathrm{Gyr})}}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif not options.eta is None:
        pyplot.annotate(r'$\eta_{\mathrm{Reimers}} = %.1f$' % options.eta,
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    elif False:
        pyplot.annotate(r'$\mathrm{Padova}$',
                        (0.5,1.08),xycoords='axes fraction',
                        horizontalalignment='center',
                        verticalalignment='top',size=16.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
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)))],
        ))
Exemplo n.º 36
0
def plot_powspec(dist, basename, plotname):
    # Density
    G0 = 0.68 + dust.dist2distmod(dist)
    densname = basename + '_D%.1f_denscl.sav' % dist
    if not os.path.exists(densname):
        densmap = densprofiles.healpixelate(dist,
                                            densprofiles.expdisk,
                                            [1. / 3., 1. / 0.3],
                                            nside=_NSIDE,
                                            nest=False)
        denscl = healpy.sphtfunc.anafast(densmap, pol=False)
        densmap2 = densprofiles.healpixelate(dist,
                                             densprofiles.expdisk,
                                             [1. / 2., 1. / 0.9],
                                             nside=_NSIDE,
                                             nest=False)
        denscl2 = healpy.sphtfunc.anafast(densmap2, pol=False)
        ell = numpy.arange(len(denscl))
        save_pickles(densname, ell, denscl, densmap, denscl2, densmap2)
    else:
        with open(densname, 'rb') as savefile:
            ell = pickle.load(savefile)
            denscl = pickle.load(savefile)
            densmap = pickle.load(savefile)
            denscl2 = pickle.load(savefile)
            densmap2 = pickle.load(savefile)
    # dust map Cl and cross-power with dens
    combinedname = basename + '_D%.1f_combinedcl.sav' % dist
    bestfitloaded = False
    if os.path.exists(combinedname):
        with open(combinedname, 'rb') as savefile:
            ell = pickle.load(savefile)
            combinedcl = pickle.load(savefile)
            combinedcr = pickle.load(savefile)
            combinedmcl = pickle.load(savefile)
            combinedmcr = pickle.load(savefile)
            combinedmcr2 = pickle.load(savefile)
            bestfitloaded = True
    if not bestfitloaded:
        # do the best-fit
        combinedmap = dust.load_combined(dist, nest=False, nside_out=_NSIDE)
        print numpy.sum(numpy.isnan(combinedmap))
        combinedmap[numpy.isnan(combinedmap)] = 0.
        # Sample over the distribution of MG
        combinedmask = numpy.zeros_like(combinedmap)
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        print "Computing effective selection function"
        for jj in range(_NGSAMPLES):
            combinedmask+= ((combinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                *(combinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
        combinedmask /= _NGSAMPLES
        print "Computing Cl of extinction map"
        combinedcl = healpy.sphtfunc.anafast(combinedmap, pol=False)
        print "Computing cross of extinction map w/ densmap"
        combinedcr = healpy.sphtfunc.anafast(combinedmap,
                                             map2=densmap,
                                             pol=False)
        print "Computing Cl of effective selection function"
        combinedmcl = healpy.sphtfunc.anafast(combinedmask, pol=False)
        print "Computing cross of effective selection function w/ densmap"
        combinedmcr = healpy.sphtfunc.anafast(combinedmask,
                                              map2=densmap,
                                              pol=False)
        print "Computing cross of effective selection function w/ densmap2"
        combinedmcr2 = healpy.sphtfunc.anafast(combinedmask,
                                               map2=densmap2,
                                               pol=False)
        # Save
        save_pickles(combinedname, ell, combinedcl, combinedcr, combinedmcl,
                     combinedmcr, combinedmcr2)
        gc.collect()
    # Plot (2l+1)Cl!!
    # Can smooth the masked power spectrum, perhaps underplot the non-smoothed in gray
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(combinedmcl)[1:],k=3,s=300.)
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(numpy.fabs(combinedmcr))[1:],k=3,s=10000.)
    # First plot the power-spectrum, then the cross-correlation, then the
    # cumulative sum
    bovy_plot.bovy_print(fig_height=3.)
    yrange = [10.**-12., 20.],
    line1 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) * combinedcl[1:],
                                'k-',
                                loglog=True,
                                ylabel=r'$(2\ell+1)\,C_\ell$',
                                xrange=[0.5, 20000],
                                yrange=yrange,
                                zorder=3)
    line2 = bovy_plot.bovy_plot(ell[2::2],
                                (2. * ell[2::2] + 1.) * denscl[2::2],
                                'b-',
                                overplot=True)
    line3 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) * combinedmcl[1:],
                                'r-',
                                overplot=True)
    # Add legend
    if dist == 5.:
        pyplot.legend(
            (line2[0], line1[0], line3[0]),
            (r'$\mathrm{exp.\ disk\ w/}$' + '\n' +
             r'$h_R = 3\,\mathrm{kpc},$' + '\n' + r'$h_Z = 0.3\,\mathrm{kpc}$',
             r'$\mathrm{extinction\ map}$',
             r'$\mathrm{effective\ selection\ function}$'),
            loc='lower left',
            bbox_to_anchor=(.02, .02),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
        bovy_plot.bovy_text(r'$\mathrm{power\ spectrum}$',
                            top_right=True,
                            size=16.)
    nullfmt = NullFormatter()  # no labels
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname)
    # Cross-correlation
    bovy_plot.bovy_print(fig_height=3.)
    line1 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) *
                                numpy.fabs(combinedcr[1:]),
                                'k-',
                                loglog=True,
                                ylabel=r'$(2\ell+1)\,C^{\mathrm{cross}}_\ell$',
                                xrange=[0.5, 20000],
                                yrange=yrange,
                                zorder=1)
    line2 = bovy_plot.bovy_plot(ell[1:], (2. * ell[1:] + 1.) *
                                numpy.fabs(combinedmcr[1:]),
                                'r-',
                                overplot=True,
                                zorder=2)
    # Add legend
    if dist == 5.:
        pyplot.legend((line1[0], line2[0]),
                      (r'$\mathrm{extinction\ map}$',
                       r'$\mathrm{effective\ selection}$' + '\n' +
                       r'$\mathrm{function}$'),
                      loc='lower left',
                      bbox_to_anchor=(.02, .02),
                      numpoints=8,
                      prop={'size': 14},
                      frameon=False)
        bovy_plot.bovy_text(r'$\mathrm{cross\ power\ spectrum\ w/\ density}$',
                            top_right=True,
                            size=16.)
    #sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],
    #                                 numpy.log(numpy.fabs(combinedmcr))[1:],
    #                                 k=3,s=100000.)
    #bovy_plot.bovy_plot(ell[1:],
    #                    10.*(2.*ell[1:]+1.)*numpy.exp(sp(numpy.log(ell[1:]))),
    #                    'r-',overplot=True,zorder=2)
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname.replace('powspec', 'crosspowspec'))
    effvol = numpy.sum((2. * ell + 1.) * combinedmcr)
    #effvol2= numpy.sum((2.*ell+1.)*combinedmcr2)
    matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
    line1 = bovy_plot.bovy_plot(
        ell[1:],
        numpy.fabs(
            numpy.log(effvol) -
            numpy.log(numpy.cumsum((2. * ell + 1.) * combinedmcr)))[1:],
        'k-',
        loglog=True,
        xlabel=r'$\ell$',
        ylabel=
        r'$\left|\Delta\ln\sum_{\ell}\sum_{m}\nu_{*,\ell m}\,\textswab{S}_{\ell m}\right|$',
        xrange=[0.5, 20000],
        yrange=[2. * 10.**-13., 20.],
        zorder=3)
    """
    line2= bovy_plot.bovy_plot(ell[1:],
                               numpy.fabs(numpy.log(effvol)
                                          -numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr))
                                          -numpy.log(effvol2)
                                          +numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr2)))[1:],
                               'k--',loglog=True,
                               overplot=True,zorder=2)
    # Add legend
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{exp.\ disk\ top\ panel}$',
                   r'$\mathrm{relative\ wrt\ exp.\ disk\ w/}$'+'\n'+
                   r'$h_R = 2\,\mathrm{kpc}, h_Z = 0.9\,\mathrm{kpc}$'),
                   loc='lower right',#bbox_to_anchor=(.91,.375),
                   numpoints=8,
                   prop={'size':14},
                   frameon=False) 
    """
    if dist == 5.:
        bovy_plot.bovy_text(
            r'$\mathrm{error\ in}\ \ln\ \mathrm{effective\ area}$',
            top_right=True,
            size=16.)
    bovy_plot.bovy_end_print(plotname.replace('powspec', 'cumulcrosspowspec'))
    return None
Exemplo n.º 37
0
def skew0957(parser):
    (options,args)= parser.parse_args()
    if len(args) == 0:
        parser.print_help()
        return
    savefilename= args[0]
    #Read data
    if options.vanderriest:
        vA= VarQso('../data/0957-A.fits',band=options.band)
        vB= VarQso('../data/0957-B.fits',band=options.band)
    else:
        vA= VarQso('../data/L0957-A_%s.fits' % options.band,band=options.band)
        vB= VarQso('../data/L0957-B_%s.fits' % options.band,band=options.band)
    if not options.fitsfile is None and os.path.exists(options.fitsfile):
        fitsfile= open(options.fitsfile,'rb')
        paramsA= pickle.load(fitsfile)
        paramsB= pickle.load(fitsfile)
        paramsAB= pickle.load(fitsfile)
        fitsfile.close()
        vA.LCparams= paramsA
        vB.LCparams= paramsB
        vA.LCtype='powerlawSF'
        vB.LCtype='powerlawSF'
        vA.LCmean= 'const'
        vB.LCmean= 'const'
        vA.fitband= options.band
        vB.fitband= options.band
    else:
        #Fit for means
        print "Fitting SF for both images ..."
        vA.fit(options.band,mean='const')
        vB.fit(options.band,mean='const')
    #Load into single new VarQso
    newm= list(vA.m[options.band]-vA.LCparams['m'])
    newerrm= list(vA.err_m[options.band])
    newmjd= list(vA.mjd[options.band])
    newm.extend(list(vB.m[options.band]+nu.mean(vA.m[options.band])
                                 -nu.mean(vB.m[options.band])-vB.LCparams['m']))
    newerrm.extend(list(vB.err_m[options.band]))
    newmjd.extend(list(vB.mjd[options.band]-417./365.25))#shift lagged B
    v= VarQso(newmjd,newm,newerrm,band=options.band,medianize=False)
    if not options.fitsfile is None and os.path.exists(options.fitsfile):
        v.LCparams= paramsAB
        v.LCtype='powerlawSF'
        v.LCmean= 'zero'
        v.fitband= options.band
        v.LC= LCmodel(trainSet=v._build_trainset(options.band),
                      type=v.LCtype,mean=v.LCmean,
                      init_params=paramsAB)
    else:
        v.fit(options.band)
    if not options.fitsfile is None and not os.path.exists(options.fitsfile):
        save_pickles(options.fitsfile,vA.LCparams,vB.LCparams,v.LCparams)
    taus= nu.arange(1.,201.,1.)/365.25
    thisskew= v.skew(taus,options.band,duration=0.7)
    thisgaussskews= nu.zeros((options.nsamples,len(taus)))
    print "Calculating simulated skews ..."
    for ii in range(options.nsamples):
        #First re-sample
        redshift= 1.41
        o= v.resample(v.mjd[options.band],band=options.band,noconstraints=True,
                      wedge=options.wedge,
                      wedgerate=options.wedgerate*365.25/(1.+redshift),
                      wedgetau=(1.+redshift)) #1yr
        o.LCparams= v.LCparams
        o.LC= v.LC
        o.fitband= v.fitband
        o.LCtype= v.LCtype
        o.LCmean= v.LCmean
        if options.wedge:
            o.LCparams['gamma']= 1.
            o.LCparams['logA']= o.LCparams['logA']\
                +nu.log(0.05**v.LCparams['gamma']/0.05)
            o.LCmean= 'zero' #bc we remove the mean when resampling wedge
            #Set up LC with correct params
            o.LC= LCmodel(trainSet=o._build_trainset(options.band),
                          type=o.LCtype,mean=o.LCmean,
                          init_params=o.LCparams)
        thisgaussskews[ii,:]= o.skew(taus,options.band,duration=0.7)
    skews= {}
    gaussskews= {}
    skews['0957']= thisskew
    gaussskews['0957']= thisgaussskews
    save_pickles(savefilename,skews,gaussskews,
                 None,options.band,None,taus)
    return None
Exemplo n.º 38
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
Exemplo n.º 39
0
def plotSurfRdfh(plotfilename):
    #Calculate the surface density profile for each trial potential, then plot in 2D
    if '.png' in plotfilename:
        savefilename= plotfilename.replace('.png','.sav')
    elif '.ps' in plotfilename:
        savefilename= plotfilename.replace('.ps','.sav')
    if not os.path.exists(savefilename):
        options= setup_options(None)
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        options.fitdvt= False
        rs= numpy.array([5.,8.,11.])
        rds= numpy.linspace(2.,3.4,_NRDS)
        fhs= numpy.linspace(0.,1.,_NFHS)
        surfz= numpy.zeros((len(rs),len(rds),len(fhs)))+numpy.nan
        ro= 1.
        vo= _VC/ _REFV0
        dlnvcdlnr= _DLNVCDLNR
        zh= _ZH
        for jj in range(len(rds)):
            for kk in range(len(fhs)):
                #Setup potential to calculate stuff
                potparams= numpy.array([numpy.log(rds[jj]/8.),vo,numpy.log(zh/8000.),fhs[kk],dlnvcdlnr])
                try:
                    pot= setup_potential(potparams,options,0,returnrawpot=True)
                except RuntimeError:
                    continue
                for ii in range(len(rs)):
                    if False:
                        surfz[ii,jj,kk]= -potential.evaluatezforces(rs[ii]/_REFR0,options.height/_REFR0/ro,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro/2./numpy.pi
                    else:
                        surfz[ii,jj,kk]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(rs[ii]/8.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
        #Save
        save_pickles(savefilename,rs,rds,fhs,surfz)
    else:
        savefile= open(savefilename,'rb')
        rs= pickle.load(savefile)
        rds= pickle.load(savefile)
        fhs= pickle.load(savefile)
        surfz= pickle.load(savefile)
        savefile.close()
    #Now plot
    bovy_plot.bovy_print()
    data = numpy.ma.masked_invalid(surfz[1,:,:])
    bovy_plot.bovy_dens2d(data.filled(data.mean()).T,
                          origin='lower',
                          cmap='jet',
                          colorbar=True,
                          shrink=0.775,
                          xlabel=r'$\mathrm{disk\ scale\ length}\,(\mathrm{kpc})$',
                          ylabel=r'$\mathrm{relative\ halo\ contribution\ to}\ V^2_c(R_0)$',
                          zlabel=r'$\Sigma(R_0,|Z| \leq 1.1\,\mathrm{kpc})\, (M_\odot\,\mathrm{pc}^{-2})$',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.])
    #Fix bad data
    bad_data = numpy.ma.masked_where(~data.mask, data.mask)
    bovy_plot.bovy_dens2d(bad_data.T,
                          origin='lower',
                          interpolation='nearest',
                          cmap=cm.gray_r,
                          overplot=True,
                          
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.])
    #Overlay contours of sigma at other R
    bovy_plot.bovy_dens2d(surfz[0,:,:].T,origin='lower',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.],
                          overplot=True,
                          justcontours=True,
                          contours=True,
                          cntrcolors='k',
                          cntrls='-')
    bovy_plot.bovy_dens2d(surfz[2,:,:].T,origin='lower',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.],
                          overplot=True,
                          justcontours=True,
                          contours=True,
                          cntrcolors='w',
#                          cntrlabel=True,
                          cntrls='--')
    #Add labels
    bovy_plot.bovy_text(r'$\Sigma(R=5\,\mathrm{kpc})$'
                        +'\n'
                        +r'$\Sigma(R=11\,\mathrm{kpc})$',
                        bottom_left=True,size=14.)
    bovy_plot.bovy_plot([2.575,2.8],[0.15,0.31],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot([2.625,2.95],[0.06,0.1525],'-',color='0.5',overplot=True)
    #overplot actual gridpoints
    gridrds= numpy.linspace(2.,3.4,8)
    gridfhs= numpy.linspace(0.,1.,16)
    for ii in range(len(gridrds)):
        bovy_plot.bovy_plot(gridrds[ii]+numpy.zeros(len(gridfhs)),
                            gridfhs,
                            's',
                            color='w',ms=3.,overplot=True,
                            markeredgecolor='none')
    bovy_plot.bovy_end_print(plotfilename)
    return None
Exemplo n.º 40
0
def plot_hzszq(options,args):
    """Plot sz,hz, q"""
    if len(args) == 0.:
        print "Must provide a savefilename ..."
        print "Returning ..."
        return None
    nqs, nszs, nhzs= 31, 51, 51
    #nqs, nszs, nhzs= 5,5,5
    if os.path.exists(args[0]):
        #Load
        savefile= open(args[0],'rb')
        hzs= pickle.load(savefile)
        szs= pickle.load(savefile)
        qs= pickle.load(savefile)
        savefile.close()
    else:
        qs= numpy.linspace(0.5,1.,nqs)
        szs= numpy.linspace(15.,50.,nszs)
        hzs= numpy.zeros((nqs,nszs))
        for ii in range(nqs):
            print "Working on potential %i / %i ..." % (ii+1,nqs)
            #Setup potential
            lp= LogarithmicHaloPotential(normalize=1.,q=qs[ii])
            if options.aAmethod.lower() == 'staeckel':
                aA= actionAngleStaeckel(pot=lp,delta=0.45,c=True)
            else:
                aA=actionAngleAdiabaticGrid(pot=pot,nR=16,nEz=16,nEr=31,nLz=31,
                                            zmax=1.,Rmax=5.)
            for jj in range(nszs):
                qdf= quasiisothermaldf(options.hr/8.,2.*szs[jj]/220.,
                                       szs[jj]/220.,7./8.,7./8.,pot=lp,
                                       aA=aA,cutcounter=True)    
                hzs[ii,jj]= qdf.estimate_hz(1.,z=0.125)
        #Save
        save_pickles(args[0],hzs,szs,qs)
    #Re-sample
    hzsgrid= numpy.linspace(50.,1500.,nhzs)/8000.
    qs2d= numpy.zeros((nhzs,nszs))
    for ii in range(nszs):
        interpQ= interpolate.UnivariateSpline(hzs[:,ii],qs,k=3)
        qs2d[:,ii]= interpQ(hzsgrid)
        qs2d[(hzsgrid < hzs[0,ii]),ii]= numpy.nan
        qs2d[(hzsgrid > hzs[-1,ii]),ii]= numpy.nan
    #Now plot
    bovy_plot.bovy_print(fig_width=6.,
                         text_fontsize=20.,
                         legend_fontsize=24.,
                         xtick_labelsize=18.,
                         ytick_labelsize=18.,
                         axes_labelsize=24.)
    bovy_plot.bovy_dens2d(qs2d.T,origin='lower',cmap='jet',
                          interpolation='gaussian',
#                          interpolation='nearest',
                          ylabel=r'$\sigma_z\ [\mathrm{km\,s}^{-1}]$',
                          xlabel=r'$h_z\ [\mathrm{pc}]$',
                          zlabel=r'$\mathrm{flattening}\ q$',
                          yrange=[szs[0],szs[-1]],
                          xrange=[8000.*hzsgrid[0],8000.*hzsgrid[-1]],
#                          vmin=0.5,vmax=1.,
                           contours=False,
                           colorbar=True,shrink=0.78)
    _OVERPLOTMAPS= True
    if _OVERPLOTMAPS:
        fehs= monoAbundanceMW.fehs()
        afes= monoAbundanceMW.afes()
        npops= len(fehs)
        mapszs= []
        maphzs= []
        for ii in range(npops):
            thissz, thiserr= monoAbundanceMW.sigmaz(fehs[ii],afes[ii],err=True)
            if thiserr/thissz > 0.1:
                continue
            thishz, thiserr= monoAbundanceMW.hz(fehs[ii],afes[ii],err=True)
            if thiserr/thishz > 0.1:
                continue
            mapszs.append(thissz)
            maphzs.append(thishz)
        mapszs= numpy.array(mapszs)
        maphzs= numpy.array(maphzs)
        bovy_plot.bovy_plot(maphzs,mapszs,'ko',overplot=True,mfc='none',mew=1.5)
    bovy_plot.bovy_text(r'$h_R = %i\,\mathrm{kpc}$' % int(options.hr),
                        bottom_right=True)
    bovy_plot.bovy_end_print(options.plotfilename)
Exemplo n.º 41
0
def plot_hrhrvshr(options,args):
    """Plot hr^out/hr^in as a function of hr for various sr"""
    if len(args) == 0.:
        print "Must provide a savefilename ..."
        print "Returning ..."
        return None
    if os.path.exists(args[0]):
        #Load
        savefile= open(args[0],'rb')
        plotthis= pickle.load(savefile)
        hrs= pickle.load(savefile)
        srs= pickle.load(savefile)
        savefile.close()
    else:
        #Grid of models to test
        hrs= numpy.linspace(options.hrmin,options.hrmax,options.nhr)
        srs= numpy.linspace(options.srmin,options.srmax,options.nsr)
        #Tile
        hrs= numpy.tile(hrs,(options.nsr,1)).T
        srs= numpy.tile(srs,(options.nhr,1))
        plotthis= numpy.zeros((options.nhr,options.nsr))
        #Setup potential and aA
        poptions= setup_options(None)
        #poptions.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        #params= [0.,0.,0.,0.,0.,0.,-1.16315,1.,-3.,0.4,0.]
        poptions.potential= 'btii'
        params= None
        #pot= MWPotential
        pot= setup_potential(params,poptions,1)
        if options.aAmethod.lower() == 'staeckel':
            aA= actionAngleStaeckel(pot=pot,delta=0.45,c=True)
        else:
            aA=actionAngleAdiabaticGrid(pot=pot,nR=16,nEz=16,nEr=31,nLz=31,
                                        zmax=1.,Rmax=5.)
        for ii in range(options.nhr):
            for jj in range(options.nsr):
                qdf= quasiisothermaldf(hrs[ii,jj]/8.,srs[ii,jj]/220.,
                                       srs[ii,jj]/numpy.sqrt(3.)/220.,
                                       7./8.,1.,
                                       pot=pot,aA=aA)
                plotthis[ii,jj]= qdf.estimate_hr(1.,z=0.8/8.,
                                                 dR=0.33,
                                                 gl=True)/hrs[ii,jj]*8.
                print ii*options.nsr+jj+1, options.nsr*options.nhr, \
                    hrs[ii,jj], srs[ii,jj], plotthis[ii,jj]
        #Save
        save_pickles(args[0],plotthis,hrs,srs)
    #Now plot
    bovy_plot.bovy_print(fig_width=6.,
                         text_fontsize=20.,
                         legend_fontsize=24.,
                         xtick_labelsize=18.,
                         ytick_labelsize=18.,
                         axes_labelsize=24.)
    indx= 0
    lines= []
    colors= [cm.jet(ii/float(options.nsr-1.)*1.+0.) for ii in range(options.nsr)]
    lss= ['-' for ii in range(options.nsr)]#,'--','-.','..']
    labels= []
    lines.append(bovy_plot.bovy_plot(hrs[:,indx],plotthis[:,indx],
                                     color=colors[indx],ls=lss[indx],
                                     xrange=[0.5,5.5],
                                     yrange=[0.,2.],
                                     xlabel=r'$h^{\mathrm{in}}_R\ \mathrm{at}\ 8\,\mathrm{kpc}$',
                                     ylabel=r'$h^{\mathrm{out}}_R / h^{\mathrm{in}}_R$'))
    labels.append(r'$\sigma_R = %.0f \,\mathrm{km\,s}^{-1}$' % srs[0,indx])
    for indx in range(1,options.nsr):
        lines.append(bovy_plot.bovy_plot(hrs[:,indx],plotthis[:,indx],
                                         color=colors[indx],ls=lss[indx],
                                         overplot=True))
        labels.append(r'$\sigma_R = %.0f \,\mathrm{km\,s}^{-1}$' % srs[0,indx])
    """
    #Legend
    pyplot.legend(lines,#(line1[0],line2[0],line3[0],line4[0]),
                  labels,#(r'$v_{bc} = 0$',
#                   r'$v_{bc} = 1\,\sigma_{bc}$',
#                   r'$v_{bc} = 2\,\sigma_{bc}$',
#                   r'$v_{bc} = 3\,\sigma_{bc}$'),
                  loc='lower right',#bbox_to_anchor=(.91,.375),
                  numpoints=2,
                  prop={'size':14},
                  frameon=False)
    """
     #Add colorbar
    map = cm.ScalarMappable(cmap=cm.jet)
    map.set_array(srs[0,:])
    map.set_clim(vmin=numpy.amin(srs[0,:]),vmax=numpy.amax(srs[0,:]))
    cbar= pyplot.colorbar(map,fraction=0.15)
    cbar.set_clim(numpy.amin(srs[0,:]),numpy.amax(srs[0,:]))
    cbar.set_label(r'$\sigma_R \,(\mathrm{km\,s}^{-1})$')
    bovy_plot.bovy_end_print(options.plotfilename)
Exemplo n.º 42
0
def fitDirect():
    savefile = "pal5GC_100.sav"
    # Load data
    savefile = open(savefile, "rb")
    data = pickle.load(savefile)
    sR, svR, svT, sz, svz, sphi = data
    savefile.close()
    # Setup potential and DF grids
    vos = numpy.linspace(160.0, 280.0, 21) / _REFV0
    qs = numpy.linspace(0.6, 1.4, 21)
    sigvs = numpy.exp(numpy.linspace(numpy.log(1.0 / _REFV0), numpy.log(1.0), 21))
    sigxs = numpy.exp(numpy.linspace(numpy.log(0.1 / _REFR0), numpy.log(1.0), 21))
    # Load progenitor orbit
    progo = progenitorOrbit(V0=_REFV0, R0=_REFR0)
    ts = numpy.linspace(0.0, 300.0, 1000)
    outfilename = "pal5GC_100_direct.sav"
    if not os.path.exists(outfilename):
        out = numpy.zeros((len(vos), len(qs), len(sigvs), len(sigxs)))
        ii, jj = 12, 0
    else:
        outfile = open(outfilename, "rb")
        out = pickle.load(outfile)
        ii = pickle.load(outfile)
        jj = pickle.load(outfile)
        ii, jj = 14, 0
        outfile.close()
    while ii < len(vos):
        progo = progenitorOrbit(V0=_REFV0 * vos[ii], R0=_REFR0)
        while jj < len(qs):
            print ii, jj
            # Setup some df
            if hasattr(progo, "orbit"):
                delattr(progo, "orbit")
            sdf = streamdf(
                sigvs[0],
                sigxs[0],
                pot=potential.LogarithmicHaloPotential(normalize=1.0, q=qs[jj]),
                progenitor=progo,
                ts=ts,
            )
            sX, sY, sZ, svX, svY, svZ = sdf.prepData4Direct(sR, svR / vos[ii], svT / vos[ii], sz, svz / vos[ii], sphi)
            for kk in range(len(sigvs)):
                for ll in range(len(sigxs)):
                    sdf = streamdf(
                        sigvs[kk],
                        sigxs[ll],
                        pot=potential.LogarithmicHaloPotential(normalize=1.0, q=qs[jj]),
                        progenitor=progo,
                        ts=ts,
                    )
                    out[ii, jj, kk, ll] = sdf(sX, sY, sZ, svX, svY, svZ, rect=True, log=True) - 3.0 * len(
                        sX
                    ) * numpy.log(vos[ii])
            jj += 1
            save_pickles(outfilename, out, ii, jj)
        if ii != (len(vos) - 1):
            jj = 0
        ii += 1
        save_pickles(outfilename, out, ii, jj)
    save_pickles(outfilename, out, ii, jj)
    return None
Exemplo n.º 43
0

if __name__ == '__main__':
    parser = get_options()
    options, args = parser.parse_args()
    # Setup the streampepperdf object
    if not os.path.exists(options.streamsavefilename):
        timpacts= simulate_streampepper.parse_times(\
            options.timpacts,options.age)
        sdf_smooth = pal5_util.setup_pal5model(age=options.age)
        sdf_pepper = pal5_util.setup_pal5model(
            timpact=timpacts,
            hernquist=not options.plummer,
            age=options.age,
            length_factor=options.length_factor)
        save_pickles(options.streamsavefilename, sdf_smooth, sdf_pepper)
    else:
        with open(options.streamsavefilename, 'rb') as savefile:
            sdf_smooth = pickle.load(savefile)
            sdf_pepper = pickle.load(savefile)
    if options.recomputeall:
        options.recompute = True
        # recompute basic
        recompute(sdf_pepper, sdf_smooth, options)
        # Find and recompute batches
        allfilenames = glob.glob(options.outdens.replace('.dat', '.*.dat'))
        batches = numpy.array(
            [int(fn.split('.dat')[0].split('.')[-1]) for fn in allfilenames],
            dtype='int')
        for batch in batches:
            options.batch = batch
Exemplo n.º 44
0
def plot_logg_jk_apokasc(parser):
    options,args= parser.parse_args()
    #Setup Zs
    if os.path.exists(args[0]):
        savefile= open(args[0],'rb')
        outhist= pickle.load(savefile)
        hists= pickle.load(savefile)
        edgess= pickle.load(savefile)
        data= pickle.load(savefile)
        savefile.close()
    else:
        zs= numpy.arange(0.0005,0.03005,0.0005)
        if _DEBUG:
            zs= numpy.arange(0.0005,0.03005,0.005)
        fehs= isodist.Z2FEH(zs,zsolar=0.017)#0.017 for APOGEE analysis
        zs= zs[numpy.fabs(fehs-options.feh) < 0.2]
        if _DEBUG:
            zs= [zs[numpy.fabs(fehs-options.feh) < 0.2][0]]
        fehs= isodist.Z2FEH(zs,zsolar=0.017)   
        #Load the RC models for each feh individually
        rcms= []
        hists= []
        edgess= []
        for z in zs:
            print z
            trc= rcmodel.rcmodel(Z=z,loggmin=1.,loggmax=3.5,
                                 band=options.band,basti=options.basti,
                                 imfmodel=options.imfmodel,
                                 parsec=options.parsec)
            rcms.append(trc)
            sample= numpy.vstack([trc._sample[:,0],trc._loggs[:,0]]).T
            weights= trc._weights
            hist, edges= numpy.histogramdd(sample,weights=weights,bins=31,
                                           range=[[0.5,0.8],[1.,3.5]])
            hists.append(hist)
            edgess.append(edges)
        #Load APOKASC data
        data= apread.apokasc()
        indx= (data['KASC_RG_LOGG_SCALE_2'] > 1.)\
            *(data['KASC_RG_LOGG_SCALE_2'] < 3.5)\
            *(data['METALS'] > options.feh-0.2)\
            *(data['METALS'] <= options.feh+0.2)
        print "Using %i APOKASC objects ..." % (numpy.sum(indx))
        data= data[indx]
        ndata= numpy.sum(indx)
        #Stack predictions
        outhist= numpy.zeros_like(hists[0])
        for ii in range(ndata):
            zindx= numpy.argmin(numpy.fabs(fehs-data['METALS'][ii]))
            outhist+= hists[zindx]
        save_pickles(args[0],outhist,hists,edgess,data)
    #Normalize each J-K
    for ii in range(len(outhist[:,0])):
        outhist[ii,:]/= numpy.nanmax(outhist[ii,:])/numpy.nanmax(outhist)
        rev= copy.copy(outhist[ii,::-1]) #reverse, but in one go does not always work
        outhist[ii,:]= rev
    if True:
        #Reload apokasc data
        data= apread.apokasc()
        indx= (data['KASC_RG_LOGG_SCALE_2'] > 1.)\
            *(data['KASC_RG_LOGG_SCALE_2'] < 3.5)\
            *(data['METALS'] > options.feh-0.2)\
            *(data['METALS'] <= options.feh+0.2)
        data= data[indx]
    #Plot everything
    bovy_plot.bovy_print()
    bovy_plot.bovy_dens2d(outhist.T,origin='lower',cmap='gist_yarg',
                          xrange=[edgess[0][0][0],edgess[0][0][-1]],
                          yrange=[edgess[0][1][-1],edgess[0][1][0]],
                          aspect=(edgess[0][0][-1]-edgess[0][0][0])/float(edgess[0][1][-1]-edgess[0][1][0]),
                          xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$',
                          ylabel=r'$\mathrm{Seismic}\ \log g$',
                          shrink=0.78,
                          interpolation='nearest')
    #Overplot APOKASC data
    noseismo= data['SEISMO EVOL'] == 'UNKNOWN'
    if numpy.sum(noseismo) > 0:
        bovy_plot.bovy_plot(data['J0'][noseismo]-data['K0'][noseismo],
                            data['KASC_RG_LOGG_SCALE_2'][noseismo],'bo',
                            overplot=True,
                            mec='none',ms=3.)
    clumpseismo= data['SEISMO EVOL'] == 'CLUMP'
    if numpy.sum(clumpseismo) > 0:
        bovy_plot.bovy_plot(data['J0'][clumpseismo]-data['K0'][clumpseismo],
                            data['KASC_RG_LOGG_SCALE_2'][clumpseismo],'yo',
                            overplot=True,
                            mec='none',ms=4.5)
    noclumpseismo= (data['SEISMO EVOL'] == 'RGB') \
        + (data['SEISMO EVOL'] == 'DWARF/SUBGIANT')
    if numpy.sum(noclumpseismo) > 0:
        bovy_plot.bovy_plot(data['J0'][noclumpseismo]-data['K0'][noclumpseismo],
                            data['KASC_RG_LOGG_SCALE_2'][noclumpseismo],'ro',
                            overplot=True,
                            mec='none',ms=3.)
    bovy_plot.bovy_text(r'$%.1f < [\mathrm{M/H}] \leq %.1f$' % (options.feh-0.2,options.feh+0.2),
                        top_left=True,size=14.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Exemplo n.º 45
0
def combine_dustmap(picklename):
    if os.path.exists(picklename): return None
    ndists = len(_GREEN15DISTS)
    # First fill in with NSIDE = 512 for Marshall
    marshallmap = mwdust.Marshall06()
    nside_mar = 512
    mar_pix = numpy.arange(healpy.pixelfunc.nside2npix(nside_mar))
    mar_val = numpy.zeros((len(mar_pix), ndists)) + healpy.UNSEEN
    theta, phi= \
        healpy.pixelfunc.pix2ang(nside_mar,mar_pix,nest=True)
    bb = (numpy.pi / 2. - theta) / numpy.pi * 180.
    ll = phi / numpy.pi * 180.
    subIndx= (numpy.fabs(bb) < 10.125)\
        *((ll < 100.125)+(ll > 259.875))
    mar_pix = mar_pix[subIndx]
    mar_val = mar_val[subIndx]
    ll = ll[subIndx]
    ll[ll > 180.] -= 360.
    bb = bb[subIndx]
    for pp, dpix in enumerate(mar_pix):
        sys.stdout.write('\r' + "Working on pixel %i, %i remaining ...\r" %
                         (pp + 1, len(mar_pix) - pp))
        sys.stdout.flush()
        if _DRYISHRUN and pp > 100: break
        mar_val[pp] = marshallmap(ll[pp], bb[pp], _GREEN15DISTS)
    sys.stdout.write('\r' + _ERASESTR + '\r')
    sys.stdout.flush()
    # Now load Green15 and remove those pixels that fall within the Marshall map
    with h5py.File(os.path.join(_greendir, 'dust-map-3d.h5'),
                   'r') as greendata:
        pix_info = greendata['/pixel_info'][:]
        best_fit = greendata['/best_fit'][:]
    # Check whether any of these fall within the Marshall map
    theta, phi = healpy.pixelfunc.pix2ang(
        pix_info['nside'].astype('int32'),
        pix_info['healpix_index'].astype('int64'),
        nest=True)
    inMar= ((phi < 100.125*_DEGTORAD)+(phi > 259.875*_DEGTORAD))\
        *(numpy.fabs(numpy.pi/2.-theta) < 10.125*_DEGTORAD)
    best_fit[inMar] = healpy.UNSEEN
    nside_min = numpy.min(pix_info['nside'])
    nside_max = numpy.max(pix_info['nside'])
    # Fill in remaining gaps with Drimmel at NSIDE=256
    pix_drim = []
    pix_drim_nside = []
    val_drim = []
    drimmelmap = mwdust.Drimmel03()
    for nside_drim in 2**numpy.arange(8, int(numpy.log2(nside_max)) + 1, 1):
        tpix = numpy.arange(healpy.pixelfunc.nside2npix(nside_drim))
        rmIndx = numpy.zeros(len(tpix), dtype='bool')
        # Remove pixels that already have values at this or a higher level
        for nside in 2**numpy.arange(8, int(numpy.log2(nside_max)) + 1, 1):
            mult_factor = (nside / nside_drim)**2
            tgpix = pix_info['healpix_index'][pix_info['nside'] == nside]
            for offset in range(mult_factor):
                rmIndx[numpy.in1d(tpix * mult_factor + offset,
                                  tgpix,
                                  assume_unique=True)] = True
        # Remove pixels that already have values at a lower level
        for nside in 2**numpy.arange(int(numpy.log2(nside_min)),
                                     int(numpy.log2(nside_drim)), 1):
            mult_factor = (nside_drim / nside)**2
            # in Green 15
            tgpix = pix_info['healpix_index'][pix_info['nside'] == nside]
            rmIndx[numpy.in1d(tpix // mult_factor, tgpix,
                              assume_unique=False)] = True
            # In the current Drimmel
            tdpix = numpy.array(pix_drim)[numpy.array(pix_drim_nside) == nside]
            rmIndx[numpy.in1d(tpix // mult_factor, tdpix,
                              assume_unique=False)] = True
        # Also remove pixels that lie within the Marshall area
        theta, phi = healpy.pixelfunc.pix2ang(nside_drim, tpix, nest=True)
        inMar= ((phi < 100.125*_DEGTORAD)+(phi > 259.875*_DEGTORAD))\
            *(numpy.fabs(numpy.pi/2.-theta) < 10.125*_DEGTORAD)
        rmIndx[inMar] = True
        tpix = tpix[True - rmIndx]
        pix_drim.extend(tpix)
        pix_drim_nside.extend(nside_drim * numpy.ones(len(tpix)))
        ll = phi[True - rmIndx] / _DEGTORAD
        bb = (numpy.pi / 2. - theta[True - rmIndx]) / _DEGTORAD
        for pp in range(len(tpix)):
            sys.stdout.write(
                '\r' + "Working on level %i, pixel %i, %i remaining ...\r" %
                (nside_drim, pp + 1, len(tpix) - pp))
            sys.stdout.flush()
            val_drim.append(drimmelmap(ll[pp], bb[pp], _GREEN15DISTS))
            if _DRYISHRUN and pp > 1000: break
    sys.stdout.write('\r' + _ERASESTR + '\r')
    sys.stdout.flush()
    # Save
    g15Indx = best_fit[:, 0] != healpy.UNSEEN
    save_pickles(picklename, mar_pix, mar_val, pix_info['nside'][g15Indx],
                 pix_info['healpix_index'][g15Indx], best_fit[g15Indx],
                 pix_drim, pix_drim_nside, val_drim)
    return None
def plot_distanceintegral_smallpatch(savename, plotname):
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
    else:
        # Load the patch
        hpIndx, dmap = read_patch()
        # For samping over the absolute magnitude distribution
        iso = gaia_rc.load_iso()
        Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # l and b of the pixels
        theta, phi = healpy.pixelfunc.pix2ang(_NSIDE_HIRES, hpIndx, nest=False)
        cosb = numpy.sin(theta)
        area= multi.parallel_map(lambda x: distanceIntegrandHires(\
                _HIRESGREEN15DISTS[x],theta,phi,cosb,Gsamples,dmap),
                                 range(len(_HIRESGREEN15DISTS)),
                                 numcores=numpy.amin([16,
                                                      len(_HIRESGREEN15DISTS),
                                                      multiprocessing.cpu_count()]))

        save_pickles(savename, area)
    # Plot the power spectrum
    if True:
        psdx, psd = signal.periodogram(
            area * _HIRESGREEN15DISTS**3. /
            numpy.sum(area * _HIRESGREEN15DISTS**3.),
            fs=1. / (_HIRESGREEN15DISTMODS[1] - _HIRESGREEN15DISTMODS[0]),
            detrend=lambda x: x,
            scaling='spectrum')
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(psdx[1:],
                            psd[1:],
                            'k-',
                            loglog=True,
                            xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                            ylabel=r'$P_k$',
                            xrange=[0.04, 4.])
        bovy_plot.bovy_text(
            r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
            bottom_left=True,
            size=16.)
        bovy_plot.bovy_end_print(plotname)
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        bovy_plot.bovy_plot(
            _HIRESGREEN15DISTMODS,
            area * _HIRESGREEN15DISTS**3.,
            'k-',
            xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
            ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    spl = interpolate.InterpolatedUnivariateSpline(_HIRESGREEN15DISTMODS,
                                                   area *
                                                   _HIRESGREEN15DISTS**3.,
                                                   k=5)
    fthder = [spl.derivatives(dm)[4] for dm in _HIRESGREEN15DISTMODS]
    print "Simpson error= ", 0.5**4. / 180. * numpy.mean(
        numpy.fabs(fthder)) / integrate.simps(area * _HIRESGREEN15DISTS**3.,
                                              dx=0.5)
    return None
def save_stream_model_pickles(fname, setupfunc, timpact, leading):
    model = setupfunc(timpact=timpact, leading=leading)
    save_pickles(fname, model)
    return
Exemplo n.º 48
0
def plot_distanceintegral_fewfields(savename, plotname, apogee=False):
    #ls and bs of the patches
    ls = [280., 30., 12., 37.5, 90., 127.5, 30., 60., 20., -20., -40.]
    bs = [45., 4., 2., 0., 0., 0., 0., 0., 0., 0., 0.]
    radius = 1.49
    locs = [4214, 4244, 4378, 4312, 4242, 4318, 4240, 4241]  # for apogee
    # If we are doing APOGEE selection, load the APOGEE selection function
    if apogee:
        selectFile = '../savs/selfunc-nospdata.sav'
        if os.path.exists(selectFile):
            with open(selectFile, 'rb') as savefile:
                apo = pickle.load(savefile)
    if os.path.exists(savename):
        with open(savename, 'rb') as savefile:
            area = pickle.load(savefile)
            if apogee:
                area_cdens = pickle.load(savefile)
    else:
        if not apogee:
            # For samping over the absolute magnitude distribution
            iso = gaia_rc.load_iso()
            Gsamples = gaia_rc.sample_Gdist(iso, n=_NGSAMPLES)
        # Loop through each distance slice
        area = numpy.zeros((len(ls), len(dust._GREEN15DISTS)))
        if apogee:
            area_cdens = numpy.zeros((len(ls), len(dust._GREEN15DISTS)))
        for ii, dist in enumerate(dust._GREEN15DISTS):
            print "Working on distance %i: %f" % (ii, dist)
            G0 = 0.68 + dust.dist2distmod(dist)
            H0 = -1.49 + dust.dist2distmod(dist)
            # Load the dust map
            combinedmap = dust.load_combined(dist,
                                             nest=False,
                                             nside_out=_NSIDE)
            # Loop through a few patches
            theta, phi = healpy.pixelfunc.pix2ang(
                _NSIDE,
                numpy.arange(healpy.pixelfunc.nside2npix(_NSIDE)),
                nest=False)
            cosb = numpy.sin(theta)
            for ff, (ll, bb) in enumerate(zip(ls, bs)):
                if ff >= len(ls) - 3 * apogee: break
                vec = healpy.pixelfunc.ang2vec((90. - bb) * _DEGTORAD,
                                               ll * _DEGTORAD)
                ipixs = healpy.query_disc(_NSIDE,
                                          vec,
                                          radius * _DEGTORAD,
                                          inclusive=False,
                                          nest=False)
                ipixIndx = numpy.in1d(numpy.arange(
                    healpy.pixelfunc.nside2npix(_NSIDE)),
                                      ipixs,
                                      assume_unique=True)
                # Calculate the density
                densmap = densprofiles.expdisk(phi[ipixIndx],
                                               numpy.pi / 2. - theta[ipixIndx],
                                               dist * numpy.ones(len(ipixs)),
                                               glon=True,
                                               params=[1. / 3., 1. / 0.3])
                combinedmask = numpy.zeros(len(ipixs))
                tcombinedmap = combinedmap[ipixIndx]
                if apogee:
                    # Loop through the three cohorts
                    for c in ['short', 'medium', 'long']:
                        hmin = apo.Hmin(locs[ff], cohort=c)
                        hmax = apo.Hmax(locs[ff], cohort=c)
                        combinedmask+= ((tcombinedmap > (hmin-H0))\
                                            *(tcombinedmap < (hmax-H0))).astype('float')*apo(locs[ff],hmin+0.01)
                else:
                    for jj in range(_NGSAMPLES):
                        combinedmask+= ((tcombinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                            *(tcombinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
                combinedmask /= _NGSAMPLES
                # Compute cross correlation
                area[ff,ii]= float(numpy.sum(cosb[ipixIndx]*densmap\
                                                 *combinedmask))
                if apogee:
                    # Also store the approximation that the density is constant
                    cdens = densprofiles.expdisk(ll * _DEGTORAD,
                                                 bb * _DEGTORAD,
                                                 dist,
                                                 glon=True,
                                                 params=[1. / 3., 1. / 0.3])
                    area_cdens[ff,ii]= float(numpy.sum(cosb[ipixIndx]*cdens\
                                                           *combinedmask))
        if apogee:
            save_pickles(savename, area, area_cdens)
        else:
            save_pickles(savename, area)
    # Plot the power spectrum
    if True:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        colors = [
            'b', 'g', 'r', 'c', 'gold', 'm', 'k', 'orange', 'y', 'b', 'g'
        ]
        lss = ['-', '-', '-', '-', '-', '-', '-', '-', '-', '--', '--']
        for ff in range(len(ls)):
            if ff >= len(ls) - 3 * apogee: break
            psdx, psd = signal.periodogram(
                area[ff] * dust._GREEN15DISTS**3. /
                numpy.sum(area[ff] * dust._GREEN15DISTS**3.),
                fs=1. / (dust._GREEN15DISTMODS[1] - dust._GREEN15DISTMODS[0]),
                detrend=lambda x: x,
                scaling='spectrum')
            bovy_plot.bovy_plot(psdx[1:],
                                psd[1:],
                                '-',
                                loglog=True,
                                xlabel=r'$2\pi\,k_\mu\,(\mathrm{mag}^{-1})$',
                                ylabel=r'$P_k$',
                                xrange=[0.04, 4.],
                                color=colors[ff],
                                ls=lss[ff],
                                overplot=ff > 0)
            if ff == 0:
                bovy_plot.bovy_text(
                    r'$\mathrm{normalized}\ D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$',
                    bottom_left=True,
                    size=16.)
        bovy_plot.bovy_end_print(plotname)
    else:
        bovy_plot.bovy_print(fig_height=3.)
        matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{yfonts}"]
        for ff in range(len(ls)):
            if ff >= len(ls) - 3 * apogee: break
            bovy_plot.bovy_plot(
                dust._GREEN15DISTMODS,
                area[ff] * dust._GREEN15DISTS**3.,
                'k-',
                xlabel=r'$\mu\,(\mathrm{mag}^{-1})$',
                ylabel=r'$D^3\,\nu_*(\mu|\theta)\,\textswab{S}(\mu)$')
        bovy_plot.bovy_end_print(plotname)
    for ff in range(len(ls)):
        if ff >= len(ls) - 3 * apogee: break
        spl = interpolate.InterpolatedUnivariateSpline(dust._GREEN15DISTMODS,
                                                       area[ff] *
                                                       dust._GREEN15DISTS**3.,
                                                       k=5)
        fthder = [spl.derivatives(dm)[4] for dm in dust._GREEN15DISTMODS]
        print "Simpson error (%f,%f)= %g, volume = %g" % (
            ls[ff], bs[ff], 0.5**4. / 180. * numpy.mean(numpy.fabs(fthder)) /
            integrate.simps(area[ff] * dust._GREEN15DISTS**3., dx=0.5),
            numpy.sum(area[ff] * dust._GREEN15DISTS**3.))
    return None
Exemplo n.º 49
0
else:
    print(
        'targe mock data from a stablized disk after adding a DM background.')
    z_mock = z_start
    vz_mock = vz_start

m_mock = m_init
totmass_true = numpy.sum(m_mock)
omegadm = copy.deepcopy(omegadm_true)

# save the mock snapshot data
if Add_perturbation == True:
    savefilename = 'xnmomega_perturbed_target_mzvz.sav'
else:
    savefilename = 'xnmomega_stable_target_mzvz.sav'
save_pickles(savefilename, m_mock, z_mock, vz_mock, omegadm_true)

# The z positions of observation
z_obs = numpy.array([
    0.0, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, -0.15, -0.25, -0.35, -0.45, -0.55,
    -0.65
])
# z_obs= numpy.array([0.15, 0.35, 0.55, 0.75, 0.95, 1.05,
#                     -0.15, -0.35, -0.55, -0.75, -0.95, -1.05])
h_obs = h_def
# density
dens_obs = xnm_true * hom2m.compute_dens(
    z_mock, zsun_true, z_obs, h_obs, w=m_mock)
# dens_obs_noise= 0.01*dens_obs/numpy.sqrt(dens_obs)
# dens_obs_noise= 0.05*dens_obs
numpy.random.seed(203)
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")
Exemplo n.º 51
0
def pixelFitVel(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)]
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        fits= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        fits= []
        ii, jj= 0, 0
    #Sample?
    if options.mcsample:
        if ii < len(binned.fehedges)-1 and jj < len(binned.afeedges)-1:
            print "First do all of the fits ..."
            print "Returning ..."
            return None
        if os.path.exists(args[1]): #Load savefile
            savefile= open(args[1],'rb')
            samples= pickle.load(savefile)
            ii= pickle.load(savefile)
            jj= pickle.load(savefile)
            savefile.close()
        else:
            samples= []
            ii, jj= 0, 0
    #Model
    if options.model.lower() == 'hwr':
        like_func= _HWRLikeMinus
        pdf_func= _HWRLike
        step= [0.01,0.3,0.3,0.3,0.3]
        create_method=['full','step_out','step_out',
                       'step_out','step_out']
        isDomainFinite=[[True,True],[True,True],
                        [True,True],[True,True],
                        [False,True]]
        domain=[[0.,1.],[-10.,10.],[-100.,100.],[-100.,100.],
                [0.,4.6051701859880918]]
    elif options.model.lower() == 'hwrrz':
        like_func= _HWRRZLikeMinus
        pdf_func= _HWRRZLike
        step= [0.01,0.3,0.3,0.3,0.3,
               0.3,0.3,0.3,0.3,
               0.3,0.3,0.3]
        create_method=['full',
                       'step_out','step_out',
                       'step_out','step_out',
                       'step_out','step_out',
                       'step_out','step_out',
                       'step_out','step_out']
#                       'step_out']
        isDomainFinite=[[True,True],
                        [True,True],[True,True],[True,True],[False,True],
                        [True,True],[True,True],[True,True],[False,True],
                        [True,True],[True,True]]#,[True,True]]
        domain=[[0.,1.],
                [-10.,10.],[-100.,100.],[-100.,100.],[0.,4.6051701859880918],
                [-10.,10.],[-100.,100.],[-100.,100.],[0.,4.6051701859880918],
                [-2.,2.],[-10.,10.]]#,[-100.,100.]]
    elif options.model.lower() == 'isotherm':
        like_func= _IsothermLikeMinus
        pdf_func= _IsothermLike
        step= [0.01,0.05,0.3]
        create_method=['full','step_out','step_out']
        isDomainFinite=[[True,True],[False,False],
                        [False,True]]
        domain=[[0.,1.],[0.,0.],[0.,4.6051701859880918]]
    #Run through the bins
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                if options.mcsample: samples.append(None)
                else: fits.append(None)
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            print binned.feh(ii), binned.afe(jj), len(data)
            #Create XYZ and R, vxvyvz, cov_vxvyvz
            R= ((8.-data.xc)**2.+data.yc**2.)**0.5
            #Confine to R-range?
            if not options.rmin is None and not options.rmax is None:
                dataindx= (R >= options.rmin)*\
                    (R < options.rmax)
                data= data[dataindx]
                R= R[dataindx]
            XYZ= numpy.zeros((len(data),3))
            XYZ[:,0]= data.xc
            XYZ[:,1]= data.yc
            XYZ[:,2]= data.zc+_ZSUN
            if options.pivotmean:
                d= numpy.fabs((XYZ[:,2]-numpy.mean(numpy.fabs(XYZ[:,2]))))
            else:
                d= numpy.fabs((XYZ[:,2]-numpy.median(numpy.fabs(XYZ[:,2]))))
            vxvyvz= numpy.zeros((len(data),3))
            vxvyvz[:,0]= data.vxc
            vxvyvz[:,1]= data.vyc
            vxvyvz[:,2]= data.vzc
            cov_vxvyvz= numpy.zeros((len(data),3,3))
            cov_vxvyvz[:,0,0]= data.vxc_err**2.
            cov_vxvyvz[:,1,1]= data.vyc_err**2.
            cov_vxvyvz[:,2,2]= data.vzc_err**2.
            cov_vxvyvz[:,0,1]= data.vxvyc_rho*data.vxc_err*data.vyc_err
            cov_vxvyvz[:,0,2]= data.vxvzc_rho*data.vxc_err*data.vzc_err
            cov_vxvyvz[:,1,2]= data.vyvzc_rho*data.vyc_err*data.vzc_err
            if options.vr or options.vrz:
                #Rotate vxvyvz to vRvTvz
                cosphi= (8.-XYZ[:,0])/R
                sinphi= XYZ[:,1]/R
                vR= -vxvyvz[:,0]*cosphi+vxvyvz[:,1]*sinphi
                vT= vxvyvz[:,0]*sinphi+vxvyvz[:,1]*cosphi
                #Subtract mean vR
                vR-= numpy.mean(vR)
                vxvyvz[:,0]= vR               
                vxvyvz[:,1]= vT
                for rr in range(len(XYZ[:,0])):
                    rot= numpy.array([[cosphi[rr],sinphi[rr]],
                                      [-sinphi[rr],cosphi[rr]]])
                    sxy= cov_vxvyvz[rr,0:2,0:2]
                    sRT= numpy.dot(rot,numpy.dot(sxy,rot.T))
                    cov_vxvyvz[rr,0:2,0:2]= sRT
            #Fit this data
            #Initial condition
            if options.model.lower() == 'hwr':
                params= numpy.array([0.02,numpy.log(30.),0.,0.,numpy.log(6.)])
            elif options.model.lower() == 'hwrrz':
                params= numpy.array([0.02,numpy.log(30.),0.,0.,numpy.log(6.),
                                     numpy.log(30.),0.,0.,numpy.log(6.),
                                     0.2,0.])#,0.])
            elif options.model.lower() == 'isotherm':
                params= numpy.array([0.02,numpy.log(30.),numpy.log(6.)])
            if not options.mcsample:
                #Optimize likelihood
                params= optimize.fmin_powell(like_func,params,
                                             args=(XYZ,vxvyvz,cov_vxvyvz,R,d,
                                                   options.vr,options.vrz))
                if options.chi2:
                    #Calculate chi2 and chi2/dof
                    chi2, dof= like_func(params,XYZ,vxvyvz,cov_vxvyvz,R,d,options.vr,options.vrz,
                                    chi2=True)
                    dof-= len(params)
                    params.resize(len(params)+2)
                    params[-2]= chi2
                    params[-1]= chi2/dof
                print numpy.exp(params)
                fits.append(params)
            else:
                #Load best-fit params
                params= fits[jj+ii*binned.npixafe()]
                print numpy.exp(params)
                thesesamples= bovy_mcmc.markovpy(params,
                #thesesamples= bovy_mcmc.slice(params,
                                                 #step,
                                                 0.01,
                                                 pdf_func,
                                                 (XYZ,vxvyvz,cov_vxvyvz,R,d,
                                                  options.vr),#options.vrz),
                                                 #create_method=create_method,
                                                 isDomainFinite=isDomainFinite,
                                                 domain=domain,
                                                 nsamples=options.nsamples)
                #Print some helpful stuff
                printthis= []
                for kk in range(len(params)):
                    xs= numpy.array([s[kk] for s in thesesamples])
                    printthis.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs))))
                print printthis
                samples.append(thesesamples)               
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
            if options.mcsample: save_pickles(args[1],samples,ii,jj)
            else: save_pickles(args[0],fits,ii,jj)
            if jj == 0: #this means we've reset the counter 
                break
    if options.mcsample: save_pickles(args[1],samples,ii,jj)
    else: save_pickles(args[0],fits,ii,jj)
    return None
Exemplo n.º 52
0
def plotbestr(options,args):
    """Make a plot of a quantity's best-fit vs. FeH and aFe"""
    if options.sample.lower() == 'g':
        npops= 62
    elif options.sample.lower() == 'k':
        npops= 54
    if options.sample.lower() == 'g':
        savefile= open('binmapping_g.sav','rb')
    elif options.sample.lower() == 'k':
        savefile= open('binmapping_k.sav','rb')
    fehs= pickle.load(savefile)
    afes= pickle.load(savefile)
    savefile.close()
    #First calculate the derivative properties
    if not options.multi is None:
        derivProps= multi.parallel_map((lambda x: calcAllSurfErr(x,options,args)),
                                  range(npops),
                                  numcores=numpy.amin([options.multi,
                                                       npops,
                                                       multiprocessing.cpu_count()]))
    else:
        derivProps= []
        for ii in range(npops):
            derivProps.append(calcAllSurfErr(ii,options,args))
    #If a second argument is given, this gives a set of rs at which also to calculate the surface density
    if len(args) > 1:
        if os.path.exists(args[1]):
            surffile= open(args[1],'rb')
            altsurfrs= pickle.load(surffile)
            surffile.close()
            calcExtra= True
        else:
            raise IOError("extra savefilename with surface-densities has to exist when it is specified")
    else:
        calcExtra= False
    if not calcExtra: #Fiducial, for which we also calculate everything at the mean radius of each MAP
        #Load g orbits
        orbitsfile= 'gOrbitsNew.sav'
        savefile= open(orbitsfile,'rb')
        orbits= pickle.load(savefile)
        savefile.close()
        #Cut to S/N, logg, and EBV
        indx= (orbits.sna > 15.)*(orbits.logga > 4.2)*(orbits.ebv < 0.3)
        orbits= orbits[indx]
        #Load the orbits into the pixel structure
        pix= pixelAfeFeh(orbits,dfeh=0.1,dafe=0.05)
        #Now calculate meanr
        rmean= numpy.zeros(npops)
        for ii in range(npops):
            data= pix(fehs[ii],afes[ii])
            vals= data.densrmean*8.
            if False:#True:
                rmean[ii]= numpy.mean(vals)
            else:
                rmean[ii]= numpy.median(vals)
    #Load into plotthis
    plotthis= numpy.zeros(npops)+numpy.nan
    plotthis_y= numpy.zeros(npops)+numpy.nan
    plotthis_y_err= numpy.zeros(npops)+numpy.nan
    plotthiskz_y= numpy.zeros(npops)+numpy.nan
    plotthiskz_y_err= numpy.zeros(npops)+numpy.nan
    altplotthis= numpy.zeros(npops)+numpy.nan
    altplotthis_y= numpy.zeros(npops)+numpy.nan
    altplotthis_y_err= numpy.zeros(npops)+numpy.nan
    altplotthiskz_y= numpy.zeros(npops)+numpy.nan
    altplotthiskz_y_err= numpy.zeros(npops)+numpy.nan
    for ii in range(npops):
        if numpy.log(monoAbundanceMW.hr(fehs[ii],afes[ii],
                                         k=(options.sample.lower() == 'k')) /8.) > -0.5 \
                or (options.sample.lower() == 'g' and (ii < 0 or ii == 50)) \
                or (options.sample.lower() == 'k' and ii < 7):
            continue
        #Determine best-r
        #indx= numpy.argmin(derivProps[ii][:,2]/numpy.fabs(derivProps[ii][:,1]))
        indx= numpy.argmin(numpy.fabs(derivProps[ii][:,2]))
        if indx == 0: indx= int(numpy.floor(numpy.random.uniform()*10))
        plotthis[ii]= derivProps[ii][indx,0]
        plotthis_y[ii]= derivProps[ii][indx,1]
        plotthis_y_err[ii]= derivProps[ii][indx,3]
        plotthiskz_y[ii]= derivProps[ii][indx,4]
        plotthiskz_y_err[ii]= derivProps[ii][indx,5]
        if calcExtra:
            indx= numpy.argmin(numpy.fabs(derivProps[ii][:,0]-altsurfrs[ii]))
            altplotthis[ii]= derivProps[ii][indx,0]
            altplotthis_y[ii]= derivProps[ii][indx,1]
            altplotthis_y_err[ii]= derivProps[ii][indx,3]           
            altplotthiskz_y[ii]= derivProps[ii][indx,4]
            altplotthiskz_y_err[ii]= derivProps[ii][indx,5]           
        else:
            indx= numpy.argmin(numpy.fabs(derivProps[ii][:,0]-rmean[ii]))
            altplotthis[ii]= derivProps[ii][indx,0]
            altplotthis_y[ii]= derivProps[ii][indx,1]
            altplotthis_y_err[ii]= derivProps[ii][indx,3]           
            altplotthiskz_y[ii]= derivProps[ii][indx,4]
            altplotthiskz_y_err[ii]= derivProps[ii][indx,5]           
    #Now plot
    bovy_plot.bovy_print()
    monoAbundanceMW.plotPixelFunc(fehs,afes,plotthis,
                                  zlabel=r'$R_\Sigma\ (\mathrm{kpc})$')
    bovy_plot.bovy_end_print(options.outfilename)
    bovy_plot.bovy_print()
    print plotthis, plotthis_y
    bovy_plot.bovy_plot(plotthis,plotthis_y,'ko',
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$\Sigma(R,|Z| \leq 1.1\,\mathrm{kpc})\ (M_\odot\,\mathrm{pc}^{-2})$',
                        xrange=[4.,10.],
                        yrange=[10,1050.],#,numpy.nanmin(plotthis_y)-10.,
#                                numpy.nanmax(plotthis_y)+10.],
                        semilogy=True)
    pyplot.errorbar(plotthis,
                    plotthis_y,
                    yerr=plotthis_y_err,
                    elinewidth=1.,capsize=3,zorder=0,
                    color='k',linestyle='none')  
    trs= numpy.linspace(4.3,9.,1001)
    pyplot.plot(trs,72.*numpy.exp(-(trs-8.)/3.),'k--')
    pyplot.plot(trs,72.*numpy.exp(-(trs-8.)/2.),'k-.')
    pyplot.plot(trs,72.*numpy.exp(-(trs-8.)/4.),'k:')
    #Fit exponential
    #indx= (plotthis < 8.)
    #plotthis= plotthis[indx]
    #plotthis_y= plotthis_y[indx]
    #plotthis_y_err= plotthis_y_err[indx]
    exp_params= optimize.fmin_powell(expcurve,
                                     numpy.log(numpy.array([72.,2.5])),
                                     args=(plotthis,plotthis_y,plotthis_y_err))
    pyplot.plot(trs,numpy.exp(exp_params[0]-(trs-8.)/numpy.exp(exp_params[1])),
                'k-',lw=2.)
    print numpy.exp(exp_params) 
    bovy_plot.bovy_end_print(options.outfilename.replace('.png','_rvssurf.png'))
    #Save
    if calcExtra:
        save_pickles(options.outfilename.replace('.png','_rvssurf.sav'),
                     plotthis,plotthis_y,plotthis_y_err,
                     plotthiskz_y,plotthiskz_y_err,
                     altplotthis,altplotthis_y,altplotthis_y_err,
                     altplotthiskz_y,altplotthiskz_y_err)
    else:
        save_pickles(options.outfilename.replace('.png','_rvssurf.sav'),
                     plotthis,plotthis_y,plotthis_y_err,
                     plotthiskz_y,plotthiskz_y_err,
                     altplotthis,altplotthis_y,altplotthis_y_err,
                     altplotthiskz_y,altplotthiskz_y_err)
    return None        
 options.abcfile = options.datadir + options.abcfile
 print(options.abcfile, options.outsamp)
 # Setup the streampepperdf object
 print(_DATADIR + options.streamsavefilename,
       os.path.exists(_DATADIR + options.streamsavefilename))
 if not os.path.exists(_DATADIR + options.streamsavefilename):
     print('rebuilding pepper sampling')
     timpacts= simulate_streampepper.parse_times(\
         options.timpacts,options.age)
     sdf_smooth = pal5_util.setup_pal5model(age=options.age)
     sdf_pepper = pal5_util.setup_pal5model(
         timpact=timpacts,
         hernquist=not options.plummer,
         age=options.age,
         length_factor=options.length_factor)
     save_pickles(_DATADIR + options.streamsavefilename,
                  sdf_pepper)  #, sdf_smooth)
 else:
     with open(_DATADIR + options.streamsavefilename, 'rb') as savefile:
         print('loading streampepper pickle')
         #print options.streamsavefilename
         #sdf_smooth= pickle.load(savefile)
         if os.uname()[1] == 'yngve':
             sdf_pepper = pickle.load(savefile, encoding='latin1')
         if os.uname()[1] == 'hendel':
             sdf_pepper = pickle.load(savefile)
 if options.recomputeall:
     options.recompute = True
     # recompute basic
     recompute(sdf_pepper, options)
     # Find and recompute batches
     allfilenames = glob.glob(options.outdens.replace('.dat', '.*.dat'))
Exemplo n.º 54
0
def plot_rckinematics(plotfilename,subsun=False):
    #Set up 3 axes
    bovy_plot.bovy_print(fig_width=8.,axes_labelsize=14)
    axdx= 1./3.
    #APOGEE-RC observations
    tdy= (_RCYMAX-_RCYMIN+4.5)/(_RCXMAX-_RCXMIN+4.5)*axdx
    obsAxes= pyplot.axes([0.1,(1.-tdy)/2.,axdx,tdy])
    pyplot.sca(obsAxes)
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    data= data[indx]
    #Get velocity field
    pixrc= pixelize_sample.pixelXY(data,
                                   xmin=_RCXMIN-2.25,xmax=_RCXMAX+2.25,
                                   ymin=_RCYMIN-2.25,ymax=_RCYMAX+2.25,
                                   dx=_RCDX,dy=_RCDX)
    if subsun:
        vmin, vmax= 0., 250.
        pixrc.plot(lambda x: vlosgal(x),
                   func=lambda x: numpy.fabs(numpy.median(x)),
                   zlabel=r'$|\mathrm{median}\ V^{\mathrm{GC}}_{\mathrm{los}}|\,(\mathrm{km\,s}^{-1})$',
                   vmin=vmin,vmax=vmax)
    else:
        vmin, vmax= -75., 75.
        img= pixrc.plot('VHELIO_AVG',
                        vmin=vmin,vmax=vmax,overplot=True,
                        colorbar=False)
        resv= pixrc.plot('VHELIO_AVG',
                         justcalc=True,returnz=True) #for later
        bovy_plot.bovy_text(r'$\mathrm{typical\ uncertainty\!:}\ 3\,\mathrm{km\,s}^{-1}$',
                            bottom_left=True,size=8.25)
        bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',top_right=True,size=10.)
    pyplot.annotate(r'$\mathrm{APOGEE\!-\!RC\ data}$',
                    (0.5,1.09),xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',size=10.)
    pyplot.axis([pixrc.xmin,pixrc.xmax,pixrc.ymin,pixrc.ymax])
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$',
                              r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$')
    #Colorbar
    cbaxes = pyplot.axes([0.1625,(1.-tdy)/2.+tdy+0.065,2.*axdx-0.195,0.02])
    CB1= pyplot.colorbar(img,orientation='horizontal',
                         cax=cbaxes)#,ticks=[-16.,-8.,0.,8.,16.])
    CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.)
    #Now calculate the expected field
    xgrid= numpy.arange(_RCXMIN-2.25+_RCDX/2.,_RCXMAX+2.25+_RCDX/2.,_RCDX)
    ygrid= numpy.arange(_RCYMIN-2.25+_RCDX/2.,_RCYMAX+2.25+_RCDX/2.,_RCDX)
    xv,yv= numpy.meshgrid(xgrid,ygrid,indexing='ij')
    rs= numpy.sqrt(xv**2.+yv**2.)
    phis= numpy.arctan2(yv,xv)
    d,l= bovy_coords.rphi_to_dl_2d(rs/8.,phis)
    expec_vlos= numpy.empty((len(xgrid),len(ygrid)))
    for ii in range(len(xgrid)):
        for jj in range(len(ygrid)):
            expec_vlos[ii,jj]= modelvlosgal(rs[ii,jj],phis[ii,jj],l[ii,jj],
                                            vc=218.,vtsun=242.)
    modelAxes= pyplot.axes([0.03+axdx,(1.-tdy)/2.,axdx,tdy])
    pyplot.sca(modelAxes)
    xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$'
    ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$'
    indx= True-numpy.isnan(resv)
    plotthis= copy.copy(expec_vlos)
    plotthis[numpy.isnan(resv)]= numpy.nan #turn these off
    bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                          interpolation='nearest',
                          xlabel=xlabel,ylabel=ylabel,
                          xrange=[_RCXMIN-2.25,_RCXMAX+2.25],
                          yrange=[_RCYMIN-2.25,_RCYMAX+2.25],
                          contours=False,
                          vmin=vmin,vmax=vmax,overplot=True,zorder=3)
    if True:
       #Now plot the pixels outside the APOGEE data set
        plotthis= copy.copy(expec_vlos)
        plotthis[True-numpy.isnan(resv)]= numpy.nan #turn these off
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              alpha=0.3,
                              xrange=[_RCXMIN-2.25,_RCXMAX+2.25],
                              yrange=[_RCYMIN-2.25,_RCYMAX+2.25],
                              contours=False,
                              vmin=vmin,vmax=vmax,overplot=True,
                              zorder=0)
    pyplot.annotate(r'$\mathrm{Bovy\ et.\ al\ (2012)\ model}$',
                    (1.02,1.09),xycoords='axes fraction',
                    horizontalalignment='center',
                    verticalalignment='top',size=10.,zorder=3)
    pyplot.axis([_RCXMIN-2.25,_RCXMAX+2.25,_RCYMIN-2.25,_RCYMAX+2.25])
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(xlabel,r'$ $')
    #Finally, add a polar plot of the whole disk
    res= 51
    rmin, rmax= 0.2, 2.4
    xgrid= numpy.linspace(0.,2.*numpy.pi*(1.-1./res/2.),
                          2.*res)
    ygrid= numpy.linspace(rmin,rmax,res)
    nx= len(xgrid)
    ny= len(ygrid)
    savefile= 'expec_vlos.sav'
    if os.path.exists(savefile):
        savefile= open(savefile,'rb')
        expec_vlos= pickle.load(savefile)
        savefile.close()
    else:
        expec_vlos= numpy.zeros((nx,ny))
        for ii in range(nx):
            for jj in range(ny):
                R, phi= ygrid[jj], xgrid[ii]
                d,l= bovy_coords.rphi_to_dl_2d(R,phi)
                expec_vlos[ii,jj]= modelvlosgal(R*8.,phi,l,
                                                vc=218.,vtsun=242.)
        save_pickles(savefile,expec_vlos)
    plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2.,
                              xgrid[-1]+(xgrid[1]-xgrid[0])/2.,
                              len(xgrid)+1)
    plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2.,
                           ygrid[-1]+(ygrid[1]-ygrid[0])/2.,
                           len(ygrid)+1)
    fullmodelAxes= pyplot.axes([-0.05+2.*axdx,(1.-tdy)/2.,axdx,tdy],polar=True)
    ax= fullmodelAxes
    pyplot.sca(fullmodelAxes)
    vmin, vmax= -150., 150.
    zlabel= r'$\mathrm{line\!-\!of\!-\!sight\ velocity}\ (\mathrm{km\,s}^{-1})$'
    out= ax.pcolor(plotxgrid,plotygrid,expec_vlos.T,cmap='jet',
                   vmin=vmin,vmax=vmax,clip_on=False)
    shrink= 0.8
    if False:
        CB1= pyplot.colorbar(out,shrink=shrink)
        bbox = CB1.ax.get_position().get_points()
        CB1.ax.set_position(transforms.Bbox.from_extents(bbox[0,0]+0.025,
                                                         bbox[0,1],
                                                         bbox[1,0],
                                                         bbox[1,1]))
        CB1.set_label(zlabel)
    from matplotlib.patches import FancyArrowPatch
    arr= FancyArrowPatch(posA=(numpy.pi+0.1,1.8),
                         posB=(3*numpy.pi/2.+0.1,1.8),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (numpy.pi/8.-0.05),
                         shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(numpy.pi+0.17,1.7,r'$\mathrm{Galactic\ rotation}$',
                        rotation=-30.,size=9.)
    radii= numpy.array([0.5,1.,1.5,2.,2.5])
    labels= []
    for r in radii:
        ax.plot(numpy.linspace(0.,2.*numpy.pi,501,),
                numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5)
        labels.append(r'$%i$' % int(r*8.))
    pyplot.rgrids(radii,labels=labels,angle=147.5)
    thetaticks = numpy.arange(0,360,45)
    # set ticklabels location at x times the axes' radius
    ax.set_thetagrids(thetaticks,frac=1.16,backgroundcolor='w',zorder=3)
    bovy_plot.bovy_text(3.*numpy.pi/4.+0.06,2.095,r'$\mathrm{kpc}$',size=10.)
    pyplot.ylim(0.,2.8)
    #Plot the box
    xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101)
    ys= numpy.ones(101)*(_RCYMIN-2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101)
    ys= numpy.ones(101)*(_RCYMAX+2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101)
    xs= numpy.ones(101)*(_RCXMIN-2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the box
    ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101)
    xs= numpy.ones(101)*(_RCXMAX+2.25)
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    ax.plot(phis,rs,'--',lw=1.25,color='k')
    #Plot the connectors on the modelAxes
    xlow=-4.*8.
    ylow= 2.77*8.
    xs= numpy.linspace(xlow,(_RCXMAX+2.25),101)
    ys= (ylow-(_RCYMAX+2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2)
    line[0].set_clip_on(False)
    xlow=-4.*8.
    ylow= -2.77*8.
    xs= numpy.linspace(xlow,(_RCXMAX+2.25),101)
    ys= (ylow-(_RCYMIN-2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow
    rs= numpy.sqrt(xs**2.+ys**2.)/8.
    phis= numpy.arctan2(ys,xs)    
    line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2)
    line[0].set_clip_on(False)
    #Colorbar
    cbaxes = pyplot.axes([0.01+2.*axdx,(1.-tdy)/2.+tdy+0.065,axdx-0.125,0.02])
    CB1= pyplot.colorbar(out,orientation='horizontal',
                         cax=cbaxes,ticks=[-150.,-75.,0.,75.,150.])
    #CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.)
    bovy_plot.bovy_end_print(plotfilename,dpi=300)
    return None
Exemplo n.º 55
0
def calcMass(options,args):
    if options.sample.lower() == 'g':
        if options.select.lower() == 'program':
            raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True)
        elif options.select.lower() == 'fakebimodal':
            raw= read_gdwarfs(_FAKEBIMODALGDWARFFILE,
                              logg=True,ebv=True,sn=True)
            options.select= 'all'
        else:
            raw= read_gdwarfs(logg=True,ebv=True,sn=True)
    elif options.sample.lower() == 'k':
        if options.select.lower() == 'program':
            raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True)
        else:
            raw= read_kdwarfs(logg=True,ebv=True,sn=True)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    #Savefile
    if os.path.exists(args[0]):#Load savefile
        savefile= open(args[0],'rb')
        mass= pickle.load(savefile)
        ii= pickle.load(savefile)
        jj= pickle.load(savefile)
        savefile.close()
    else:
        mass= []
        ii, jj= 0, 0
    #parameters
    if os.path.exists(args[1]):#Load initial
        savefile= open(args[1],'rb')
        fits= pickle.load(savefile)
        savefile.close()
    else:
        print "Error: must provide parameters of best fits"
        print "Returning ..."
        return None
    #Sample?
    if options.mcsample:
        if ii < len(binned.fehedges)-1 and jj < len(binned.afeedges)-1:
            print "First do all of the best-fit mass estimates ..."
            print "Returning ..."
            return None
        if os.path.exists(args[2]): #Load savefile
            savefile= open(args[2],'rb')
            masssamples= pickle.load(savefile)
            ii= pickle.load(savefile)
            jj= pickle.load(savefile)
            savefile.close()
        else:
            masssamples= []
            ii, jj= 0, 0
        if os.path.exists(args[3]): #Load savefile
            savefile= open(args[3],'rb')
            denssamples= pickle.load(savefile)
            savefile.close()
        else:
            print "If mcsample you need to provide the file with the density samples ..."
            print "Returning ..."
            return None
    #Set up model etc.
    if options.model.lower() == 'hwr':
        densfunc= _HWRDensity
    elif options.model.lower() == 'twodblexp':
        densfunc= _TwoDblExpDensity
    like_func= _HWRLikeMinus
    pdf_func= _HWRLike
    if options.sample.lower() == 'g':
        colorrange=[0.48,0.55]
    elif options.sample.lower() == 'k':
        colorrange=[0.55,0.75]
    #Load selection function
    plates= numpy.array(list(set(list(raw.plate))),dtype='int') #Only load plates that we use
    print "Using %i plates, %i stars ..." %(len(plates),len(raw))
    sf= segueSelect(plates=plates,type_faint='tanhrcut',
                    sample=options.sample,type_bright='tanhrcut',
                    sn=True,select=options.select)
    platelb= bovy_coords.radec_to_lb(sf.platestr.ra,sf.platestr.dec,
                                     degree=True)
    indx= [not 'faint' in name for name in sf.platestr.programname]
    platebright= numpy.array(indx,dtype='bool')
    indx= ['faint' in name for name in sf.platestr.programname]
    platefaint= numpy.array(indx,dtype='bool')
    if options.sample.lower() == 'g':
        grmin, grmax= 0.48, 0.55
        rmin,rmax= 14.5, 20.2
    #Run through the bins
    while ii < len(binned.fehedges)-1:
        while jj < len(binned.afeedges)-1:
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                if options.mcsample: masssamples.append(None)
                else: mass.append(None)
                jj+= 1
                if jj == len(binned.afeedges)-1: 
                    jj= 0
                    ii+= 1
                    break
                continue               
            print binned.feh(ii), binned.afe(jj), len(data)
            fehindx= binned.fehindx(binned.feh(ii))
            afeindx= binned.afeindx(binned.afe(jj))
            #set up feh and color
            feh= binned.feh(ii)
            fehrange= [binned.fehedges[ii],binned.fehedges[ii+1]]
            #FeH
            fehdist= DistSpline(*numpy.histogram(data.feh,bins=5,
                                                 range=fehrange),
                                 xrange=fehrange,dontcuttorange=False)
            #Color
            colordist= DistSpline(*numpy.histogram(data.dered_g\
                                                       -data.dered_r,
                                                   bins=9,range=colorrange),
                                   xrange=colorrange)
            
            #Age marginalization
            afe= binned.afe(jj)
            if options.simpleage:
                agemin, agemax= 0.5, 10.
            else:
                if afe > 0.25: agemin, agemax= 7.,10.
                else: agemin,agemax= 1.,8.
            if options.mcsample:
                #Loop over samples
                thissamples= denssamples[afeindx+fehindx*binned.npixafe()]
                if options.nsamples < len(thissamples):
                    print "Taking random ..."
                    #Random permutation
                    thissamples= numpy.random.permutation(thissamples)[0:options.nsamples]
                thismasssamples= []
                print "WARNING: DISK MASS IN CALCMASS ONLY FOR G COLORS"
                for kk in range(len(thissamples)):
                    thisparams= thissamples[kk]
                    thismasssamples.append(predictDiskMass(densfunc,
                                                           thisparams,sf,
                                                           colordist,fehdist,
                                                           fehrange[0],
                                                           fehrange[1],feh,
                                                           data,0.45,
                                                           0.58,
                                                           agemin,agemax,
                                                           normalize=options.normalize,
                                                           imfmodel=options.imfmodel))
                #Print some stuff
                print numpy.mean(numpy.array(thismasssamples)), numpy.std(numpy.array(thismasssamples))
                masssamples.append(thismasssamples)
            else:
                thisparams= fits[afeindx+fehindx*binned.npixafe()]
                print "WARNING: DISK MASS IN CALCMASS ONLY FOR G COLORS"
                mass.append(predictDiskMass(densfunc,
                                            thisparams,sf,
                                            colordist,fehdist,
                                            fehrange[0],
                                            fehrange[1],feh,
                                            data,0.45,
                                            0.58,
                                            agemin,agemax,
                                            normalize=options.normalize,
                                            imfmodel=options.imfmodel))
                print mass[-1]
            jj+= 1
            if jj == len(binned.afeedges)-1: 
                jj= 0
                ii+= 1
            if options.mcsample: save_pickles(args[2],masssamples,ii,jj)
            else: save_pickles(args[0],mass,ii,jj)
            if jj == 0: #this means we've reset the counter 
                break
    if options.mcsample: save_pickles(args[2],masssamples,ii,jj)
    else: save_pickles(args[0],mass,ii,jj)
    return None
Exemplo n.º 56
0
def skewQSO(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)
        fittype= pickle.load(savefile)
        band= pickle.load(savefile)
        mean= pickle.load(savefile)
        taus= pickle.load(savefile)      
        savefile.close()
    else:
        skews= {}
        gaussskews= {}
        fittype= options.type
        mean= options.mean
        band= options.band
        taus= nu.arange(options.dtau,options.taumax,options.dtau)/365.25
    if os.path.exists(options.fitsfile):
        fitsfile= open(options.fitsfile,'rb')
        params= pickle.load(fitsfile)
        fitsfile.close()
    else:
        raise IOError("--fitsfile (or -f) has to be set to the file holding the best-fits")
    if options.star:
        dir= '../data/star/'
    elif options.nuvx:
        dir= '../data/nuvx/'
    elif options.nuvxall:
        dir= '../data/nuvx_all/'
    elif options.uvx:
        dir= '../data/uvx/'
    elif options.rrlyrae:
        dir= '../data/rrlyrae/'
    else:
        dir= '../data/s82qsos/'
    qsos= QSOfilenames(dir=dir)
    if not options.split is None:
        splitarr= nu.arange(len(qsos)) / int(nu.ceil(len(qsos)/float(options.split)))
        splitDict= {}
        for ii, qso in enumerate(qsos):
            key= os.path.basename(qso)
            splitDict[key]= splitarr[ii]
        print "Running bin %i ..." % (options.rah-1)
    savecount= 0
    count= len(skews)
    if not options.star and not options.rrlyrae:
        #Read master file for redshifts
        dataqsos= open_qsos()
        qsoDict= {}
        ii=0
        for qso in dataqsos:
            qsoDict[qso.oname.strip().replace(' ', '')+'.fit']= ii
            ii+= 1
    for qso in qsos:
        key= os.path.basename(qso)
        if skews.has_key(key):
            continue
        if not options.split is None:
            if splitDict[key] != (options.rah-1):
                continue
        else:
            try:
                if int(key[5:7]) != options.rah and options.rah != -1:
                    continue
            except ValueError:
                if options.rah == -2 or options.rah == -1:
                    pass
                else:
                    print "Skipping ValueError "+key
                    continue
        sys.stdout.write('\r'+_ERASESTR+'\r')
        sys.stdout.flush()
        sys.stdout.write('\rWorking on %s: %s\r' % (str(count),key))
        sys.stdout.flush()
        v= VarQso(qso,flux=options.flux)
        if v.nepochs(band) < 20:
            #print "This object does not have enough epochs ..."
            continue
        #Set best-fit
        if options.flux:
            params[key]['logA']+= 2.*nu.log(nu.log(10.)/2.5)
        if options.mean == 'const':
            params[key]['m']= -nu.log(10.)/2.5*params[key]['m']
        v.LCparams= params[key]
        v.LC= LCmodel(trainSet=v._build_trainset(band),type=fittype,mean=mean,
                      init_params=params[key])
        v.LCtype= fittype
        v.LCmean= mean
        v.fitband= band
        #Now compute skew and Gaussian samples
        try:
            thisskew= v.skew(taus,band)
        except RuntimeError:
            continue
        if options.flux:
            thisskew*= -1.
        thisgaussskews= nu.zeros((options.nsamples,len(taus)))
        for ii in range(options.nsamples):
            #First re-sample
            if options.star or options.rrlyrae:
                redshift= 0.
            else:
                redshift= dataqsos[qsoDict[key]].z
            try:
                o= v.resample(v.mjd[band],band=band,noconstraints=True,
                              wedge=options.wedge,
                              wedgerate=options.wedgerate*365.25/(1.+redshift),
                              wedgetau=(1.+redshift)) #1yr
            except nu.linalg.linalg.LinAlgError:
                if params[key]['gamma'] > 1.5 \
                        or params[key]['logA'] < -10.:
                    continue #re-sampling fails because of bad gamma/logA
                else:
                    print key, params[key]
            o.LCparams= v.LCparams
            o.LC= v.LC
            o.fitband= v.fitband
            o.LCtype= v.LCtype
            o.LCmean= v.LCmean
            if options.wedge:
                o.LCparams['gamma']= 1.
                o.LCparams['logA']= o.LCparams['logA']\
                    +nu.log(0.025**v.LCparams['gamma']/0.025)
                o.LCmean= 'zero' #bc we remove the mean when resampling wedge
                #Set up LC with correct params
                o.LC= LCmodel(trainSet=o._build_trainset(band),
                              type=o.LCtype,mean=o.LCmean,
                              init_params=o.LCparams)
            thisgaussskews[ii,:]= o.skew(taus,band)
            if options.flux:
                thisgaussskews[ii,:]*= -1.
        skews[key]= thisskew
        gaussskews[key]= thisgaussskews
        savecount+= 1
        if savecount == options.saveevery:
            sys.stdout.write('\r'+_ERASESTR+'\r')
            sys.stdout.flush()
            sys.stdout.write('\rSaving ...\r')
            sys.stdout.flush()
            save_pickles(savefilename,skews,gaussskews,fittype,band,mean,taus)
            savecount= 0
        count+= 1
    sys.stdout.write('\r'+_ERASESTR+'\r')
    sys.stdout.flush()
    save_pickles(savefilename,skews,gaussskews,fittype,band,mean,taus)
    print "All done"
Exemplo n.º 57
0
        nsam = int(times.split('sampling')[0])
        return [
            float(ti) / bovy_conversion.time_in_Gyr(vo, ro)
            for ti in numpy.arange(1, nsam + 1) / (nsam + 1.) * age
        ]
    return [
        float(ti) / bovy_conversion.time_in_Gyr(vo, ro)
        for ti in times.split(',')
    ]


timpacts = parse_times(options.timpacts, options.td, ro=_REFR0, vo=tvo)

size = options.chunk_size

tarray = [timpacts[i:i + size] for i in range(0, len(timpacts), size)]

timpactn = tarray[options.tind]

print(timpactn)

#sdf_smooth= pal5_util.setup_pal5model()
pepperfilename = 'pkl_files/pal5pepper_Plummer_td{}_{}sampling_chainind{}_{}.pkl'.format(
    options.td, len(timpacts), options.chain_ind, options.tind)

sdf_pepper = GMC_util.make_nondefault_pal5stream(options.chain_ind,
                                                 timpact=timpactn,
                                                 td=options.td)

save_pickles(pepperfilename, sdf_pepper)
Exemplo n.º 58
0
def plot_effsel_location(location, plotname):
    # Setup selection function
    selectFile = '../savs/selfunc-nospdata.sav'
    if os.path.exists(selectFile):
        with open(selectFile, 'rb') as savefile:
            apo = pickle.load(savefile)
    else:
        # Setup selection function
        apo = apogee.select.apogeeSelect()
        # Delete these because they're big and we don't need them
        del apo._specdata
        del apo._photdata
        save_pickles(selectFile, apo)
    effselFile = '../savs/effselfunc-%i.sav' % location
    if not os.path.exists(effselFile):
        # Distances at which to calculate the effective selection function
        distmods = numpy.linspace(7., 15.5, 301)
        ds = 10.**(distmods / 5 - 2.)
        # Setup default effective selection function
        do_samples = True
        gd = mwdust.Green15(filter='2MASS H', load_samples=do_samples)
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=gd)
        sf_default = apof(location, ds)
        # Also calculate for a sample of MH
        data = get_rcsample()
        MH = data['H0'] - data['RC_DM']
        MH = numpy.random.permutation(MH)[:1000]
        sf_jkz = apof(location, ds, MH=MH)
        # Go through the samples
        sf_samples = numpy.zeros((20, len(ds)))
        if do_samples:
            for ii in range(20):
                # Swap in a sample for bestfit in the Green et al. (2015) dmap
                gd.substitute_sample(ii)
                apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=gd)
                sf_samples[ii] = apof(location, ds)
        zerodust = mwdust.Zero(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=zerodust)
        sf_zero = apof(location, ds)
        drimmel = mwdust.Drimmel03(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=drimmel)
        sf_drimmel = apof(location, ds)
        marshall = mwdust.Marshall06(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=marshall)
        try:
            sf_marshall = apof(location, ds)
        except IndexError:
            sf_marshall = -numpy.ones_like(ds)
        sale = mwdust.Sale14(filter='2MASS H')
        apof = apogee.select.apogeeEffectiveSelect(apo, dmap3d=sale)
        try:
            sf_sale = apof(location, ds)
        except (TypeError, ValueError):
            sf_sale = -numpy.ones_like(ds)
        save_pickles(effselFile, distmods, sf_default, sf_jkz, sf_samples,
                     sf_zero, sf_drimmel, sf_marshall, sf_sale)
    else:
        with open(effselFile, 'rb') as savefile:
            distmods = pickle.load(savefile)
            sf_default = pickle.load(savefile)
            sf_jkz = pickle.load(savefile)
            sf_samples = pickle.load(savefile)
            sf_zero = pickle.load(savefile)
            sf_drimmel = pickle.load(savefile)
            sf_marshall = pickle.load(savefile)
            sf_sale = pickle.load(savefile)
    # Now plot
    bovy_plot.bovy_print(fig_height=3.)
    rc('text.latex',
       preamble=r'\usepackage{amsmath}' + '\n' + r'\usepackage{amssymb}' +
       '\n' + r'\usepackage{yfonts}')
    if _PLOTDIST:
        distmods = 10.**(distmods / 5 - 2.)
        xrange = [0., 12.]
        xlabel = r'$D\,(\mathrm{kpc})$'
        ylabel = r'$\textswab{S}(\mathrm{location},D)$'
    else:
        xrange = [7., 15.8],
        xlabel = r'$\mathrm{distance\ modulus}\ \mu$'
        ylabel = r'$\textswab{S}(\mathrm{location},\mu)$'
    line_default = bovy_plot.bovy_plot(distmods,
                                       sf_default,
                                       'b-',
                                       lw=_LW,
                                       zorder=12,
                                       xrange=xrange,
                                       xlabel=xlabel,
                                       yrange=[0., 1.2 * numpy.amax(sf_zero)],
                                       ylabel=ylabel)
    pyplot.fill_between(distmods,
                        sf_default-_EXAGGERATE_ERRORS\
                            *(sf_default-numpy.amin(sf_samples,axis=0)),
                        sf_default+_EXAGGERATE_ERRORS\
                            *(numpy.amax(sf_samples,axis=0)-sf_default),
                        color='0.65',zorder=0)
    line_jkz = bovy_plot.bovy_plot(distmods,
                                   sf_jkz,
                                   'g-.',
                                   lw=2. * _LW,
                                   overplot=True,
                                   zorder=13)
    line_zero = bovy_plot.bovy_plot(distmods,
                                    sf_zero,
                                    'k--',
                                    lw=_LW,
                                    overplot=True,
                                    zorder=7)
    line_drimmel = bovy_plot.bovy_plot(distmods,
                                       sf_drimmel,
                                       '-',
                                       color='gold',
                                       lw=_LW,
                                       overplot=True,
                                       zorder=8)
    line_marshall = bovy_plot.bovy_plot(distmods,
                                        sf_marshall,
                                        'r-',
                                        lw=_LW,
                                        overplot=True,
                                        zorder=9)
    line_sale = bovy_plot.bovy_plot(distmods,
                                    sf_sale,
                                    'c-',
                                    lw=_LW,
                                    overplot=True,
                                    zorder=10)
    if location == 4378:
        pyplot.legend(
            (line_default[0], line_jkz[0], line_zero[0]),
            (r'$\mathrm{Green\ et\ al.\ (2015)}$',
             r'$\mathrm{Green\ et\ al.} + p(M_H)$',
             r'$\mathrm{zero\ extinction}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    elif location == 4312:
        pyplot.legend(
            (line_sale[0], line_marshall[0], line_drimmel[0]),
            (r'$\mathrm{Sale\ et\ al.\ (2014)}$',
             r'$\mathrm{Marshall\ et\ al.\ (2006)}$',
             r'$\mathrm{Drimmel\ et\ al.\ (2003)}$'),
            loc='lower right',  #bbox_to_anchor=(.91,.375),
            numpoints=8,
            prop={'size': 14},
            frameon=False)
    # Label
    lcen, bcen = apo.glonGlat(location)
    if numpy.fabs(bcen) < 0.1: bcen = 0.
    bovy_plot.bovy_text(r'$(l,b) = (%.1f,%.1f)$' % (lcen, bcen),
                        top_right=True,
                        size=16.)
    bovy_plot.bovy_end_print(plotname)
    return None
def main(args: Optional[list] = None,
         opts: Optional[argparse.Namespace] = None):
    """Fit Combination Pal5 and GD1 to MW Potential Script Function.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        file.write("\nMass Constraints:")

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

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

    bovy_plot.scatterplot(
        hmass,
        s[-1, ::skip],
        "k,",
        onedhists=True,
        bins=31,
        xrange=[0.5, 1.5],
        yrange=[0.5, 1.5],
        xlabel=r"$M_{\mathrm{halo}} (r<20\,\mathrm{kpc})\,(M_\odot)$",
        ylabel=r"$c/a$",
    )
    plt.savefig(fpath + "scatterplot.pdf")
Exemplo n.º 60
0
def plot_powspec(dist,basename,plotname):
    # Density
    G0= 0.68+dust.dist2distmod(dist)
    densname= basename+'_D%.1f_denscl.sav' % dist
    if not os.path.exists(densname):
        densmap= densprofiles.healpixelate(dist,densprofiles.expdisk,
                                           [1./3.,1./0.3],nside=_NSIDE,
                                           nest=False)
        denscl= healpy.sphtfunc.anafast(densmap,pol=False)
        densmap2= densprofiles.healpixelate(dist,densprofiles.expdisk,
                                            [1./2.,1./0.9],nside=_NSIDE,
                                            nest=False)
        denscl2= healpy.sphtfunc.anafast(densmap2,pol=False)
        ell= numpy.arange(len(denscl))
        save_pickles(densname,ell,denscl,densmap,denscl2,densmap2)
    else:
        with open(densname,'rb') as savefile:
            ell= pickle.load(savefile)
            denscl= pickle.load(savefile)
            densmap= pickle.load(savefile)
            denscl2= pickle.load(savefile)
            densmap2= pickle.load(savefile)
    # dust map Cl and cross-power with dens
    combinedname= basename+'_D%.1f_combinedcl.sav' % dist
    bestfitloaded= False
    if os.path.exists(combinedname):
        with open(combinedname,'rb') as savefile:
            ell= pickle.load(savefile)
            combinedcl= pickle.load(savefile)
            combinedcr= pickle.load(savefile)
            combinedmcl= pickle.load(savefile)
            combinedmcr= pickle.load(savefile)
            combinedmcr2= pickle.load(savefile)
            bestfitloaded= True
    if not bestfitloaded:
        # do the best-fit
        combinedmap= dust.load_combined(dist,nest=False,nside_out=_NSIDE)
        print numpy.sum(numpy.isnan(combinedmap))
        combinedmap[numpy.isnan(combinedmap)]= 0.
        # Sample over the distribution of MG
        combinedmask= numpy.zeros_like(combinedmap)
        iso= gaia_rc.load_iso()
        Gsamples= gaia_rc.sample_Gdist(iso,n=_NGSAMPLES)
        print "Computing effective selection function"
        for jj in range(_NGSAMPLES):
            combinedmask+= ((combinedmap > (_GMIN-G0-Gsamples[jj]+0.68))\
                                *(combinedmap < (_GMAX-G0-Gsamples[jj]+0.68))).astype('float')
        combinedmask/= _NGSAMPLES
        print "Computing Cl of extinction map"
        combinedcl= healpy.sphtfunc.anafast(combinedmap,pol=False)
        print "Computing cross of extinction map w/ densmap"
        combinedcr= healpy.sphtfunc.anafast(combinedmap,map2=densmap,pol=False)
        print "Computing Cl of effective selection function"
        combinedmcl= healpy.sphtfunc.anafast(combinedmask,pol=False)
        print "Computing cross of effective selection function w/ densmap"
        combinedmcr= healpy.sphtfunc.anafast(combinedmask,map2=densmap,pol=False)
        print "Computing cross of effective selection function w/ densmap2"
        combinedmcr2= healpy.sphtfunc.anafast(combinedmask,map2=densmap2,pol=False)
        # Save
        save_pickles(combinedname,ell,combinedcl,combinedcr,
                     combinedmcl,combinedmcr,combinedmcr2)
        gc.collect()
    # Plot (2l+1)Cl!!
    # Can smooth the masked power spectrum, perhaps underplot the non-smoothed in gray
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(combinedmcl)[1:],k=3,s=300.)
    # sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],numpy.log(numpy.fabs(combinedmcr))[1:],k=3,s=10000.)
    # First plot the power-spectrum, then the cross-correlation, then the
    # cumulative sum
    bovy_plot.bovy_print(fig_height=3.)
    yrange=[10.**-12.,20.],
    line1= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*combinedcl[1:],
                               'k-',loglog=True,
                               ylabel=r'$(2\ell+1)\,C_\ell$',
                               xrange=[0.5,20000],
                               yrange=yrange,
                               zorder=3)
    line2= bovy_plot.bovy_plot(ell[2::2],
                               (2.*ell[2::2]+1.)*denscl[2::2],
                               'b-',overplot=True)
    line3= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*combinedmcl[1:],
                               'r-',overplot=True)
    # Add legend
    if dist == 5.:
        pyplot.legend((line2[0],line1[0],line3[0]),
                      (r'$\mathrm{exp.\ disk\ w/}$'+'\n'+r'$h_R = 3\,\mathrm{kpc},$'+'\n'+r'$h_Z = 0.3\,\mathrm{kpc}$',
                       r'$\mathrm{extinction\ map}$',
                       r'$\mathrm{effective\ selection\ function}$'),
                      loc='lower left',bbox_to_anchor=(.02,.02),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False) 
        bovy_plot.bovy_text(r'$\mathrm{power\ spectrum}$',top_right=True,size=16.)
    nullfmt   = NullFormatter()         # no labels
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname)
    # Cross-correlation
    bovy_plot.bovy_print(fig_height=3.)
    line1= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*numpy.fabs(combinedcr[1:]),
                               'k-',loglog=True,
                               ylabel=r'$(2\ell+1)\,C^{\mathrm{cross}}_\ell$',
                               xrange=[0.5,20000],
                               yrange=yrange,
                               zorder=1)
    line2= bovy_plot.bovy_plot(ell[1:],
                               (2.*ell[1:]+1.)*numpy.fabs(combinedmcr[1:]),
                               'r-',overplot=True,zorder=2)
    # Add legend
    if dist == 5.:
        pyplot.legend((line1[0],line2[0]),
                      (r'$\mathrm{extinction\ map}$',
                       r'$\mathrm{effective\ selection}$'+'\n'+r'$\mathrm{function}$'),
                      loc='lower left',bbox_to_anchor=(.02,.02),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False) 
        bovy_plot.bovy_text(r'$\mathrm{cross\ power\ spectrum\ w/\ density}$',top_right=True,size=16.)
    #sp= interpolate.UnivariateSpline(numpy.log(ell)[1:],
    #                                 numpy.log(numpy.fabs(combinedmcr))[1:],
    #                                 k=3,s=100000.)
    #bovy_plot.bovy_plot(ell[1:],
    #                    10.*(2.*ell[1:]+1.)*numpy.exp(sp(numpy.log(ell[1:]))),
    #                    'r-',overplot=True,zorder=2)
    pyplot.gca().xaxis.set_major_formatter(nullfmt)
    bovy_plot.bovy_end_print(plotname.replace('powspec','crosspowspec'))
    effvol= numpy.sum((2.*ell+1.)*combinedmcr)
    #effvol2= numpy.sum((2.*ell+1.)*combinedmcr2)
    matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{yfonts}"]
    line1= bovy_plot.bovy_plot(ell[1:],
                               numpy.fabs(numpy.log(effvol)
                                          -numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr)))[1:],
                               'k-',loglog=True,
                               xlabel=r'$\ell$',
                               ylabel=r'$\left|\Delta\ln\sum_{\ell}\sum_{m}\nu_{*,\ell m}\,\textswab{S}_{\ell m}\right|$',
                               xrange=[0.5,20000],
                               yrange=[2.*10.**-13.,20.],
                               zorder=3)
    """
    line2= bovy_plot.bovy_plot(ell[1:],
                               numpy.fabs(numpy.log(effvol)
                                          -numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr))
                                          -numpy.log(effvol2)
                                          +numpy.log(numpy.cumsum((2.*ell+1.)*combinedmcr2)))[1:],
                               'k--',loglog=True,
                               overplot=True,zorder=2)
    # Add legend
    pyplot.legend((line1[0],line2[0]),
                  (r'$\mathrm{exp.\ disk\ top\ panel}$',
                   r'$\mathrm{relative\ wrt\ exp.\ disk\ w/}$'+'\n'+
                   r'$h_R = 2\,\mathrm{kpc}, h_Z = 0.9\,\mathrm{kpc}$'),
                   loc='lower right',#bbox_to_anchor=(.91,.375),
                   numpoints=8,
                   prop={'size':14},
                   frameon=False) 
    """
    if dist == 5.:
        bovy_plot.bovy_text(r'$\mathrm{error\ in}\ \ln\ \mathrm{effective\ area}$',top_right=True,size=16.)
    bovy_plot.bovy_end_print(plotname.replace('powspec','cumulcrosspowspec')) 
    return None