Пример #1
0
def test_units():
    import galpy.util.bovy_conversion as conversion
    print(conversion.force_in_pcMyr2(220.,8.))#pc/Myr^2
    assert numpy.fabs(conversion.force_in_pcMyr2(220.,8.)-6.32793804994) < 10.**-4., 'unit conversion has changed'
    print(conversion.dens_in_msolpc3(220.,8.))#Msolar/pc^3
    assert numpy.fabs(conversion.dens_in_msolpc3(220.,8.)-0.175790330079) < 10.**-4., 'unit conversion has changed'
    print(conversion.surfdens_in_msolpc2(220.,8.))#Msolar/pc^2
    assert numpy.fabs(conversion.surfdens_in_msolpc2(220.,8.)-1406.32264063) < 10.**-4., 'unit conversion has changed'
    print(conversion.mass_in_1010msol(220.,8.))#10^10 Msolar
    assert numpy.fabs(conversion.mass_in_1010msol(220.,8.)-9.00046490005) < 10.**-4., 'unit conversion has changed'
    print(conversion.freq_in_Gyr(220.,8.))#1/Gyr
    assert numpy.fabs(conversion.freq_in_Gyr(220.,8.)-28.1245845523) < 10.**-4., 'unit conversion has changed'
    print(conversion.time_in_Gyr(220.,8.))#Gyr
    assert numpy.fabs(conversion.time_in_Gyr(220.,8.)-0.0355560807712) < 10.**-4., 'unit conversion has changed'
    return None
Пример #2
0
    def lindbladR(self,OmegaP,m=2,**kwargs):
        """
        
        NAME:
        
           lindbladR
        
        PURPOSE:
        
            calculate the radius of a Lindblad resonance
        
        INPUT:
        
           OmegaP - pattern speed (can be Quantity)

           m= order of the resonance (as in m(O-Op)=kappa (negative m for outer)
              use m='corotation' for corotation
              +scipy.optimize.brentq xtol,rtol,maxiter kwargs
        
        OUTPUT:
        
           radius of Linblad resonance, None if there is no resonance
        
        HISTORY:
        
           2011-10-09 - Written - Bovy (IAS)
        
        """
        if _APY_LOADED and isinstance(OmegaP,units.Quantity):
            OmegaP= OmegaP.to(1/units.Gyr).value/freq_in_Gyr(self._vo,self._ro)
        return lindbladR(self,OmegaP,m=m,use_physical=False,**kwargs)
Пример #3
0
def test_kickdO():
    from galpy.util import bovy_conversion
    # Closest one to the impact point, should be close to zero
    tIndx= numpy.argmin(numpy.fabs(sdf_sanders15._kick_interpolatedThetasTrack\
                                       -sdf_sanders15._impact_angle))
    assert numpy.all(numpy.fabs(sdf_sanders15._kick_dOap[tIndx,:3]*bovy_conversion.freq_in_Gyr(sdf_sanders15._Vnorm,sdf_sanders15._Rnorm)) < 0.03), 'Kick near the impact point not close to zero'
    # The peak, size and location
    assert numpy.fabs(numpy.amax(numpy.fabs(sdf_sanders15._kick_dOap[:,0]*bovy_conversion.freq_in_Gyr(sdf_sanders15._Vnorm,sdf_sanders15._Rnorm)))-0.085) < 0.01, 'Peak dOR incorrect'
    assert sdf_sanders15._kick_interpolatedThetasTrack[numpy.argmax(sdf_sanders15._kick_dOap[:,0])]-sdf_sanders15._impact_angle < 0., 'Location of peak dOR incorrect'
    assert numpy.fabs(numpy.amax(numpy.fabs(sdf_sanders15._kick_dOap[:,1]*bovy_conversion.freq_in_Gyr(sdf_sanders15._Vnorm,sdf_sanders15._Rnorm)))-0.07) < 0.01, 'Peak dOp incorrect'
    assert sdf_sanders15._kick_interpolatedThetasTrack[numpy.argmax(sdf_sanders15._kick_dOap[:,1])]-sdf_sanders15._impact_angle < 0., 'Location of peak dvy incorrect'
    assert numpy.fabs(numpy.amax(numpy.fabs(sdf_sanders15._kick_dOap[:,2]*bovy_conversion.freq_in_Gyr(sdf_sanders15._Vnorm,sdf_sanders15._Rnorm)))-0.075) < 0.01, 'Peak dOz incorrect'
    assert sdf_sanders15._kick_interpolatedThetasTrack[numpy.argmax(sdf_sanders15._kick_dOap[:,2])]-sdf_sanders15._impact_angle < 0., 'Location of peak dOz incorrect'
    # Close to zero far from impact point
    tIndx= numpy.argmin(numpy.fabs(sdf_sanders15._kick_interpolatedThetasTrack\
                                       -sdf_sanders15._impact_angle-1.5))
    assert numpy.all(numpy.fabs(sdf_sanders15._kick_dOap[tIndx,:3]*bovy_conversion.freq_in_Gyr(sdf_sanders15._Vnorm,sdf_sanders15._Rnorm)) < 0.03), 'Kick far the impact point not close to zero'
    return None
