Ejemplo n.º 1
0
def plot_jr(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp,tintJ=200,ntintJ=20000)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,0.88719443,
                      -0.47713334,0.12019596])
    bovy_plot.bovy_print(fig_width=6.)
    aAI.plot(*obs,type='jr',downsample=True)
    bovy_plot.bovy_end_print(plotfilename)
def plot_pdfs_l(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                  leading=True,nTrackChunks=_NTRACKCHUNKS,
                  vsun=[0.,30.24*8.,0.],
                  tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                  multi=_NTRACKCHUNKS)
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    #Sample from sdf
    llbd= sdf.sample(n=40000,lb=True)
    tlbd= sdft.sample(n=50000,lb=True)
    b,e= numpy.histogram(llbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    lspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=1.)
    lls= numpy.linspace(t[0],t[-1],_NLS)
    lps= numpy.exp(lspl(lls))
    lps/= numpy.sum(lps)*(lls[1]-lls[0])*2.
    b,e= numpy.histogram(tlbd[0],bins=101,normed=True)
    t= ((numpy.roll(e,1)-e)/2.+e)[1:]
    tspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=0.5)
    tls= numpy.linspace(t[0],t[-1],_NLS)
    tps= numpy.exp(tspl(tls))
    tps/= numpy.sum(tps)*(tls[1]-tls[0])*2.
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    bovy_plot.bovy_plot(lls,lps,'k-',lw=1.5,
                        xlabel=r'$\mathrm{Galactic\ longitude}\,(\mathrm{deg})$',
                        ylabel=r'$p(l)$',
                        xrange=[65.,250.],
                        yrange=[0.,1.2*numpy.nanmax(numpy.hstack((lps,tps)))])
    bovy_plot.bovy_plot(tls,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    #Transform to (l,b)
    XYZ= bovy_coords.galcenrect_to_XYZ(data[:,1],data[:,3],data[:,2],Xsun=8.)
    lbd= bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2],degree=True)
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    lbd= lbd[indx,:]
    bovy_plot.bovy_hist(lbd[:,0],bins=40,range=[65.,250.],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
def plot_pdfs_x(plotfilename):
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                   leading=False,nTrackChunks=_NTRACKCHUNKS,
                   vsun=[0.,30.24*8.,0.],
                   tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                   multi=_NTRACKCHUNKS)
    #Calculate the density as a function of l, p(l)
    txs= numpy.linspace(3.,12.4,_NLS)
    tlogps= multi.parallel_map((lambda x: sdft.callMarg([txs[x]/8.,None,None,None,None,None],
                                                        interp=True,ngl=_NGL,
                                                        nsigma=3)),
                              range(_NLS),
                              numcores=numpy.amin([_NLS,
                                                   multiprocessing.cpu_count()]))
    tlogps= numpy.array(tlogps)
    tlogps[numpy.isnan(tlogps)]= -100000000000000000.
    tps= numpy.exp(tlogps-logsumexp(tlogps))
    tps/= numpy.nansum(tps)*(txs[1]-txs[0])
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(txs,tps,'k-',lw=1.5,
                        xlabel=r'$X\,(\mathrm{kpc})$',
                        ylabel=r'$p(X)$',
                        xrange=[3.,12.4],
                        yrange=[0.,1.2*numpy.nanmax(tps)])
    bovy_plot.bovy_plot(txs,tps,'k-',lw=1.5,overplot=True)
    #Also plot the stream histogram
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= thetar-numpy.pi < -(5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    data= data[indx,:]
    bovy_plot.bovy_hist(data[:,1],bins=20,range=[3.,12.4],
                        histtype='step',normed=True,
                        overplot=True,
                        lw=1.5,color='k')
    bovy_plot.bovy_end_print(plotfilename)
def calc_actions(snapfile=None):
    #Directories
    snapdir= 'snaps/'
    basefilename= snapfile.split('.')[0]
    nsnap= len(glob.glob(os.path.join(snapdir,basefilename+'_*.dat')))
    print "Processing %i snapshots ..." % nsnap
    #Setup potential
    lp= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
    if False:
        aA= actionAngleStaeckel(pot=lp,delta=1.20,c=True)
        snapaadir= 'snaps_aas/'
    else:
        aA= actionAngleIsochroneApprox(pot=lp,b=0.8)
        snapaadir= 'snaps_aai/'
    #Run each snapshot
    if True:
        calcThese= []
        for ii in range(nsnap):
            csvfilename= os.path.join(snapaadir,basefilename+'_aa_%s.dat' % str(ii).zfill(5))
            if os.path.exists(csvfilename):
                #Don't recalculate those that have already been calculated
                nstart= int(subprocess.check_output(['wc','-l',csvfilename]).split(' ')[0])
                if nstart < 10000:
                    calcThese.append(ii)
            else:
                calcThese.append(ii)
        nsnap= len(calcThese)
    if len(calcThese) == 0:
        print "All done with everything ..."
        return None
    args= (aA,snapdir,basefilename,snapaadir)
    print "Using %i cpus ..." % (numpy.amin([64,nsnap,
                                             multiprocessing.cpu_count()]))
    dummy= multi.parallel_map((lambda x: indiv_calc_actions(x,
                                                            *args)),
                              calcThese,
#                              range(nsnap),
                              numcores=numpy.amin([64,nsnap,
                                                      multiprocessing.cpu_count()]))
    return None
def calc_progenitor_actions(savefilename):
    # Setup potential
    lp = potential.LogarithmicHaloPotential(normalize=1.0, q=0.9)
    # Setup orbit
    x, z, y, vx, vz, vy = -11.63337239, -10.631736273934635, -20.76235661, -128.8281653, 79.172383882274971, 42.88727925
    R, phi, z = bovy_coords.rect_to_cyl(x, y, z)
    vR, vT, vz = bovy_coords.rect_to_cyl_vec(vx, vy, vz, R, phi, z, cyl=True)
    R /= 8.0
    z /= 8.0
    vR /= 220.0
    vT /= 220.0
    vz /= 220.0
    o = Orbit([R, vR, vT, z, vz, phi])
    ts = numpy.linspace(0.0, 5.125 * 220.0 / 8.0, 1313)  # times of the snapshots
    o.integrate(ts, lp, method="dopr54_c")
    if "aas" in savefilename:
        aA = actionAngleStaeckel(pot=lp, delta=1.20, c=True)
    else:
        aA = actionAngleIsochroneApprox(pot=lp, b=0.8)
    # Now calculate actions, frequencies, and angles for all positions
    Rs = o.R(ts)
    vRs = o.vR(ts)
    vTs = o.vT(ts)
    zs = o.z(ts)
    vzs = o.vz(ts)
    phis = o.phi(ts)
    csvfile = open(savefilename, "wb")
    writer = csv.writer(csvfile, delimiter=",")
    for ii in range(len(ts)):
        acfs = aA.actionsFreqsAngles(Rs[ii], vRs[ii], vTs[ii], zs[ii], vzs[ii], phis[ii])
        writer.writerow(
            [acfs[0][0], acfs[1][0], acfs[2][0], acfs[3][0], acfs[4][0], acfs[5][0], acfs[6][0], acfs[7][0], acfs[8][0]]
        )
        csvfile.flush()
    csvfile.close()
    return None
def plot_stream_xz(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_00800.dat'),
                        delimiter=',')
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_00800.dat'),
                        delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    if 'sim' in plotfilename:
        sindx= numpy.fabs(thetar-numpy.pi) > (4.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    else:
        sindx= numpy.fabs(thetar-numpy.pi) > (1.5*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    includeorbit= True
    if includeorbit:
        npts= 201
        pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
        pts= numpy.linspace(0.,4.,npts)
        #Calculate progenitor orbit around this point
        pox= numpy.median(data[:,1])
        poy= numpy.median(data[:,3])
        poz= numpy.median(data[:,2])
        povx= numpy.median(data[:,4])
        povy= numpy.median(data[:,6])
        povz= numpy.median(data[:,5])
        pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)
        pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,
                                                 pphi,pZ,cyl=True)
        ppo= Orbit([pR/8.,pvR/220.,pvT/220.,pZ/8.,pvZ/220.,pphi])
        pno= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])
        ppo.integrate(pts,pot)
        pno.integrate(pts,pot)
        pvec= numpy.zeros((3,npts*2-1))
        pvec[0,:npts-1]= pno.x(pts)[::-1][:-1]
        pvec[1,:npts-1]= pno.z(pts)[::-1][:-1]
        pvec[2,:npts-1]= pno.y(pts)[::-1][:-1]
        pvec[0,npts-1:]= ppo.x(pts)
        pvec[1,npts-1:]= ppo.z(pts)
        pvec[2,npts-1:]= ppo.y(pts)
        pvec*= 8.
    includetrack= True
    if includetrack:
        #Setup stream model
        lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
        aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
        obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                          0.88719443,-0.47713334,0.12019596])
        #Obs is at time 1312, need to go back 2 Gyr to time 800
        obs[1]*= -1.
        obs[2]*= -1.
        obs[4]*= -1.
        o= Orbit(obs)
        ts= numpy.linspace(0.,2.*977.7922212082034/1000./bovy_conversion.time_in_Gyr(220.,8.),1001)
        o.integrate(ts,lp)
        obs= o(ts[-1])._orb.vxvv
        obs[1]*= -1.
        obs[2]*= -1.
        obs[4]*= -1.       
        tdisrupt= 4.5-2.*977.7922212082034/1000.
        sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                      leading=True,nTrackChunks=_NTRACKCHUNKS,
                      tdisrupt=tdisrupt/bovy_conversion.time_in_Gyr(220.,8.),
                      deltaAngleTrack=1.5*3./5.,multi=_NTRACKCHUNKS)
        sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                       leading=False,nTrackChunks=_NTRACKCHUNKS,
                       tdisrupt=tdisrupt/bovy_conversion.time_in_Gyr(220.,8.),
                       deltaAngleTrack=1.5*3./5.,multi=_NTRACKCHUNKS)
    if 'sim' in plotfilename:
        #Replace data with simulated data
        forwardXY= sdf.sample(int(round(numpy.sum(sindx)/2.)),
                              xy=True)
        backwardXY= sdft.sample(int(round(numpy.sum(sindx)/2.)),
                                xy=True)
        data= numpy.empty((forwardXY.shape[1]+backwardXY.shape[1],7))
        data[:forwardXY.shape[1],1]= forwardXY[0]*8.
        data[:forwardXY.shape[1],2]= forwardXY[2]*8.
        data[:forwardXY.shape[1],3]= forwardXY[1]*8.
        data[:forwardXY.shape[1],4]= forwardXY[3]*220.
        data[:forwardXY.shape[1],5]= forwardXY[5]*220.
        data[:forwardXY.shape[1],6]= forwardXY[4]*220.
        data[forwardXY.shape[1]:,1]= backwardXY[0]*8.
        data[forwardXY.shape[1]:,2]= backwardXY[2]*8.
        data[forwardXY.shape[1]:,3]= backwardXY[1]*8.
        data[forwardXY.shape[1]:,4]= backwardXY[3]*220.
        data[forwardXY.shape[1]:,5]= backwardXY[5]*220.
        data[forwardXY.shape[1]:,6]= backwardXY[4]*220.
        sindx= numpy.ones(data.shape[0],dtype='bool')      
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data[sindx,1],data[sindx,2],'k,',ms=2.,
                        xlabel=r'$X\,(\mathrm{kpc})$',
                        ylabel=r'$Z\,(\mathrm{kpc})$',
                        xrange=[-12.5,-3.],
                        yrange=[-12.5,-7.])
    if numpy.sum(True-sindx) > 0:
        #Also plot progenitor
        pindx= copy.copy(True-sindx)
        pindx[0:9900]= False #subsample
        bovy_plot.bovy_plot(data[pindx,1],data[pindx,2],
                            'k,',overplot=True)
    if includeorbit:
        bovy_plot.bovy_plot(pox,poz,'o',color='0.5',mec='none',overplot=True,ms=8)
        bovy_plot.bovy_plot(pvec[0,:],pvec[1,:],'k--',overplot=True,lw=1.)
    if 'sim' in plotfilename:
        bovy_plot.bovy_text(r'$\mathrm{mock\ stream}$',
                            bottom_left=True,size=16.)
    else:
        bovy_plot.bovy_text(r'$N\!\!-\!\!\mathrm{body\ stream}$',
                            bottom_left=True,size=16.)
    if includetrack:
        d1= 'x'
        d2= 'z'
        sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                      overplot=True,lw=1.,scaleToPhysical=True)
        sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                       overplot=True,lw=1.,scaleToPhysical=True)
        #Also create inset
        pyplot.plot([-9.,-9.],[-11.75,-10.3],'k-')
        pyplot.plot([-6.,-6.],[-11.75,-10.3],'k-')
        pyplot.plot([-9.,-6.],[-11.75,-11.75],'k-')
        pyplot.plot([-9.,-6.],[-10.3,-10.3],'k-')
        pyplot.plot([-6.,-3.4],[-10.3,-10.],'k:')
        pyplot.plot([-9.,-8.85],[-10.3,-10.],'k:')
        insetAxes= pyplot.axes([0.42,0.47,0.45,0.42])
        pyplot.sca(insetAxes)
        bovy_plot.bovy_plot(data[sindx,1],data[sindx,2],'k.',ms=2.,zorder=0.,
                            overplot=True)
        if numpy.sum(True-sindx) > 0:
            pindx= copy.copy(True-sindx)
            pindx[0:9700]= False #subsample
            bovy_plot.bovy_plot(data[pindx,1],data[pindx,2],'k,',
                                zorder=0.,
                                overplot=True)
        bovy_plot.bovy_plot(pvec[0,:],pvec[1,:],'k--',overplot=True,lw=1.,
                            zorder=1)
        sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                      overplot=True,lw=1.,scaleToPhysical=True,zorder=2)
        nullfmt   = NullFormatter()         # no labels
        insetAxes.xaxis.set_major_formatter(nullfmt)
        insetAxes.yaxis.set_major_formatter(nullfmt)
        insetAxes.set_xlim(-9.,-6.)
        insetAxes.set_ylim(-11.75,-10.3)
        pyplot.tick_params(\
            axis='both',          # changes apply to the x-axis
            which='both',      # both major and minor ticks are affected
            bottom='off',      # ticks along the bottom edge are off
            top='off',         # ticks along the top edge are off
            left='off',      # ticks along the bottom edge are off
            right='off')         # ticks along the top edge are off
    bovy_plot.bovy_end_print(plotfilename)