def readaA():
    """Read the action angle data for the stream, and process it"""
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                     'gd1_evol_hitres_aa_01312.dat'),
                        delimiter=',')
    thetar= data[:,6]
    print "Median angles:", numpy.median(thetar), numpy.median(data[:,7]),\
        numpy.median(data[:,8])
    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.))
    dOpar= numpy.dot(dOdir,dO)
    #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
    dOperp1= numpy.dot(u2,dO)
    dOperp2= numpy.dot(u3,dO)
    #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)
    return (thetar,thetap,thetaz,Or[indx],Op[indx],Oz[indx],\
                dO,dangle,
            dOpar,dOperp1,dOperp2,newdangle,Or,Op,Oz)
Пример #5
0
def eig(filename):

    # compute direction in cylindrical
    data    = np.loadtxt(dir+filename)
    thetar  = data[:,6]
    thetar  = (np.pi+(thetar-np.median(thetar))) % (2.*np.pi)
    indx    = np.fabs(thetar-np.pi) > (5.*np.median(np.fabs(thetar-np.median(thetar))))
    
    #Frequencies
    Or      = data[:,3]
    Op      = data[:,4]
    Oz      = data[:,5]
    dOr     = Or[indx]-np.median(Or)
    dOp     = Op[indx]-np.median(Op)
    dOz     = Oz[indx]-np.median(Oz)
    dO      = np.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
    dO4dir  = copy.copy(dO)
    dO4dir[:,dO4dir[:,0] < 0.]*= -1.
    dOdir   = np.median(dO4dir,axis=1)
    dOdir  /= np.sqrt(np.sum(dOdir**2.))

    # direction in cylindrical
    Or, Ophi, Oz = dOdir[0], dOdir[1], dOdir[2]
    
    
    
    # cheking for cylindrical
    if (Ophi<(2*np.pi)):
        Ophi -= (2*np.pi)

    # convert cylindrical to cartesian
    x,y,z = bovy_coords.cyl_to_rect(Or, Ophi, Oz)
    
    # convert cartesian to spherical
    R, theta_sph, phi_sph = cart_spher(x,y,z)
    
    
    # checking for spherical
    if (theta_sph> (2*np.pi)):
        theta_sph -= (2*np.pi)
    elif (theta_sph< (-2*np.pi)):
        theta_sph += (2*np.pi)

    if (phi_sph>np.pi):
        phi_sph -= np.pi

    elif (phi_sph<-np.pi):
        phi_sph += np.pi


    val = np.array([R, theta_sph, phi_sph])
    return val
Пример #6
0
def strip_time(filename_tail):
    """
    Parameter:
    -------------------------------------------------------
    
        
        
    Returns:
    -------------------------------------------------------
        Stripping time (eq. 3 in Bovy 2014)
    
    """
    '''
    if ptype == "Log":
        data      = np.loadtxt(filename_tail)
    elif ptype =="MW":
        data      = np.loadtxt(filename_tail)
    '''
    data      = np.loadtxt(filename_tail)
    
    thetar    = data[:,6]
    thetar    = (np.pi+(thetar-np.median(thetar))) % (2.*np.pi)
    indx      = np.fabs(thetar-np.pi) > (5.*np.median(np.fabs(thetar-np.median(thetar))))
    thetar    = thetar[indx]
    thetap    = data[:,7]
    thetap    = (np.pi+(thetap-np.median(thetap))) % (2.*np.pi)
    thetap    = thetap[indx]
    thetaz    = data[:,8]
    thetaz    = (np.pi+(thetaz-np.median(thetaz))) % (2.*np.pi)
    thetaz    = thetaz[indx]
    
    # center around 0 (instead of pi)
    thetar   -= np.pi
    thetap   -= np.pi
    thetaz   -= np.pi
    
    # Frequencies
    Or        = data[:,3]
    Op        = data[:,4]
    Oz        = data[:,5]
    dOr       = Or[indx]-np.median(Or)
    dOp       = Op[indx]-np.median(Op)
    dOz       = Oz[indx]-np.median(Oz)
    
    # Times
    dangle    = np.vstack((thetar,thetap,thetaz))
    dO        = np.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)

    ts        = np.sum(dO*dangle,axis=0)/np.sum(dO**2.,axis=0)
    del_freq  = np.sum(dO**2.,    axis=0)
    del_theta = np.sum(dangle**2.,axis=0)
    return  dO, dangle, del_freq, del_theta, ts