def illustrate_track(plotfilename1,plotfilename2,plotfilename3):
    #Setup stream model
    lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
    aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
    obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                      0.88719443,-0.47713334,0.12019596])
    sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                  leading=True,nTrackChunks=_NTRACKCHUNKS,
                  tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.))
    #First calculate meanOmega and sigOmega
    mOs= numpy.array([sdf.meanOmega(t,oned=True) for t in sdf._thetasTrack])
    sOs= numpy.array([sdf.sigOmega(t) for t in sdf._thetasTrack])
    mOs-= sdf._progenitor_Omega_along_dOmega
    mOs*= -bovy_conversion.freq_in_Gyr(220.,8.)
    sOs*= bovy_conversion.freq_in_Gyr(220.,8.)
    progAngle= numpy.dot(sdf._progenitor_angle,sdf._dsigomeanProgDirection)
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs,'ko',ms=8.,
                        xlabel=r'$\theta_\parallel$',
                        ylabel=r'$\Omega_\parallel\,(\mathrm{Gyr}^{-1})$',
                        xrange=[-0.2-1.14,1.6-1.14],
                        yrange=[22.05,22.55])
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs,'k-',lw=1.5,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,
                        mOs[0]*numpy.ones(len(sdf._thetasTrack))+0.03,
                        'ko',ls='--',dashes=(20,10),lw=1.5,overplot=True,
                        ms=6.)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs+2*sOs,'ko',ms=6.,mfc='none',
                        zorder=1,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs-2*sOs,'ko',ms=6.,mfc='none',
                        zorder=1,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs+2*sOs,'k-.',lw=1.5,
                        zorder=0,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,mOs-2*sOs,'k-.',lw=1.5,
                        zorder=0,overplot=True)
    bovy_plot.bovy_plot(sdf._thetasTrack+progAngle,sdf._progenitor_Omega_along_dOmega*bovy_conversion.freq_in_Gyr(220.,8.)*numpy.ones(len(sdf._thetasTrack)),
                        'k--',lw=1.5,overplot=True)
    bovy_plot.bovy_plot((sdf._thetasTrack+progAngle)[0],(sdf._progenitor_Omega_along_dOmega*bovy_conversion.freq_in_Gyr(220.,8.)*numpy.ones(len(sdf._thetasTrack)))[0],
                        'ko',ms=6.,overplot=True)
    bovy_plot.bovy_text(1.05+progAngle,22.475,r'$\mathrm{progenitor\ orbit}$',size=16.)
    bovy_plot.bovy_text(progAngle+0.05,22.50,r'$\mathrm{current\ progenitor\ position}$',size=16.)
    bovy_plot.bovy_plot([progAngle+0.05,progAngle],[22.50,sdf._progenitor_Omega_along_dOmega*bovy_conversion.freq_in_Gyr(220.,8.)],'k:',overplot=True)
    bovy_plot.bovy_text(-1.2,22.35,r"$\mathrm{At\ the\ progenitor's}\ \theta_{\parallel}, \mathrm{we\ calculate\ an\ auxiliary\ orbit\ through}$"+'\n'+r"$(\mathbf{x}_a,\mathbf{v}_a) = (\mathbf{\Omega}_p+\Delta \mathbf{\Omega}^m,\boldsymbol{\theta}_p)\ \mathrm{using\ a\ linearized}\ (\mathbf{\Omega},\boldsymbol{\theta})\ \mathrm{to}\ (\mathbf{x},\mathbf{v}).$",size=16.)
    yarcs= numpy.linspace(22.30,22.39,101)
    bovy_plot.bovy_plot(sdf._thetasTrack[0]+progAngle-0.1*numpy.sqrt(1.-(yarcs-22.35)**2./0.05**2.),yarcs,'k:',
                        overplot=True)
    bovy_plot.bovy_text(-1.3,22.07,r'$\mathrm{At\ a\ small\ number\ of\ points, we\ calculate}$'+'\n'+r'$\partial(\mathbf{\Omega},\boldsymbol{\theta})/\partial (\mathbf{x},\mathbf{v}), \mathrm{the\ mean\ stream\ track\ in}\ (\mathbf{\Omega},\boldsymbol{\theta})^\dagger,$'+'\n'+r'$\mathrm{and\ estimate\ the\ spread\ around\ the\ track}.$',size=16.)
    bovy_plot.bovy_plot([-0.9,sdf._thetasTrack[1]+progAngle],
                        [22.185,mOs[1]+0.03],
                        'k:',overplot=True)
    bovy_plot.bovy_plot([-0.9,progAngle+sdf._thetasTrack[1]],
                        [22.185,mOs[1]],
                        'k:',overplot=True)
    bovy_plot.bovy_text(-0.18,22.265,r'$\mathrm{stream\ track\ +\ spread}$',
                         size=16.,
                        rotation=-20.)
    bovy_plot.bovy_end_print(plotfilename1)
    #Now plot Z,X
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    pyplot.figure()
    sdf.plotTrack(d1='z',d2='x',interp=True,
                  color='k',spread=2,overplot=True,lw=1.5,
                  scaleToPhysical=True)
    sdf.plotTrack(d1='z',d2='x',interp=False,marker='o',ms=8.,color='k',
                  overplot=True,ls='none',
                  scaleToPhysical=True)
    sdf.plotProgenitor(d1='z',d2='x',color='k',
                       overplot=True,ls='--',lw=1.5,dashes=(20,10),
                       scaleToPhysical=True)
    pyplot.plot(sdf._progenitor.z(sdf._trackts)*8.,
                sdf._progenitor.x(sdf._trackts)*8.,marker='o',ms=6.,
                ls='none',
                color='k')
    pyplot.xlim(8.,-3.)
    pyplot.ylim(12.,15.5)
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$Z\,(\mathrm{kpc})$',r'$X\,(\mathrm{kpc})$')
    bovy_plot.bovy_text(0.,14.25,r'$\mathrm{auxiliary\ orbit}$',
                        size=16.,rotation=-20.)
    bovy_plot.bovy_text(1.,13.78,r'$\mathrm{stream\ track\ +\ spread}$',
                        size=16.,rotation=-25.)
    bovy_plot.bovy_text(7.5,14.2,r"$\mathrm{At\ these\ points, we\ calculate\ the\ stream\ position\ in}\ (\mathbf{x},\mathbf{v})\ \mathrm{from}$"+
                         '\n'+r"$\mathrm{the\ auxiliary's}\ (\mathbf{x}_a,\mathbf{v}_a) = (\mathbf{\Omega}_a,\boldsymbol{\theta}_a), \mathrm{the\ mean\ offset} (\Delta \mathbf{\Omega},\Delta \boldsymbol{\theta}),$"+'\n'+
                         r"$\mathrm{and}\ \left(\frac{\partial(\mathbf{\Omega},\boldsymbol{\theta})}{\partial (\mathbf{x},\mathbf{v})}\right)^{-1 \, \dagger}.$",
                        size=16.)
    bovy_plot.bovy_plot([sdf._progenitor.z(sdf._trackts[1])*8.,4.5],
                        [sdf._progenitor.x(sdf._trackts[1])*8.,14.8],
                        'k:',overplot=True)
    bovy_plot.bovy_text(5.6,12.4,r"$\mathrm{We\ interpolate\ the\ track\ between\ the}$"+'\n'+r"$\mathrm{calculated\ points\ and\ use\ slerp\ to}$"+'\n'+r"$\mathrm{interpolate\ the\ estimated\ 6D\ spread.}$",
                         size=16.)
    bovy_plot.bovy_plot([3.,sdf._interpolatedObsTrackXY[500,2]*8.],
                        [13.3,sdf._interpolatedObsTrackXY[500,0]*8.],
                        'k:',overplot=True)
    bovy_plot.bovy_end_print(plotfilename2)
    #Finally plot l vs. d
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    pyplot.figure()
    sdf.plotTrack(d1='ll',d2='dist',interp=True,
                  color='k',spread=2,overplot=True,lw=1.5)
    sdf.plotTrack(d1='ll',d2='dist',interp=False,marker='o',ms=8.,color='k',
                  overplot=True,ls='none')
    sdf.plotProgenitor(d1='ll',d2='dist',color='k',dashes=(20,10),
                       overplot=True,ls='--',lw=1.5)
    pyplot.plot(sdf._progenitor.ll(sdf._trackts,
                                        obs=[sdf._R0,0.,sdf._Zsun],ro=sdf._Rnorm),
                sdf._progenitor.dist(sdf._trackts,
                                        obs=[sdf._R0,0.,sdf._Zsun],ro=sdf._Rnorm),
                marker='o',ms=6.,
                ls='none',
                color='k')
    pyplot.xlim(157.,260.)
    pyplot.ylim(7.4,15.5)
    bovy_plot._add_ticks()
    bovy_plot._add_axislabels(r'$\mathrm{Galactic\ longitude\, (deg)}$',
                              r'$\mathrm{distance\, (kpc)}$')
    bovy_plot.bovy_text(165.,13.5,r"$\mathrm{Finally, the\ interpolated\ track\ in}\ (\mathbf{x},\mathbf{v})\ \mathrm{is}$"+'\n'+r"$\mathrm{converted\ to\ observable\ quantities\ (here}, l\ \mathrm{and}\ D).$",
                        size=16.)
    bovy_plot.bovy_plot([230.,sdf._interpolatedObsTrackLB[850,0]],
                        [13.25,sdf._interpolatedObsTrackLB[850,2]],
                        'k:',overplot=True)
    bovy_plot.bovy_text(170.,9.4,r"$\mathrm{The\ estimated\ spread\ is\ propagated}$"+'\n'+r"$\mathrm{at\ the\ points\ directly\ from}\ (\mathbf{\Omega},\boldsymbol{\theta})\ \mathrm{to}$"+'\n'+r"$(l,b,D,\ldots)\ \mathrm{and\ interpolated}$"+'\n'+r"$\mathrm{using\ slerp}.$",
                        size=16.)
    bovy_plot.bovy_plot([195.,sdf._ObsTrackLB[1,0]],
                        [9.7,sdf._ObsTrackLB[1,2]],
                        'k:',overplot=True)
    bovy_plot.bovy_end_print(plotfilename3)
    return None