Пример #7
0
def test_interpKickdO():
    from galpy.util import bovy_conversion
    freqConv= bovy_conversion.freq_in_Gyr(sdf_sanders15._Vnorm,sdf_sanders15._Rnorm)
    # Bunch of spot checks at some interesting angles
    # Impact angle
    theta= sdf_sanders15._impact_angle
    assert numpy.fabs(sdf_sanders15._kick_interpdOpar(theta)*freqConv) < 10.**-4., 'Frequency kick at the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOperp0(theta)*freqConv) < 10.**-4., 'Frequency kick at the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOperp1(theta)*freqConv) < 10.**-4., 'Frequency kick at the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOr(theta)*freqConv) < 10.**-4., 'Frequency kick at the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOp(theta)*freqConv) < 10.**-4., 'Frequency kick at the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOz(theta)*freqConv) < 10.**-4., 'Frequency kick at the impact point is not zero'
    # random one
    theta= sdf_sanders15._impact_angle-0.25
    assert numpy.fabs(sdf_sanders15._kick_interpdOpar(theta)*freqConv+0.07) < 0.002, 'Frequency kick near the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOperp0(theta)*freqConv) < 0.002, 'Frequency kick near the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOperp1(theta)*freqConv) < 0.003, 'Frequency kick near the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOr(theta)*freqConv-0.05) < 0.01, 'Frequency kick near the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOp(theta)*freqConv-0.035) < 0.01, 'Frequency kick near the impact point is not zero'
    assert numpy.fabs(sdf_sanders15._kick_interpdOz(theta)*freqConv-0.04) < 0.01, 'Frequency kick near the impact point is not zero'
    return None
Пример #8
0
def hist_fig4(filename):

    """
    Parameter:
    -------------------------------------------------------
        
        
        
    Returns:
    -------------------------------------------------------
        
    """
    
    data    = np.loadtxt(filename)
    thetar  = data[:,6]
    thetar  = (np.pi+(thetar-np.median(thetar))) % (2.*np.pi)
    indx    = np.fabs(thetar-np.pi) > (5.*np.median(np.fabs(thetar-np.median(thetar))))
    
    #Frequencies
    Or  = data[:,3]
    Op  = data[:,4]
    Oz  = data[:,5]
    dOr = Or[indx]-np.median(Or)
    dOp = Op[indx]-np.median(Op)
    dOz = Oz[indx]-np.median(Oz)
    dO  = np.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
    dO4dir = copy.copy(dO)
    dO4dir[:,dO4dir[:,0] < 0.] *= -1.
    dOdir  = np.median(dO4dir, axis=1)
    dOdir /= np.sqrt(np.sum(dOdir**2.))
    dO1d   = np.dot(dOdir,dO)
    dO1d[dO1d < 0.] *= -1.
    
    dOpar = np.dot(dOdir,dO)
    
    return dO1d, dOdir #dOpar
def plot_all(ptype):
    
    """
    Parameters
    ----------------------------------------------------------------------------------
        ptype : type of simulation. For example if it is Log2e4 (Logarithmic potential
                with mass of M = 2 X 10^4 or MW2e4 (Milky Way 2014 potential with the
                same mass)
        
        
    Return
    ----------------------------------------------------------------------------------
        Does not return anything. It only plots the specified set of variables set
        by plot_type argument.
    """
    
    plt.ion()

    fact  = bovy_conversion.freq_in_Gyr(220., 8.)

    if ptype == "Log2e4":
        val_prog = aA_prog("Log")
        plt.plot(val_prog[3]*fact, val_prog[5]*fact, "mo", ms=10, label="progenitor")
        i = 0
        for names in fnames_Log2e4:
            omegaR_t, omegaz_t = plot_fig2(dirname_Log,names,"OzOr")
            plt.plot(omegaR_t*fact, omegaz_t*fact, 'o', color=clist_Log[i],ms=2,label="$W_0= $" + W0_Log2e4[i])
            plt.title(r"Log potential, $M = 2 \times 10^4$")
            i += 1

    elif ptype == "MW2e4":
        val_prog = aA_prog("MW")
        plt.plot(val_prog[3]*fact, val_prog[5]*fact, "mo", ms=10, label="progenitor")
        i = 0
        for names in fnames_MW2e4:
            omegaR_t, omegaz_t = plot_fig2(dirname_MW,names, "OzOr")
            plt.plot(omegaR_t*fact, omegaz_t*fact,'o',  color=clist_MW2e4[i],label="$W_0= $" + W0_MW2e4[i])
            plt.title(r"MW2014 potential, $M = 2 \times 10^4$")
            i += 1

    elif ptype == "Log2e6":
        val_prog = aA_prog("Log")
        plt.plot(val_prog[3]*fact, val_prog[5]*fact, "mo", ms=10, label="progenitor")
        i = 0
        for names in fnames_Log2e6:
            omegaR_t, omegaz_t = plot_fig2(dirname_Log,names, "OzOr")
            plt.plot(omegaR_t*fact, omegaz_t*fact, 'o', ms=2, color=clist_Log[i],label="$W_0= $" + W0_Log2e6[i])
            plt.title(r"Log potential, $M = 2 \times 10^6$")
            i += 1

    elif ptype == "Log2e7":
        val_prog = aA_prog("Log")
        plt.plot(val_prog[3]*fact, val_prog[5]*fact, "mo", ms=10, label="progenitor")
        i = 0
        for names in fnames_Log2e7:
            omegaR_t, omegaz_t = plot_fig2(dirname_Log,names, "OzOr")
            plt.plot(omegaR_t*fact, omegaz_t*fact, 'o', ms = 2, color=clist_Log[i],label="$W_0= $" + W0_Log2e7[i])
            plt.title(r"Log potential, $M = 2 \times 10^7$")
            i += 1

    plt.xlabel("$\Omega_R (\mathrm{Gyr^{-1}})$", fontsize=20)
    plt.ylabel("$\Omega_z (\mathrm{Gyr^{-1}})$", fontsize=20)
    plt.legend(loc='best')
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
Пример #11
0
import numpy            as    np
import matplotlib.pylab as    plt
import galpy
from   galpy.util      import bovy_conversion
from   nemo_funcs      import tail_cut

R0 = 8.
V0 = 220.

fact  = bovy_conversion.freq_in_Gyr(220., 8.)
fact2 = bovy_conversion.freq_in_kmskpc(220., 8.)

#prog = np.loadtxt("/Users/anita/dyn-modeling-streams-2014/sim/test.dat", delimiter=',')
#tail = np.loadtxt("/Users/anita/Desktop/Meeting_2/tail_concatenated_final.txt")

tail = np.loadtxt("/home/bahmanyar/Github/AST1501/Codes/concatenated_2.0.txt")

tail = tail.T
#JR_p, Lz_p, Jz_p, omegaR_p, omega_phi_p, omegaz_p, thetaR_p, theta_phi_p, thetaz_p = prog[:,0], prog[:,1], prog[:,2], prog[:,3], prog[:,4], prog[:,5], prog[:,6], prog[:,7], prog[:,8]
JR_t, Lz_t, Jz_t, omegaR_t, omega_phi_t, omegaz_t, thetaR_t, theta_phi_t, thetaz_t = tail[:,0], tail[:,1], tail[:,2], tail[:,3], tail[:,4], tail[:,5], tail[:,6], tail[:,7], tail[:,8]

indx_t = tail_cut(tail)
#indx_p = tail_cut(prog)

# Tail
omegaR_t, omega_phi_t, omegaz_t,  = tail[indx_t,3], tail[indx_t,4], tail[indx_t,5]
JR_t, Lz_t, Jz_t                  = tail[indx_t,0], tail[indx_t,1], tail[indx_t,2]
thetaR_t, theta_phi_t, thetaz_t   = tail[indx_t,6], tail[indx_t,7], tail[indx_t,8]