def plot_stream_aa(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                     'gd1_evol_hitres_aa_01312.dat'),
                        delimiter=',')
    includeorbit= True
    includetrack= True
    fmt= 'k,'
    if includeorbit:
        #Read progenitor actions
        progfile= '../sim/gd1_evol_hitres_progaai.dat'
        progaa= numpy.loadtxt(progfile,delimiter=',')
    if includetrack:
        #Setup stream model
        lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
        aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
        obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                          0.88719443,-0.47713334,0.12019596])
        sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                      leading=True,nosetup=True,
                      tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.))
    if 'araz' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,6]
        ploty= data[indx,8]
        plotx= (numpy.pi+(plotx-numpy.median(data[:,6]))) % (2.*numpy.pi)
        ploty= (numpy.pi+(ploty-numpy.median(data[:,8]))) % (2.*numpy.pi)
        xrange=[numpy.pi-1.,numpy.pi+1.]
        yrange=[numpy.pi-1.,numpy.pi+1.]
        xlabel=r'$\theta_R$'
        ylabel=r'$\theta_Z$'
    elif 'arap' in plotfilename and not 'aparaperp' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,6]
        ploty= data[indx,7]
        plotx= (numpy.pi+(plotx-numpy.median(data[:,6]))) % (2.*numpy.pi)
        ploty= (numpy.pi+(ploty-numpy.median(data[:,7]))) % (2.*numpy.pi)
        xrange=[numpy.pi-1.,numpy.pi+1.]
        yrange=[numpy.pi-1.,numpy.pi+1.]
        xlabel=r'$\theta_R$'
        ylabel=r'$\theta_\phi$'
    elif 'oroz' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,3]*bovy_conversion.freq_in_Gyr(220.,8.)
        ploty= data[indx,5]*bovy_conversion.freq_in_Gyr(220.,8.)
        xrange=[15.45,15.95]
        yrange=[11.7,12.05]
        xlabel=r'$\Omega_R\,(\mathrm{Gyr}^{-1})$'
        ylabel=r'$\Omega_Z\,(\mathrm{Gyr}^{-1})$'
    elif 'orop' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,3]*bovy_conversion.freq_in_Gyr(220.,8.)
        ploty= data[indx,4]*bovy_conversion.freq_in_Gyr(220.,8.)
        xrange=[15.45,15.95]
        yrange=[-10.98,-10.65]
        xlabel=r'$\Omega_R\,(\mathrm{Gyr}^{-1})$'
        ylabel=r'$\Omega_\phi\,(\mathrm{Gyr}^{-1})$'
    elif 'jrjz' in plotfilename:       
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,0]*8.
        ploty= data[indx,2]*8.
        xrange=[1.2,1.42]
        yrange=[3.98,4.18]
        xlabel=r'$J_R\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
        ylabel=r'$J_Z\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
    elif 'jrjp' in plotfilename:       
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        plotx= data[indx,0]*8.
        ploty= data[indx,1]*8.
        xrange=[1.2,1.42]
        yrange=[-14.64,-14.23]
        xlabel=r'$J_R\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
        ylabel=r'$L_Z\,(220\,\mathrm{km\,s}^{-1}\,\mathrm{kpc})$'
    elif 'dohist' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        dO1d= numpy.dot(dOdir,dO)
        print "Misalignment:", numpy.arccos(numpy.sum(dOdir*progaa[-1,3:6])/numpy.sqrt(numpy.sum(dOdir**2.)*numpy.sum(progaa[-1,3:6]**2.)))/numpy.pi*180.-180.
        dO1d[dO1d < 0.]*= -1.
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(dO1d,range=[0.,0.4],bins=61,
                            normed=True,
                            xlabel=r'$\Large|\Delta \mathbf{\Omega}_\parallel\Large|\,(\mathrm{Gyr}^{-1})$',
                            histtype='step',color='k',zorder=10)
        #Overplot best-fit Gaussian
        xs= numpy.linspace(0.,0.4,1001)
        print numpy.mean(dO1d), numpy.std(dO1d)
        bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi)/numpy.std(dO1d)\
                                *numpy.exp(-(xs-numpy.mean(dO1d))**2./2./numpy.var(dO1d)),
                            '--',color='k',overplot=True,lw=2.,zorder=2)
        bestfit= optimize.fmin_powell(gausstimesvalue,
                                      numpy.array([numpy.log(numpy.mean(dO1d)*2.),
                                                   numpy.log(numpy.std(dO1d))]),
                                      args=(dO1d,))
        print numpy.exp(bestfit)
        bovy_plot.bovy_plot(xs,gausstimesvalue(bestfit,xs,nologsum=True),
                            '-',color='0.4',overplot=True,lw=2.,zorder=1)
        bovy_plot.bovy_end_print(plotfilename)
        return None
    elif 'dahist' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Gram-Schmidt to get the perpendicular directions
        v2= numpy.array([1.,0.,0.])
        v3= numpy.array([0.,1.,0.])
        u2= v2-numpy.sum(dOdir*v2)*dOdir
        u2/= numpy.sqrt(numpy.sum(u2**2.))
        u3= v3-numpy.sum(dOdir*v3)*dOdir-numpy.sum(u2*v3)*u2
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        dts= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
        #Rewind angles
        dangle-= dO*dts
        newdangle= numpy.empty_like(dangle)
        newdangle[0,:]= numpy.dot(dOdir,dangle)
        newdangle[1,:]= numpy.dot(u2,dangle)
        newdangle[2,:]= numpy.dot(u3,dangle)
        bovy_plot.bovy_print()
        xmin= -0.015
        bovy_plot.bovy_hist(newdangle[2,:].flatten(),range=[xmin,-xmin],bins=61,
                            xlabel=r'$|\Delta \mathbf{\theta}|$',
                            normed=True,lw=2.,
                            color='k',zorder=10,
                            histtype='step')
        #Overplot best-fit Gaussian
        xs= numpy.linspace(xmin,-xmin,1001)
        bovy_plot.bovy_plot(xs,1./numpy.sqrt(2.*numpy.pi)/numpy.std(newdangle[1:,:])\
                                *numpy.exp(-(xs-numpy.mean(newdangle[1:,:]))**2./2./numpy.var(newdangle[1:,:])),
                            '--',color='k',overplot=True,lw=2.,zorder=0)
        print "along", numpy.mean(newdangle[0,:]), numpy.std(newdangle[0,:])
        print "perpendicular 1", numpy.mean(newdangle[1,:]), numpy.std(newdangle[1,:])
        print "perpendicular 2", numpy.mean(newdangle[2,:]), numpy.std(newdangle[2,:])
        bovy_plot.bovy_end_print(plotfilename)
        return None
    elif 'aparopar' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= numpy.fabs(numpy.dot(dO.T,dOdir))
        xrange=[0.,1.3]
        yrange=[0.1,0.3]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$\Large|\Delta \mathbf{\Omega}_\parallel\Large|\,(\mathrm{Gyr}^{-1})$'
        fmt= 'k.'
    elif 'aparoperp' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= numpy.sqrt(numpy.sum(dO**2.,axis=0)\
                              -(numpy.dot(dO.T,dOdir))**2.)
        print numpy.std(ploty)
        xrange=[0.,1.3]
        yrange=[0.,0.005]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$\Large|\Delta \mathbf{\Omega}_\perp\Large|\,(\mathrm{Gyr}^{-1})$'
        fmt= 'k.'
    elif 'aparaperp' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= numpy.sqrt(numpy.sum(dangle**2.,axis=0)\
                              -(numpy.dot(dangle.T,dOdir))**2.)
        xrange=[0.,1.3]
        yrange=[0.,0.03]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$\Large|\Delta \mathbf{\theta}_\perp\Large|$'
        fmt= 'k.'
    elif 'apartime' in plotfilename:
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[indx]
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[indx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[indx]
        #center around 0 (instead of pi)
        thetar-= numpy.pi
        thetap-= numpy.pi
        thetaz-= numpy.pi
        #Frequencies
        Or= data[:,3]
        Op= data[:,4]
        Oz= data[:,5]
        dOr= Or[indx]-numpy.median(Or)
        dOp= Op[indx]-numpy.median(Op)
        dOz= Oz[indx]-numpy.median(Oz)
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        dts= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
        plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
        ploty= dts
        xrange=[0.,1.3]
        yrange=[0.,5.]
        xlabel= r'$\Large|\Delta \mathbf{\theta}_\parallel\Large|$'
        ylabel= r'$t_s\,(\mathrm{Gyr})$'
        fmt= 'k.'
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(plotx,ploty,fmt,
                        xlabel=xlabel,
                        ylabel=ylabel,
                        xrange=xrange,
                        yrange=yrange,zorder=5)
    if includeorbit and 'araz' in plotfilename:
        #plot frequency line
        xs= numpy.array(xrange)
        ys= (xs-numpy.pi)*progaa[-1,5]/progaa[-1,3]+numpy.pi
        bovy_plot.bovy_plot(xs,ys,'k--',overplot=True,
                            zorder=0)
    elif includeorbit and 'arap' in plotfilename:
        #plot frequency line
        xs= numpy.array(xrange)
        ys= (xs-numpy.pi)*progaa[-1,4]/progaa[-1,3]+numpy.pi
        bovy_plot.bovy_plot(xs,ys,'k--',overplot=True,
                            zorder=0)
    elif includeorbit and 'oroz' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,3]*bovy_conversion.freq_in_Gyr(220.,8.),
                            progaa[-1,5]*bovy_conversion.freq_in_Gyr(220.,8.),
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    elif includeorbit and 'orop' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,3]*bovy_conversion.freq_in_Gyr(220.,8.),
                            progaa[-1,4]*bovy_conversion.freq_in_Gyr(220.,8.),
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    elif includeorbit and 'jrjz' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,0]*8.,
                            progaa[-1,2]*8.,
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    elif includeorbit and 'jrjp' in plotfilename:
        bovy_plot.bovy_plot(progaa[-1,0]*8.,
                            progaa[-1,1]*8.,
                            'o',overplot=True,color='0.5',
                            mec='none',ms=8.,
                            zorder=0)
    if includetrack and 'aparopar' in plotfilename:
        #Calculate mean and std of Omegapar as a function of anglepar
        das= numpy.linspace(0.,1.3,1001)
        dOs= numpy.array([sdf.meanOmega(da,oned=True) for da in das])
        sOs= numpy.array([sdf.sigOmega(da) for da in das])
        bovy_plot.bovy_plot(das,dOs*bovy_conversion.freq_in_Gyr(220.,8),
                            '-',color='0.75',lw=2.,overplot=True,zorder=10)
        pyplot.fill_between(das,(dOs+sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            (dOs-sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            color='0.6',zorder=1)
        pyplot.fill_between(das,(dOs+2*sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            (dOs-2*sOs)*bovy_conversion.freq_in_Gyr(220.,8),
                            color='0.8',zorder=0)
        #Also plot the apar at which t_d becomes important
        pyplot.plot([sdf.meanOmega(0.01,oned=True)*sdf._tdisrupt,
                     sdf.meanOmega(0.01,oned=True)*sdf._tdisrupt],
                    [0.,0.3],
                    'k--')                     
    elif includetrack and 'apartime' in plotfilename:
        das= numpy.linspace(0.01,1.3,101)
        mts= numpy.array([sdf.meantdAngle(da) for da in das])
        sts= numpy.array([sdf.sigtdAngle(da) for da in das])
        bovy_plot.bovy_plot(das,mts*bovy_conversion.time_in_Gyr(220.,8),
                            '-',color='0.75',lw=2.,overplot=True,zorder=10)
        pyplot.fill_between(das,(mts+2*sts)*bovy_conversion.time_in_Gyr(220.,8),
                            (mts-2*sts)*bovy_conversion.time_in_Gyr(220.,8),
                            color='0.8',zorder=0)
        pyplot.fill_between(das,(mts+sts)*bovy_conversion.time_in_Gyr(220.,8),
                            (mts-sts)*bovy_conversion.time_in_Gyr(220.,8),
                            color='0.6',zorder=1)
    elif includetrack and 'aparaperp' in plotfilename:
        das= numpy.linspace(0.01,1.3,101)
        sas= numpy.array([sdf.sigangledAngle(da) for da in das])*numpy.sqrt(2.)
        sass= numpy.array([sdf.sigangledAngle(da,simple=True) for da in das])*numpy.sqrt(2.)
        pyplot.fill_between(das,0.,
                            (2*sas),
                            color='0.8',zorder=0)
        pyplot.fill_between(das,0.,
                            (sas),
                            color='0.6',zorder=1)
        pyplot.plot(das,sass,'--',color='w',zorder=7,lw=2.)
    #ax= pyplot.gca()
    #ax.set_rasterized(True)
    bovy_plot.bovy_end_print(plotfilename)
def plot_stream_xz(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    includeorbit= True
    if includeorbit:
        npts= 201
        pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
        pts= numpy.linspace(0.,4.,npts)
        #Calculate progenitor orbit around this point
        pox= numpy.median(data[:,1])
        poy= numpy.median(data[:,3])
        poz= numpy.median(data[:,2])
        povx= numpy.median(data[:,4])
        povy= numpy.median(data[:,6])
        povz= numpy.median(data[:,5])
        pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)
        pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,
                                                 pphi,pZ,cyl=True)
        ppo= Orbit([pR/8.,pvR/220.,pvT/220.,pZ/8.,pvZ/220.,pphi])
        pno= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])
        ppo.integrate(pts,pot)
        pno.integrate(pts,pot)
        pvec= numpy.zeros((3,npts*2-1))
        pvec[0,:npts-1]= pno.x(pts)[::-1][:-1]
        pvec[1,:npts-1]= pno.z(pts)[::-1][:-1]
        pvec[2,:npts-1]= pno.y(pts)[::-1][:-1]
        pvec[0,npts-1:]= ppo.x(pts)
        pvec[1,npts-1:]= ppo.z(pts)
        pvec[2,npts-1:]= ppo.y(pts)
        pvec*= 8.
    includetrack= True
    if includetrack:
        #Setup stream model
        lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
        aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
        obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                          0.88719443,-0.47713334,0.12019596])
        sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                      leading=True,nTrackChunks=_NTRACKCHUNKS,
                      tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.))
        sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                       leading=False,nTrackChunks=_NTRACKCHUNKS,
                       tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.))
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data[:,1],data[:,2],'k,',
                        xlabel=r'$X\,(\mathrm{kpc})$',
                        ylabel=r'$Z\,(\mathrm{kpc})$',
                        xrange=[0.,16.],
                        yrange=[-0.5,11.])
    if includeorbit:
        bovy_plot.bovy_plot(pox,poz,'o',color='0.5',mec='none',overplot=True,ms=8)
        bovy_plot.bovy_plot(pvec[0,:],pvec[1,:],'k--',overplot=True,lw=1.)
    if includetrack:
        d1= 'x'
        d2= 'z'
        sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                      overplot=True,lw=1.,scaleToPhysical=True)
        sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                       overplot=True,lw=1.,scaleToPhysical=True)
        #Also create inset
        pyplot.plot([12.,12.],[0.5,7.5],'k-')
        pyplot.plot([14.5,14.5],[0.5,7.5],'k-')
        pyplot.plot([12.,14.5],[0.5,0.5],'k-')
        pyplot.plot([12.,14.5],[7.5,7.5],'k-')
        pyplot.plot([12.,8.8],[7.5,7.69],'k:')
        pyplot.plot([12.,8.8],[0.5,-0.21],'k:')
        insetAxes= pyplot.axes([0.15,0.12,0.4,0.55])
        pyplot.sca(insetAxes)
        bovy_plot.bovy_plot(data[:,1],data[:,2],'k,',
                            overplot=True)
        bovy_plot.bovy_plot(pvec[0,:],pvec[1,:],'k--',overplot=True,lw=1.)
        sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                      overplot=True,lw=1.,scaleToPhysical=True)
        nullfmt   = NullFormatter()         # no labels
        insetAxes.xaxis.set_major_formatter(nullfmt)
        insetAxes.yaxis.set_major_formatter(nullfmt)
        insetAxes.set_xlim(12.,14.5)
        insetAxes.set_ylim(.5,7.5)
        pyplot.tick_params(\
            axis='both',          # changes apply to the x-axis
            which='both',      # both major and minor ticks are affected
            bottom='off',      # ticks along the bottom edge are off
            top='off',         # ticks along the top edge are off
            left='off',      # ticks along the bottom edge are off
            right='off')         # ticks along the top edge are off
    bovy_plot.bovy_end_print(plotfilename)
Ejemplo n.º 10
0
def plot_stream_lb(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),
                        delimiter=',')
    aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                       'gd1_evol_hitres_aa_01312.dat'),
                          delimiter=',')
    thetar= aadata[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    sindx= numpy.fabs(thetar-numpy.pi) > (1.5*numpy.median(numpy.fabs(thetar-numpy.median(thetar)))) #stars in the stream
    #Transform to (l,b)
    XYZ= bovy_coords.galcenrect_to_XYZ(data[:,1],data[:,3],data[:,2],Xsun=8.)
    lbd= bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2],degree=True)
    vXYZ= bovy_coords.galcenrect_to_vxvyvz(data[:,4],data[:,6],data[:,5],
                                           vsun=[0.,30.24*8.,0.])
    vlbd= bovy_coords.vxvyvz_to_vrpmllpmbb(vXYZ[0],vXYZ[1],vXYZ[2],
                                           lbd[:,0],lbd[:,1],lbd[:,2],
                                           degree=True)
    includeorbit= True
    if includeorbit:
        npts= 201
        pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
        pts= numpy.linspace(0.,4.,npts)
        #Calculate progenitor orbit around this point
        pox= numpy.median(data[:,1])
        poy= numpy.median(data[:,3])
        poz= numpy.median(data[:,2])
        povx= numpy.median(data[:,4])
        povy= numpy.median(data[:,6])
        povz= numpy.median(data[:,5])
        pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)
        pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,
                                                 pphi,pZ,cyl=True)
        ppo= Orbit([pR/8.,pvR/220.,pvT/220.,pZ/8.,pvZ/220.,pphi])
        pno= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])
        ppo.integrate(pts,pot)
        pno.integrate(pts,pot)
        pvec= numpy.zeros((6,npts*2-1))
        pvec[0,:npts-1]= pno.x(pts)[::-1][:-1]
        pvec[1,:npts-1]= pno.z(pts)[::-1][:-1]
        pvec[2,:npts-1]= pno.y(pts)[::-1][:-1]
        pvec[0,npts-1:]= ppo.x(pts)
        pvec[1,npts-1:]= ppo.z(pts)
        pvec[2,npts-1:]= ppo.y(pts)
        pvec[3,:npts-1]= -pno.vx(pts)[::-1][:-1]
        pvec[4,:npts-1]= -pno.vz(pts)[::-1][:-1]
        pvec[5,:npts-1]= -pno.vy(pts)[::-1][:-1]
        pvec[3,npts-1:]= ppo.vx(pts)
        pvec[4,npts-1:]= ppo.vz(pts)
        pvec[5,npts-1:]= ppo.vy(pts)
        pvec[:3,:]*= 8.
        pvec[3:,:]*= 220.
        pXYZ= bovy_coords.galcenrect_to_XYZ(pvec[0,:],pvec[2,:],pvec[1,:],
                                            Xsun=8.)
        plbd= bovy_coords.XYZ_to_lbd(pXYZ[0],pXYZ[1],pXYZ[2],degree=True)
        pvXYZ= bovy_coords.galcenrect_to_vxvyvz(pvec[3,:],pvec[5,:],pvec[4,:],
                                                vsun=[0.,30.24*8.,0.])
        pvlbd= bovy_coords.vxvyvz_to_vrpmllpmbb(pvXYZ[0],pvXYZ[1],pvXYZ[2],
                                                plbd[:,0],plbd[:,1],plbd[:,2],
                                                degree=True)
    includetrack= True
    if includetrack:
        #Setup stream model
        lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
        aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
        obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                          0.88719443,-0.47713334,0.12019596])
        sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                      leading=True,nTrackChunks=_NTRACKCHUNKS,
                      vsun=[0.,30.24*8.,0.],
                      tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                      multi=_NTRACKCHUNKS)
        sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                       leading=False,nTrackChunks=_NTRACKCHUNKS,
                       vsun=[0.,30.24*8.,0.],
                       tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                       multi=_NTRACKCHUNKS)
    #Plot
    bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)
    if 'ld' in plotfilename:
        lbindx= 2
        ylabel=r'$\mathrm{Distance}\,(\mathrm{kpc})$'
        yrange=[0.,30.]
    elif 'lvlos' in plotfilename:
        lbindx= 0
        ylabel=r'$V_\mathrm{los}\,(\mathrm{km\,s}^{-1})$'
        yrange=[-500.,500.]
    elif 'lpmll' in plotfilename:
        lbindx= 1
        ylabel=r'$\mu_{l}\cos b\,(\mathrm{mas\,yr}^{-1})$'
        yrange=[-2.,13.5]
    elif 'lpmbb' in plotfilename:
        lbindx= 2
        ylabel=r'$\mu_{b}\,(\mathrm{mas\,yr}^{-1})$'
        yrange=[-8.,7.]
    else:
        lbindx= 1 
        yrange=[-10.,60.]
        ylabel=r'$\mathrm{Galactic\ latitude}\,(\mathrm{deg})$'
    if 'vlos' in plotfilename or 'pm' in plotfilename:
        #Stream
        bovy_plot.bovy_plot(lbd[sindx,0],vlbd[sindx,lbindx],'k,',
                            xlabel=r'$\mathrm{Galactic\ longitude}\,(\mathrm{deg})$',
                            ylabel=ylabel,
                            xrange=[0.,290.],
                            yrange=yrange)
        #Progenitor
        pindx= copy.copy(True-sindx)
        pindx[0:9900]= False
        bovy_plot.bovy_plot(lbd[pindx,0],vlbd[pindx,lbindx],'k,',overplot=True)
    else:
        bovy_plot.bovy_plot(lbd[sindx,0],lbd[sindx,lbindx],'k,',
                            xlabel=r'$\mathrm{Galactic\ longitude}\,(\mathrm{deg})$',
                            ylabel=ylabel,
                            xrange=[0.,290.],
                            yrange=yrange)
        #Progenitor
        pindx= copy.copy(True-sindx)
        pindx[0:9900]= False
        bovy_plot.bovy_plot(lbd[pindx,0],lbd[pindx,lbindx],'k,',overplot=True)
    if includeorbit:
        if 'vlos' in plotfilename or 'pm' in plotfilename:
            bovy_plot.bovy_plot(plbd[npts,0],pvlbd[npts,lbindx],
                                'o',color='0.5',mec='none',overplot=True,ms=8)
            bovy_plot.bovy_plot(plbd[:,0],pvlbd[:,lbindx],'k--',overplot=True)
        else:
            bovy_plot.bovy_plot(plbd[npts,0],plbd[npts,lbindx],
                                'o',color='0.5',mec='none',overplot=True,ms=8)
            bovy_plot.bovy_plot(plbd[:,0],plbd[:,lbindx],'k--',overplot=True)
    if includetrack:
        d1= 'll'
        if 'vlos' in plotfilename:
            d2= 'vlos'
        elif 'pmll' in plotfilename:
            d2= 'pmll'
        elif 'pmbb' in plotfilename:
            d2= 'pmbb'
        elif 'ld'  in plotfilename:
            d2= 'dist'
        else:
            d2= 'bb'
        sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                      overplot=True,lw=1.)
        sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                       overplot=True,lw=1.)
        #Insets
        if 'vlos' in plotfilename:
            xmin, xmax= 220., 250.
            ymin, ymax= 230., 390.
            pyplot.plot([xmin,xmin],[ymin,ymax],'k-')
            pyplot.plot([xmax,xmax],[ymin,ymax],'k-')
            pyplot.plot([xmin,xmax],[ymin,ymin],'k-')
            pyplot.plot([xmin,xmax],[ymax,ymax],'k-')
            pyplot.plot([xmin,152.],[ymin,-100.],'k:')
            pyplot.plot([xmin,152.],[ymax,460.],'k:')
            insetAxes= pyplot.axes([0.15,0.42,0.38,0.45])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[:,0],vlbd[:,lbindx],'k,',
                                overplot=True)
            sdf.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([240.,240.],[250.,275.],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(241.,255.,r'$25\,\mathrm{km\,s}^{-1}$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin,xmax)
            insetAxes.set_ylim(ymin,ymax)
        elif 'pmll' in plotfilename:
            xmin, xmax= 158.,205.
            ymin, ymax= 10.5, 13.
            pyplot.plot([xmin,xmin],[ymin,ymax],'k-')
            pyplot.plot([xmax,xmax],[ymin,ymax],'k-')
            pyplot.plot([xmin,xmax],[ymin,ymin],'k-')
            pyplot.plot([xmin,xmax],[ymax,ymax],'k-')
            pyplot.plot([xmin,113.],[ymin,6.1],'k:')
            pyplot.plot([xmax,227.],[ymin,6.1],'k:')
            insetAxes= pyplot.axes([0.43,0.12,0.3,0.4])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[sindx,0],vlbd[sindx,lbindx],'k,',
                                overplot=True)
            bovy_plot.bovy_plot(lbd[pindx,0],vlbd[pindx,lbindx],'k,',
                                overplot=True)
            sdf.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([168.5,168.5],[10.75,11.25],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(169.8,10.875,r'$0.5\,\mathrm{mas\,yr}^{-1}$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin,xmax)
            insetAxes.set_ylim(ymin,ymax)
        elif 'pmbb' in plotfilename:
            xmin, xmax= 185., 230.
            ymin, ymax= -7.4, -4.7
            pyplot.plot([xmin,xmin],[ymin,ymax],'k-')
            pyplot.plot([xmax,xmax],[ymin,ymax],'k-')
            pyplot.plot([xmin,xmax],[ymin,ymin],'k-')
            pyplot.plot([xmin,xmax],[ymax,ymax],'k-')
            pyplot.plot([xmin,159.],[ymax,1.],'k:')
            pyplot.plot([xmax,287.],[ymax,1.],'k:')
            #2nd inset
            xmin2, xmax2= 80., 125.
            ymin2, ymax2= 4.2, 5.8
            pyplot.plot([xmin2,xmin2],[ymin2,ymax2],'k-')
            pyplot.plot([xmax2,xmax2],[ymin2,ymax2],'k-')
            pyplot.plot([xmin2,xmax2],[ymin2,ymin2],'k-')
            pyplot.plot([xmin2,xmax2],[ymax2,ymax2],'k-')
            pyplot.plot([xmin2,8.],[ymin2,-1.],'k:')
            pyplot.plot([xmax2,155.],[ymin2,-1.],'k:')
            insetAxes= pyplot.axes([0.55,0.57,0.34,0.3])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[:,0],vlbd[:,lbindx],'k,',
                                overplot=True)
            sdf.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([200.,200.],[-5.75,-5.25],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(201.25,-5.675,r'$0.5\,\mathrm{mas\,yr}^{-1}$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin,xmax)
            insetAxes.set_ylim(ymin,ymax)
            pyplot.tick_params(\
                axis='both',          # changes apply to the x-axis
                which='both',      # both major and minor ticks are affected
                bottom='off',      # ticks along the bottom edge are off
                top='off',         # ticks along the top edge are off
                left='off',      # ticks along the bottom edge are off
                right='off')         # ticks along the top edge are off
            #Also make second inset
            insetAxes= pyplot.axes([0.14,0.12,0.4,0.35])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[:,0],vlbd[:,lbindx],'k,',
                                overplot=True)
            sdft.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([103.,103.],[4.35,4.85],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(104.,4.5,r'$0.5\,\mathrm{mas\,yr}^{-1}$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin2,xmax2)
            insetAxes.set_ylim(ymin2,ymax2)
        elif 'ld' in plotfilename:
            xmin, xmax= 158., 227.
            ymin, ymax= 7.7,9.5
            pyplot.plot([xmin,xmin],[ymin,ymax],'k-')
            pyplot.plot([xmax,xmax],[ymin,ymax],'k-')
            pyplot.plot([xmin,xmax],[ymin,ymin],'k-')
            pyplot.plot([xmin,xmax],[ymax,ymax],'k-')
            pyplot.plot([xmin,70.],[ymax,18.5],'k:')
            pyplot.plot([xmax,248.],[ymax,18.5],'k:')
            #2nd inset
            xmin2, xmax2= 72.,100.
            ymin2, ymax2= 11.5, 16.1
            pyplot.plot([xmin2,xmin2],[ymin2,ymax2],'k-')
            pyplot.plot([xmax2,xmax2],[ymin2,ymax2],'k-')
            pyplot.plot([xmin2,xmax2],[ymin2,ymin2],'k-')
            pyplot.plot([xmin2,xmax2],[ymax2,ymax2],'k-')
            pyplot.plot([xmin2,66.5],[ymax2,15.85],'k:')
            pyplot.plot([xmin2,66.5],[ymin2,0.5],'k:')
            insetAxes= pyplot.axes([0.31,0.6,0.48,0.27])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[sindx,0],lbd[sindx,lbindx],'k,',
                                overplot=True)
            bovy_plot.bovy_plot(lbd[pindx,0],lbd[pindx,lbindx],'k,',
                                overplot=True)
            sdf.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([168.,168.],[8.7,9.2],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(169.7,8.8,r'$0.5\,\mathrm{kpc}$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin,xmax)
            insetAxes.set_ylim(ymin,ymax)
            pyplot.tick_params(\
                axis='both',          # changes apply to the x-axis
                which='both',      # both major and minor ticks are affected
                bottom='off',      # ticks along the bottom edge are off
                top='off',         # ticks along the top edge are off
                left='off',      # ticks along the bottom edge are off
                right='off')         # ticks along the top edge are off
            #Also make second inset
            insetAxes= pyplot.axes([0.13,0.12,0.17,0.4])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[:,0],lbd[:,lbindx],'k,',
                                overplot=True)
            sdft.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([74.,74.],[11.95,12.45],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(76.,12.01,r'$0.5\,\mathrm{kpc}$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin2,xmax2)
            insetAxes.set_ylim(ymin2,ymax2)
        else:
            xmin, xmax= 90., 165.
            ymin, ymax= 47., 59.
            pyplot.plot([xmin,xmin],[ymin,ymax],'k-')
            pyplot.plot([xmax,xmax],[ymin,ymax],'k-')
            pyplot.plot([xmin,xmax],[ymin,ymin],'k-')
            pyplot.plot([xmin,xmax],[ymax,ymax],'k-')
            pyplot.plot([xmin,70.],[ymin,31.],'k:')
            pyplot.plot([xmax,213.],[ymin,31.],'k:')
            insetAxes= pyplot.axes([0.31,0.12,0.38,0.45])
            pyplot.sca(insetAxes)
            bovy_plot.bovy_plot(lbd[sindx,0],lbd[sindx,lbindx],'k,',
                                overplot=True)
            bovy_plot.bovy_plot(lbd[pindx,0],lbd[pindx,lbindx],'k,',
                                overplot=True)
            sdft.plotProgenitor(d1=d1,d2=d2,color='k',ls='--',
                                overplot=True)
            sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                           overplot=True,lw=1.)
            #Plot approximate scale
            bovy_plot.bovy_plot([115.,115.],[48.5,49.5],'k-',lw=2.,
                                overplot=True)
            bovy_plot.bovy_text(117.2,48.5,r'$1^\circ$',
                                size=16.)
            nullfmt   = NullFormatter()         # no labels
            insetAxes.xaxis.set_major_formatter(nullfmt)
            insetAxes.yaxis.set_major_formatter(nullfmt)
            insetAxes.set_xlim(xmin,xmax)
            insetAxes.set_ylim(ymin,ymax)
        pyplot.tick_params(\
            axis='both',          # changes apply to the x-axis
            which='both',      # both major and minor ticks are affected
            bottom='off',      # ticks along the bottom edge are off
            top='off',         # ticks along the top edge are off
            left='off',      # ticks along the bottom edge are off
            right='off')         # ticks along the top edge are off
    bovy_plot.bovy_end_print(plotfilename)
def make_action_movie(aa=False):
    skip= 1
    if aa:
        savedir= '../movies/aa/'
        savedirpng= '../movies/aa/pngs/'
        moviefilename= os.path.join(savedir,'aa_orbit_skip%i.mpg' % skip)
        basefilename= 'aa_'
        xrange=[-0.7,7.]
        yrange=[-0.7,7.]
        xlabel=r'$\theta_R$'
        ylabel=r'$\theta_Z$'    
    else:
        savedir= '../movies/actions/'
        savedirpng= '../movies/actions/pngs/'
        basefilename= 'real_'
        moviefilename= os.path.join(savedir,'real_orbit_skip%i.mpg' % skip)
        xrange=[0.,7.]
        yrange=[-4.25,4.25]
        xlabel=r'$R$'
        ylabel=r'$Z$'    
    pot= potential.MWPotential
    o= Orbit([1.,0.8,1.5,0.8,0.5,0.])
    ts= numpy.linspace(0.,300.,1000)
    o.integrate(ts,pot)
    Rs= numpy.zeros(len(ts)+23)
    zs= numpy.zeros(len(ts)+23)
    Rs[:23]= numpy.nan
    zs[:23]= numpy.nan
    if aa:
        aAIA= actionAngleIsochroneApprox(b=5.,pot=pot)
        acfs= aAIA.actionsFreqsAngles(o,maxn=3)
        Rs[23:]= (acfs[6]+acfs[3]*ts) % (2.*numpy.pi)
        zs[23:]= (acfs[8]+acfs[5]*ts) % (2.*numpy.pi)
    else:
        Rs[23:]= o.R(ts)
        zs[23:]= o.z(ts)
        print numpy.nanmax(Rs)
        print numpy.nanmax(numpy.fabs(zs))
    if True:
        for ii in range(len(ts)-1):       
            bovy_plot.bovy_print()
            bovy_plot.bovy_plot(Rs[ii:ii+24:skip],zs[ii:ii+24:skip],
                                scatter=True,color='k',
                                s=numpy.arange(24/skip)*skip,
                                xlabel=xlabel,
                                ylabel=ylabel,
                                xrange=xrange,
                                yrange=yrange)
            bovy_plot.bovy_end_print(os.path.join(savedirpng,basefilename+'%s.png' % str(ii).zfill(5)))
    #Turn into movie
    framerate= 25
    bitrate= 1000000
    try:
        subprocess.check_call(['ffmpeg',
                               '-i',
                               os.path.join(savedirpng,basefilename+'%05d.png'),
                               '-y',
                               '-r',str(framerate),
                               '-b', str(bitrate),
                               moviefilename])
    except subprocess.CalledProcessError:
        print "'ffmpeg' failed"
    return None
def plot_stream_xz(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1-hisigv_evol_00041.dat'),
                        delimiter=',')
    includeorbit= True
    if includeorbit:
        npts= 201
        pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
        pts= numpy.linspace(0.,17.,npts)
        #Calculate progenitor orbit around this point
        pox= numpy.median(data[:,1])
        poy= numpy.median(data[:,3])
        poz= numpy.median(data[:,2])
        povx= numpy.median(data[:,4])
        povy= numpy.median(data[:,6])
        povz= numpy.median(data[:,5])
        pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)
        pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,
                                                 pphi,pZ,cyl=True)
        ppo= Orbit([pR/8.,pvR/220.,pvT/220.,pZ/8.,pvZ/220.,pphi])
        pno= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])
        ppo.integrate(pts,pot)
        pno.integrate(pts,pot)
        pvec= numpy.zeros((3,npts*2-1))
        pvec[0,:npts-1]= pno.x(pts)[::-1][:-1]
        pvec[1,:npts-1]= pno.z(pts)[::-1][:-1]
        pvec[2,:npts-1]= pno.y(pts)[::-1][:-1]
        pvec[0,npts-1:]= ppo.x(pts)
        pvec[1,npts-1:]= ppo.z(pts)
        pvec[2,npts-1:]= ppo.y(pts)
        pvec*= 8.
    includetrack= True
    if includetrack:
        #Setup stream model
        lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)
        aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)
        obs= numpy.array([1.56148083,0.35081535,-1.15481504,
                          0.88719443,-0.47713334,0.12019596])
        sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                      leading=True,nTrackChunks=_NTRACKCHUNKS,
                      tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                      deltaAngleTrack=13.5,multi=_NTRACKCHUNKS)
        sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,
                       leading=False,nTrackChunks=_NTRACKCHUNKS,
                       tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),
                       deltaAngleTrack=13.5,multi=_NTRACKCHUNKS)
    #Plot
    bovy_plot.bovy_print()
    bovy_plot.bovy_plot(data[:,1],data[:,2],'k,',
                        xlabel=r'$X\,(\mathrm{kpc})$',
                        ylabel=r'$Z\,(\mathrm{kpc})$',
                        xrange=[-30.,30.],
                        yrange=[-20.,20])
    if includeorbit:
        bovy_plot.bovy_plot(pox,poz,'o',color='0.5',mec='none',overplot=True,ms=8)
        bovy_plot.bovy_plot(pvec[0,:],pvec[1,:],'k--',overplot=True,lw=1.)
    if includetrack:
        d1= 'x'
        d2= 'z'
        sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                      overplot=True,lw=1.,scaleToPhysical=True)
        sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,
                       overplot=True,lw=1.,scaleToPhysical=True)
    bovy_plot.bovy_text(r'$M^p = 2\times 10^7\,M_\odot$'+'\n'+
                        r'$\sigma_v^p = 14\,\mathrm{km\,s}^{-1}$',
                        top_left=True,size=16.)
    bovy_plot.bovy_end_print(plotfilename)