thetaR_t    = (np.pi+(thetaR_t-np.median(tail[:,6]))) % (2.*np.pi)
theta_phi_t = (np.pi+(theta_phi_t-np.median(tail[:,7]))) % (2.*np.pi)
Пример #12
0
def test_freq_in_Gyr():
    #Test the scaling, as 1/time, should scale as velocity/position
    vofid, rofid= 200., 8.
    assert numpy.fabs(2.*bovy_conversion.freq_in_Gyr(vofid,rofid)/bovy_conversion.freq_in_Gyr(2.*vofid,rofid)-1.) < 10.**-10., 'freq_in_Gyr did not work as expected'
    assert numpy.fabs(.5*bovy_conversion.freq_in_Gyr(vofid,rofid)/bovy_conversion.freq_in_Gyr(vofid,2*rofid)-1.) < 10.**-10., 'freq_in_Gyr did not work as expected'
    return None
Пример #13
0
def make_sim_movie_oparapar(proj='aaarazap',
                            skippng=False,
                            aas=False):
    #Directories
    if aas:
        snapaadir= 'snaps_aas/'
        aastr= 'aas'
    else:
        snapaadir= 'snaps_aai/'
        aastr= 'aai'
    savedirpng= './movies/oph_aa/pngs/'
    basefilename= 'oph_evol_%s_' % aastr
    moviefilename= 'oph_evol_%s' % aastr
    if True:
        basefilename+= 'oparapar_'
        moviefilename+= '_oparapar'
        xlabel=r'$|\Delta\theta_\parallel|$'
        ylabel=r'$|\Delta\Omega_\parallel|$'
        xrange=[0.,1.3]
        yrange=[0.1,0.3]
        zrange=[0.,4.5]
    if not skippng:
        nt= len(glob.glob(os.path.join(snapaadir,
                                       'oph_evol_hitres_aa_*.dat')))
        #Load one of the final snapshots first, determine which stars are debris and when they were stripped
        data= numpy.loadtxt(os.path.join(snapaadir,
                                         'oph_evol_hitres_aa_%s.dat' % str(1287).zfill(5)),
                            delimiter=',')
        thetar= data[:,6]
        thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
        debrisIndx= numpy.fabs(thetar-numpy.pi) > (6.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
        thetar= thetar[debrisIndx]
        #Calculate times at which stars were stripped, angles
        thetap= data[:,7]
        thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
        thetap= thetap[debrisIndx]
        thetaz= data[:,8]
        thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
        thetaz= thetaz[debrisIndx]
        #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[debrisIndx]-numpy.median(Or)
        dOp= Op[debrisIndx]-numpy.median(Op)
        dOz= Oz[debrisIndx]-numpy.median(Oz)
        #Times
        dangle= numpy.vstack((thetar,thetap,thetaz))
        dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
        dts= numpy.empty(data.shape[0])
        dts[debrisIndx]= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
        #Direction in which the stream spreads
        dO4dir= copy.copy(dO)
        try:
            dO4dir[:,dO4dir[:,0] < 0.]*= -1.
        except IndexError:
            pass
        dOdir= numpy.median(dO4dir,axis=1)
        dOdir/= numpy.sqrt(numpy.sum(dOdir**2.))
        for ii in range(80,nt):#Skip the first 100, because nothing happens anyway
            #Read data
            data= numpy.loadtxt(os.path.join(snapaadir,
                                       'oph_evol_hitres_aa_%s.dat' % str(ii).zfill(5)),
                                delimiter=',')
            if True:
                indx= dts > (1312-ii)/1312.*5.125/1.0227121655399913
                indx*= debrisIndx
                tdts= dts[indx]
                if numpy.sum(indx) == 0:
                    data= -1000.+numpy.random.uniform(size=(20,9))*50.
                    indx= numpy.ones(20,dtype='bool')
                    tdts= -1.*numpy.ones(20)
            if True:
                thetar= data[:,6]
                thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
                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, taken from final snapshot
                #Times
                dangle= numpy.vstack((thetar,thetap,thetaz))
                plotx= numpy.fabs(numpy.dot(dangle.T,dOdir))
                ploty= numpy.fabs(numpy.dot(dO.T,dOdir))
                plotz= tdts
            bovy_plot.bovy_print()
            bovy_plot.bovy_plot(plotx,ploty,c=plotz,scatter=True,
                                edgecolor='none',s=9.5,
                                xlabel=xlabel,
                                ylabel=ylabel,
                                xrange=xrange,
                                yrange=yrange,
                                crange=zrange,
                                vmin=zrange[0],vmax=zrange[1],zorder=2)
            bovy_plot.bovy_end_print(os.path.join(savedirpng,basefilename+'%s.png' % str(ii-80).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+'.mpg'])
    except subprocess.CalledProcessError:
        print "'ffmpeg' failed"
    return None
def plot_stream_times(plotfilename):
    #Read stream
    data= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,
                                     'gd1_evol_hitres_aa_01312.dat'),
                        delimiter=',')
    #Calculate times at which stars were stripped, angles
    thetar= data[:,6]
    thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)
    indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))
    thetar= thetar[indx]
    thetap= data[:,7]
    thetap= (numpy.pi+(thetap-numpy.median(thetap))) % (2.*numpy.pi)
    thetap= thetap[indx]
    thetaz= data[:,8]
    thetaz= (numpy.pi+(thetaz-numpy.median(thetaz))) % (2.*numpy.pi)
    thetaz= thetaz[indx]
    #center around 0 (instead of pi)
    thetar-= numpy.pi
    thetap-= numpy.pi
    thetaz-= numpy.pi
    #Frequencies
    Or= data[:,3]
    Op= data[:,4]
    Oz= data[:,5]
    dOr= Or[indx]-numpy.median(Or)
    dOp= Op[indx]-numpy.median(Op)
    dOz= Oz[indx]-numpy.median(Oz)
    #Times
    dangle= numpy.vstack((thetar,thetap,thetaz))
    dO= numpy.vstack((dOr,dOp,dOz))*bovy_conversion.freq_in_Gyr(220.,8.)
    dts= numpy.sum(dO*dangle,axis=0)/numpy.sum(dO**2.,axis=0)
    if 'hist' in plotfilename:
        bovy_plot.bovy_print()
        bovy_plot.bovy_hist(dts,range=[0.,6.],bins=13,
                            xlabel=r'$t_s\ (\mathrm{Gyr})$',
                            histtype='step',color='k',normed=True,lw=2.)
        bovy_plot.bovy_hist(dts,range=[0.,6.],bins=61,normed=True,
                            overplot=True,ls='dotted',histtype='step',
                            color='0.5',lw=2.)
        includeorbit= False #bc pericenter passage doesn't seem to work
        if includeorbit:
            npts= 10001
            pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)
            ts= numpy.linspace(0.,5./bovy_conversion.time_in_Gyr(220.,8.),
                               npts)
            #Calculate progenitor orbit around this point
            pox= numpy.median(data[:,1])
            poy= numpy.median(data[:,3])
            poz= numpy.median(data[:,2])
            povx= numpy.median(data[:,4])
            povy= numpy.median(data[:,6])
            povz= numpy.median(data[:,5])
            pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)
            pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,
                                                     pphi,pZ,cyl=True)
            o= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])
            o.integrate(ts,pot)
            rs= numpy.sqrt(o.R(ts)**2.+o.z(ts)**2.)
            #Find local minima
            periIndx= numpy.r_[True, rs[1:] < rs[:-1]] & numpy.r_[rs[:-1] < rs[1:], True]
            for ii in range(numpy.sum(periIndx)):
                bovy_plot.bovy_plot([ts[periIndx][ii]*bovy_conversion.time_in_Gyr(220.,8.),
                                     ts[periIndx][ii]*bovy_conversion.time_in_Gyr(220.,8.)],
                                    [0.,1.],overplot=True,ls='--',lw=1.,
                                    color='0.5')
    elif 'dO' in plotfilename:
        bovy_plot.bovy_print()
        bovy_plot.bovy_plot(dts,
                            numpy.sqrt(numpy.sum(dO**2.,axis=0)),
                            'k.',
                            xrange=[0.,6.],
                            yrange=[0.1,0.35],
                            xlabel=r'$t_s\ (\mathrm{Gyr})$',
                            ylabel=r'$|\Delta \mathbf{\Omega}|\ (\mathrm{Gyr}^{-1})$')
    elif 'da' in plotfilename:
        bovy_plot.bovy_print()
        bovy_plot.bovy_plot(dts,
                            numpy.sqrt(numpy.sum(dangle**2.,axis=0)),
                            'k.',
                            xrange=[0.,6.],
                            yrange=[0.,1.5],
                            xlabel=r'$t_s\ (\mathrm{Gyr})$',
                            ylabel=r'$|\Delta \boldsymbol\theta|$')
    bovy_plot.bovy_end_print(plotfilename)
    return None
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)