Example #1
0
 def _zforce(self,R,z,phi=0.,t=0.):
     if self._interpzforce and self._enable_c:
         if isinstance(R,float):
             R= numpy.array([R])
         if isinstance(z,float):
             z= numpy.array([z])
         if self._zsym:
             return sign(z) * eval_force_c(self,R,numpy.fabs(z),zforce=True)[0]
         else:
             return eval_force_c(self,R,z,zforce=True)[0]
     from galpy.potential import evaluatezforces
     if self._interpzforce:
         if isinstance(R,float):
             return self._zforce(numpy.array([R]),numpy.array([z]))
         out= numpy.empty_like(R)
         indx= (R >= self._rgrid[0])*(R <= self._rgrid[-1])
         if numpy.sum(indx) > 0:
             if self._zsym:
                 if self._logR:
                     out[indx]= sign(z) * self._zforceInterp.ev(numpy.log(R[indx]),numpy.fabs(z[indx]))
                 else:
                     out[indx]= sign(z) * self._zforceInterp.ev(R[indx],numpy.fabs(z[indx]))
             else:
                 if self._logR:
                     out[indx]= self._zforceInterp.ev(numpy.log(R[indx]),z[indx])
                 else:
                     out[indx]= self._zforceInterp.ev(R[indx],z[indx])
         if numpy.sum(True-indx) > 0:
             out[True-indx]= evaluatezforces(R[True-indx],
                                             z[True-indx],
                                             self._origPot)
         return out
     else:
         return evaluatezforces(R,z,self._origPot)
Example #2
0
def accmaps(npix=200):
    #First setup the potential, the following are the best-fit parameters from the Sec. 5 of our paper
    #params= numpy.array([-1.33663190049,0.998420232634,-3.49031638164,0.31949840593,-1.63965169376])
    params= numpy.array([-1.33663190049,0.998420232634,-3.0736938150237028,0.31949840593,-1.63965169376]) #this has a scale height of 360 pc
    try:
        pot= setup_potential(params)
    except RuntimeError: #if this set of parameters gives a nonsense potential
        raise
    #Setup grid and output
    Rs= numpy.linspace(0.01,20.,npix)/_REFR0
    Zs= numpy.linspace(0.,20.,npix)/_REFR0
    accR_dm= numpy.empty((len(Rs),len(Zs)))
    accZ_dm= numpy.empty((len(Rs),len(Zs)))
    accR_baryon= numpy.empty((len(Rs),len(Zs)))
    accZ_baryon= numpy.empty((len(Rs),len(Zs)))
    #Calculate accelerations
    for ii in range(len(Rs)):
        for jj in range(len(Zs)):
            accR_dm[ii,jj]= potential.evaluateRforces(Rs[ii],Zs[jj],[pot[0]])
            accZ_dm[ii,jj]= potential.evaluatezforces(Rs[ii],Zs[jj],[pot[0]])
            accR_baryon[ii,jj]= potential.evaluateRforces(Rs[ii],Zs[jj],pot[1:])
            accZ_baryon[ii,jj]= potential.evaluatezforces(Rs[ii],Zs[jj],pot[1:])
    accR_dm*= bovy_conversion.force_in_10m13kms2(_REFV0*params[1],_REFR0)
    accZ_dm*= bovy_conversion.force_in_10m13kms2(_REFV0*params[1],_REFR0)
    accR_baryon*= bovy_conversion.force_in_10m13kms2(_REFV0*params[1],_REFR0)
    accZ_baryon*= bovy_conversion.force_in_10m13kms2(_REFV0*params[1],_REFR0)
    return (accR_dm,accZ_dm,accR_baryon,accZ_baryon,Rs,Zs)
Example #3
0
def estimateDeltaStaeckel(R,z,pot=None):
    """
    NAME:
       estimateDeltaStaeckel
    PURPOSE:
       Estimate a good value for delta using eqn. (9) in Sanders (2012)
    INPUT:
       R,z = coordinates (if these are arrays, the median estimated delta is returned, i.e., if this is an orbit)
       pot= Potential instance or list thereof
    OUTPUT:
       delta
    HISTORY:
       2013-08-28 - Written - Bovy (IAS)
    """
    if pot is None:
        raise IOError("pot= needs to be set to a Potential instance or list thereof")
    if isinstance(R,nu.ndarray):
        delta2= nu.array([(z[ii]**2.-R[ii]**2. #eqn. (9) has a sign error
                           +(3.*R[ii]*evaluatezforces(R[ii],z[ii],pot)
                             -3.*z[ii]*evaluateRforces(R[ii],z[ii],pot)
                             +R[ii]*z[ii]*(evaluateR2derivs(R[ii],z[ii],pot)
                                           -evaluatez2derivs(R[ii],z[ii],pot)))/evaluateRzderivs(R[ii],z[ii],pot)) for ii in range(len(R))])
        indx= (delta2 < 0.)*(delta2 > -10.**-10.)
        delta2[indx]= 0.
        delta2= nu.median(delta2[True-nu.isnan(delta2)])
    else:
        delta2= (z**2.-R**2. #eqn. (9) has a sign error
                 +(3.*R*evaluatezforces(R,z,pot)
                   -3.*z*evaluateRforces(R,z,pot)
                   +R*z*(evaluateR2derivs(R,z,pot)
                         -evaluatez2derivs(R,z,pot)))/evaluateRzderivs(R,z,pot))
        if delta2 < 0. and delta2 > -10.**-10.: delta2= 0.
    return nu.sqrt(delta2)
Example #4
0
    def rotSatForce(self,satpot,sat,freq,tdep,method,tstep=0):

        if tdep:
            if method=='fast':

                nt= len(self.t)

                discz= np.tile(np.array(self.discOrb.x(self.t)).T,(nt,1,1,1))
                satx,saty,satz= np.tile(sat.x(self.t),(nt,1)), np.tile(sat.y(self.t),(nt,1)), np.tile(sat.z(self.t),(nt,1))
                satx= np.array([np.roll(s,nt-int(i)) for  i,s in enumerate(satx)])
                saty= np.array([np.roll(s,nt-int(i)) for  i,s in enumerate(saty)])
                satz= np.array([np.roll(s,nt-int(i)) for  i,s in enumerate(satz)])[:,:,None,None]

                dx= np.tile(np.cos(freq*self.t),(nt,1))-satx
                dy= np.tile(np.sin(freq*self.t),(nt,1))-saty
                F= evaluatezforces(satpot,R=np.sqrt(dx**2+dy**2)[:,:,None,None],z=(discz-satz))
                discz,satx,saty,satz= np.array([[],[],[],[]])

                self.Force= F.T
                return F.T

            elif method=='slow':

                F= [None]*len(self.t)
                nt= len(self.t)
                for i in range(nt):
                    dx= np.cos(freq*self.t[(nt-i-1):])-sat.x(self.t[(nt-i-1):])
                    dy= np.sin(freq*self.t[(nt-i-1):])-sat.y(self.t[(nt-i-1):])
                    F[i]= evaluatezforces(satpot,R=np.sqrt(dx**2+dy**2),
                                           z=(self.discOrb.x(self.t[:i+1]))-sat.z(self.t[(nt-i-1):]))
                    if i==0:
                        F[i]= F[i][:,:,None]

                self.Force= F
                return F

            elif method=='slowest':

                F= [None]*len(self.t)
                nt= len(self.t)
                for i in range(nt):
                    dx= np.cos(freq*self.t[(nt-i-1):])-sat.x(self.t[(nt-i-1):])
                    dy= np.sin(freq*self.t[(nt-i-1):])-sat.y(self.t[(nt-i-1):])
                    F[i]= evaluatezforces(satpot,R=np.sqrt(dx**2+dy**2),
                                           z=(self.discOrb[tstep].x(self.t[:i+1]))-sat.z(self.t[(nt-i-1):]))
                    if i==0:
                        F[i]= F[i][:,None]

                self.Force= F
                return F

        else:
            dx,dy,dz= np.cos(freq*self.t)-sat.x(self.t), np.sin(freq*self.t)-sat.y(self.t), self.discOrb.x(self.t)-sat.z(self.t)
            dR= np.sqrt(dx**2.+dy**2.)

            F= evaluatezforces(satpot,R=dR,z=dz)

            self.Force= F
            return F
Example #5
0
    def statSatForce(self,satpot,sat,tdep=False,method='slow',tstep=0):

        '''
        INPUTS

        satpot- 3D potential describing the shape of the potential
        sat- Orbit instance integrated over t
        t- numpy array with the timesteps over which the satellite was integrated
        '''
        if tdep:
            if method=='fast':
                nt= len(self.t)

                F= np.zeros([nt,nt,self.vnpt,self.znpt])

                satx,saty,satz= np.tile(sat.x(self.t),(nt,1)), np.tile(sat.y(self.t),(nt,1)), np.tile(sat.z(self.t),(nt,1))
                satx= np.array([np.roll(s,nt-int(i)) for  i,s in enumerate(satx)])[:,:,None]
                saty= np.array([np.roll(s,nt-int(i)) for  i,s in enumerate(saty)])[:,:,None]
                satz= np.array([np.roll(s,nt-int(i)) for  i,s in enumerate(satz)])[:,:,None]

                for i in range(self.znpt):
                    F[:,:,:,i]= evaluatezforces(satpot,R=np.sqrt((satx-1.)**2+saty**2),
                                                z=(self.discOrb.x(self.t)[i,:,:,None].T-satz))

                self.Force= F.T
                return F.T

            elif method=='slow':
                F= [None]*len(self.t)
                nt= len(self.t)
                for i in range(len(self.t)):
                    F[i]= evaluatezforces(satpot,
                                           R=np.sqrt((sat.x(self.t[(nt-i-1):])-1.)**2+sat.y(self.t[(nt-i-1):])**2),
                                           z=(self.discOrb.x(self.t[:i+1]))-sat.z(self.t[(nt-i-1):]))
                    if i==0:
                        F[i]= F[i][:,:,None]
                self.Force= F
                return F

            elif method=='slowest':
                F= [None]*len(self.t)
                nt= len(self.t)
                for i in range(len(self.t)):
                    F[i]= evaluatezforces(satpot,
                                           R=np.sqrt((sat.x(self.t[(nt-i-1):])-1.)**2+sat.y(self.t[(nt-i-1):])**2),
                                           z=(self.discOrb[tstep].x(self.t[:i+1]))-sat.z(self.t[(nt-i-1):]))
                    if i==0:
                        F[i]= F[i][:,None]
                return F
        else:
            F= evaluatezforces(satpot,R=np.sqrt((sat.x(self.t)-1.)**2+sat.y(self.t)**2),
                               z=(self.discOrb.x(self.t))-sat.z(self.t))

            self.Force= F
            return F
def calAcc(r, v) : 
    N = r.shape[0]
    a = np.zeros([N,3])
    dt_min = np.ones(N)*1e5*yrs
    dr = r
    dx = r[:,0]
    dy = r[:,1]
    dz = r[:,2]
    dv = v
    dr_gp = np.sqrt(dx*dx + dy*dy)/(r0*kpc) # galpy units
    dz_gp = dz/(r0*kpc)
    drNorm = np.linalg.norm(dr, axis = 1)
    acc = None
    if useNFW : 
        m, rho, sigma = NFWmass( drNorm)
        acc = -G*m/(drNorm*drNorm)[:,np.newaxis]*dr/drNorm[:,np.newaxis]
    elif useHernquist:
        m, rho, sigma = hernquistmass( drNorm)
        acc = -G*m/(drNorm*drNorm)[:,np.newaxis]*dr/drNorm[:,np.newaxis]
    else : 
        acc = np.zeros([dr_gp.size,3])
        conv = 1e-13*1e5
        for i, x_gp, y_gp, r_gp, z_gp in zip(range(dr_gp.size), dx/(r0*kpc), dy/(r0*kpc), dr_gp, dz_gp) : 
            a = gp.evaluateRforces(MWpot,r_gp,z_gp)*bovy_conversion.force_in_10m13kms2(v0,r0)*conv
            acc[i,0] = a*x_gp/r_gp
            acc[i,1] = a*y_gp/r_gp
            acc[i,2] = gp.evaluatezforces(MWpot,r_gp,z_gp)*bovy_conversion.force_in_10m13kms2(v0,r0)*conv
    dt_rmin = np.min(drNorm/np.linalg.norm(dv, axis=1))
    dt_amin = np.min(np.linalg.norm(dv,axis=1)/np.maximum(np.linalg.norm(acc,axis=1), TINY))
    dt_min = min(dt_rmin, dt_amin)
    if(args.use_DF) : 
        acc = acc + accDF( r, v)
    return acc, dt_min
Example #7
0
def MWBHZfo(bdeg, ldeg, dkpc):

    b = bdeg * par.degtorad
    l = ldeg * par.degtorad
    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    Rpkpc = Rpkpcfunc(dkpc, b, l, Rskpc)
    zkpc = dkpc * math.sin(b)
    '''
    bp= PowerSphericalPotentialwCutoff(alpha=1.8,rc=1.9/8.,normalize=0.05)
    mp= MiyamotoNagaiPotential(a=3./8.,b=0.28/8.,normalize=.6)
    np= NFWPotential(a=16./8.,normalize=.35)
    kp = KeplerPotential(amp=4*10**6./bovy_conversion.mass_in_msol(par.Vs,par.Rskpc))
    MWBH = [bp,mp,np,kp]
    zf1 = evaluatezforces(MWBH, Rpkpc/Rskpc,zkpc/Rskpc)*bovy_conversion.force_in_kmsMyr(Vs,Rskpc)
    '''
    MWPotential2014wBH = [
        MWPotential2014,
        KeplerPotential(amp=4 * 10**6. /
                        bovy_conversion.mass_in_msol(par.Vs, par.Rskpc))
    ]
    zf1 = evaluatezforces(MWPotential2014wBH, Rpkpc / Rskpc, zkpc /
                          Rskpc) * bovy_conversion.force_in_kmsMyr(Vs, Rskpc)

    Excz = zf1 * conversion * math.sin(b)  #s-1

    return Excz
Example #8
0
def test_mwpotential2014():
    from galpy.potential import (MWPotential2014,
                                 evaluateDensities,
                                 evaluatezforces,
                                 evaluatePotentials)

    # Here these have to be default:
    ro = 8 * u.kpc
    vo = 220 * u.km/u.s

    gala_pot = BovyMWPotential2014()
    bovy_pot = MWPotential2014
    for x in bovy_pot:
        x.turn_physical_on()

    Rs = np.random.uniform(1, 15, size=ntest) * u.kpc
    zs = np.random.uniform(1, 15, size=ntest) * u.kpc

    xyz = np.zeros((3, Rs.size)) * u.kpc
    xyz[0] = Rs
    xyz[2] = zs
    assert np.allclose(gala_pot.density(xyz).to_value(u.Msun/u.pc**3),
                       evaluateDensities(bovy_pot, R=Rs.to_value(ro), z=zs.to_value(ro)))

    assert np.allclose(gala_pot.energy(xyz).to_value((u.km / u.s)**2),
                       evaluatePotentials(bovy_pot, R=Rs.to_value(ro), z=zs.to_value(ro)))

    assert np.allclose(gala_pot.gradient(xyz).to_value((u.km/u.s) * u.pc/u.Myr / u.pc)[2],
                       -evaluatezforces(bovy_pot, R=Rs.to_value(ro), z=zs.to_value(ro)))
def plotKz(pot,plotfilename,surfrs,kzs,kzerrs):
    krs= numpy.linspace(4./_REFR0,10./_REFR0,1001)
    modelkz= numpy.array([-potential.evaluatezforces(kr,1.1/_REFR0,pot)\
                               *bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0) for kr in krs])
    bovy_plot.bovy_print(fig_height=3.5)
    bovy_plot.bovy_plot(krs*_REFR0,modelkz,'-',color='0.6',lw=2.,
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$F_{Z}(R,|Z| = 1.1\,\mathrm{kpc})\ (2\pi G\,M_\odot\,\mathrm{pc}^{-2})$',
                        semilogy=True,
                        yrange=[10.,1000.],
                        xrange=[4.,10.],
                        zorder=0)
    pyplot.errorbar(surfrs,
                    kzs,
                    yerr=kzerrs,
                    marker='o',
                    elinewidth=1.,capsize=3,zorder=1,
                    color='k',linestyle='none')  
    pyplot.errorbar([_REFR0],[69.],yerr=[6.],marker='d',ms=10.,
                    elinewidth=1.,capsize=3,zorder=10,
                    color='0.4',linestyle='none')
    bovy_plot.bovy_end_print(plotfilename)
    #Do an exponential fit to the model Kz and return the scale length
    indx= krs < 9./_REFR0
    p= numpy.polyfit(krs[indx],numpy.log(modelkz[indx]),1)
    return -1./p[0]
Example #10
0
    def _satellite_force(self, sat_time, orb_time,
                         satellite_orbit_physical_off,
                         phase_space_orbits_physical_off,
                         satellite_potential_physical_off, verbose):

        r_over_r0 = self.potential_extension_global.R_over_R0_eval

        vc_over_v0 = self.potential_extension_global.Vc

        freq = vc_over_v0 / r_over_r0

        if verbose:
            print('evaluating at r_ovver_r0 = ' + str(r_over_r0))
            print('evaluating at vc_over_v0 = ' + str(vc_over_v0))

        dx = r_over_r0 * np.cos(
            freq * sat_time) - satellite_orbit_physical_off.x(sat_time)
        dy = r_over_r0 * np.sin(
            freq * sat_time) - satellite_orbit_physical_off.y(sat_time)
        dz = phase_space_orbits_physical_off.x(
            orb_time) - satellite_orbit_physical_off.z(sat_time)
        dR = np.sqrt(dx**2. + dy**2.)

        force = evaluatezforces(satellite_potential_physical_off, R=dR, z=dz)

        return force
def force_pal5(pot: PotentialType,
               dpal5: float,
               ro: float = REFR0,
               vo: float = REFV0) -> Tuple[float]:
    """Return the force at Pal5.

    Parameters
    ----------
    pot: Potential, list
    dpal5: float
    ro, vo: float

    Return
    ------
    force: tuple
        [fx, fy, fz]

    """
    from galpy import potential
    from galpy.util import bovy_coords

    # First compute the location based on the distance
    l5, b5 = bovy_coords.radec_to_lb(229.018, -0.124, degree=True)
    X5, Y5, Z5 = bovy_coords.lbd_to_XYZ(l5, b5, dpal5, degree=True)
    R5, p5, Z5 = bovy_coords.XYZ_to_galcencyl(X5, Y5, Z5, Xsun=ro, Zsun=0.025)

    args: list = [pot, R5 / ro, Z5 / ro]
    kws: dict = {"phi": p5, "use_physical": True, "ro": ro, "vo": vo}

    return (
        potential.evaluateRforces(*args, **kws),
        potential.evaluatezforces(*args, **kws),
        potential.evaluatephiforces(*args, **kws),
    )
Example #12
0
    def get_gravity_at_point(self, eps, x, y, z):

        R = np.sqrt(x.value_in(units.kpc)**2. + y.value_in(units.kpc)**2.)
        zed = z.value_in(units.kpc)
        phi = np.arctan2(y.value_in(units.kpc), x.value_in(units.kpc))

        Rforce = potential.evaluateRforces(self.pot,
                                           R / self.ro,
                                           zed / self.ro,
                                           phi=phi,
                                           t=self.tgalpy)
        phiforce = potential.evaluatephiforces(
            self.pot, R / self.ro, zed / self.ro, phi=phi,
            t=self.tgalpy) / (R / self.ro)
        zforce = potential.evaluatezforces(self.pot,
                                           R / self.ro,
                                           zed / self.ro,
                                           phi=phi,
                                           t=self.tgalpy)

        ax = (Rforce * np.cos(phi) -
              phiforce * np.sin(phi)) * bovy_conversion.force_in_kmsMyr(
                  ro=self.ro, vo=self.vo) | units.kms * units.myr**-1
        ay = (Rforce * np.sin(phi) +
              phiforce * np.cos(phi)) * bovy_conversion.force_in_kmsMyr(
                  ro=self.ro, vo=self.vo) | units.kms * units.myr**-1
        az = zforce * bovy_conversion.force_in_kmsMyr(
            ro=self.ro, vo=self.vo) | units.kms * units.myr**-1

        return ax, ay, az
def fdotdotSB2cal(ldeg, bdeg, dkpc, mul, mub):

    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    yrts = par.yrts
    c = par.c
    kpctom = par.kpctom
    Rs = Rskpc * kpctom
    mastorad = par.mastorad

    normpottoSI = par.normpottoSI
    normForcetoSI = par.normForcetoSI
    normjerktoSI = par.normjerktoSI

    b = bdeg * par.degtorad
    l = ldeg * par.degtorad

    Rpkpc = par.Rpkpc(ldeg, bdeg, dkpc)

    zkpc = par.z(ldeg, bdeg, dkpc)

    fex_pl = excGal.Expl(ldeg, bdeg, dkpc)

    fex_z = excGal.Exz(ldeg, bdeg, dkpc)

    fex_shk = Shk.Exshk(dkpc, mul, mub)

    fex_tot = fex_pl + fex_z + fex_shk

    #mub = mu_alpha #mas/yr
    #mul = mu_delta

    muT = (mub**2. + mul**2.)**0.5
    #MWPotential2014= [MWPotential2014,KeplerPotential(amp=4*10**6./bovy_conversion.mass_in_msol(par.Vs,par.Rskpc))]
    MWPot = MWPotential2014

    appl = evaluateRforces(MWPot, Rpkpc / Rskpc, zkpc / Rskpc) * normForcetoSI
    aspl = evaluateRforces(MWPot, Rskpc / Rskpc, 0.0 / Rskpc) * normForcetoSI
    apz = evaluatezforces(MWPot, Rpkpc / Rskpc, zkpc / Rskpc) * normForcetoSI

    be = (dkpc / Rskpc) * math.cos(b) - math.cos(l)
    coslam = be * (Rskpc / Rpkpc)

    res1 = 2. * (mastorad / yrts) * (mub *
                                     ((math.sin(b) / c) *
                                      (appl * coslam + aspl * math.cos(l)) -
                                      (math.cos(b) / c) * apz) - mul *
                                     (math.sin(l) / c) *
                                     (appl * (Rskpc / Rpkpc) - aspl))

    res2 = 2. * fex_tot * (math.cos(b) * math.cos(l) * (aspl / c) +
                           (mastorad / yrts) * mub *
                           (1000. * Vs / c) * math.sin(b) * math.sin(l) -
                           (mastorad / yrts) * mul *
                           (1000. * Vs / c) * math.cos(l))

    res = res1 + res2
    return res
Example #14
0
    def _zforce(self, R, z, phi=0.0, t=0.0):
        from galpy.potential import evaluatezforces

        if self._interpzforce:
            out = numpy.empty_like(R)
            indx = (R >= self._rgrid[0]) * (R <= self._rgrid[-1]) * (z <= self._zgrid[-1]) * (z >= self._zgrid[0])
            if numpy.sum(indx) > 0:
                if self._enable_c:
                    out[indx] = eval_force_c(self, R[indx], z[indx], zforce=True)[0] / self._amp
                else:
                    if self._logR:
                        out[indx] = self._zforceInterp.ev(numpy.log(R[indx]), z[indx])
                    else:
                        out[indx] = self._zforceInterp.ev(R[indx], z[indx])
            if numpy.sum(True - indx) > 0:
                out[True - indx] = evaluatezforces(R[True - indx], z[True - indx], self._origPot)
            return out
        else:
            return evaluatezforces(R, z, self._origPot)
def force_gd1(pot,ro,vo):
    """Return the force at GD-1"""
    # Just use R=12.5 kpc, Z= 6.675 kpc, phi=0
    R1= 12.5
    Z1= 6.675
    p1= 0.
    return (potential.evaluateRforces(pot,R1/ro,Z1/ro,phi=p1,
                                      use_physical=True,ro=ro,vo=vo),
            potential.evaluatezforces(pot,R1/ro,Z1/ro,phi=p1,
                                      use_physical=True,ro=ro,vo=vo),
            potential.evaluatephiforces(pot,R1/ro,Z1/ro,phi=p1,
                                        use_physical=True,ro=ro,vo=vo))
def force_pal5(pot,dpal5,ro,vo):
    """Return the force at Pal5"""
    # First compute the location based on the distance
    l5, b5= bovy_coords.radec_to_lb(229.018,-0.124,degree=True)
    X5,Y5,Z5= bovy_coords.lbd_to_XYZ(l5,b5,dpal5,degree=True)
    R5,p5,Z5= bovy_coords.XYZ_to_galcencyl(X5,Y5,Z5,Xsun=ro,Zsun=0.025)
    return (potential.evaluateRforces(pot,R5/ro,Z5/ro,phi=p5,
                                      use_physical=True,ro=ro,vo=vo),
            potential.evaluatezforces(pot,R5/ro,Z5/ro,phi=p5,
                                      use_physical=True,ro=ro,vo=vo),
            potential.evaluatephiforces(pot,R5/ro,Z5/ro,phi=p5,
                                        use_physical=True,ro=ro,vo=vo))
Example #17
0
def MWZfo(ldeg, sigl, bdeg, sigb, dkpc, sigd):

    b = bdeg*par.degtorad
    l = ldeg*par.degtorad
    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    Rpkpc = par.Rpkpc(ldeg, sigl, bdeg, sigb, dkpc, sigd)
    zkpc = dkpc*math.sin(b)

    zf1 = evaluatezforces(MWPotential2014, Rpkpc/Rskpc,zkpc/Rskpc)*bovy_conversion.force_in_kmsMyr(Vs,Rskpc)
    Excz = zf1*conversion*math.sin(b)#s-1
    return Excz;
Example #18
0
def estimateDeltaStaeckel(R, z, pot=None):
    """
    NAME:
       estimateDeltaStaeckel
    PURPOSE:
       Estimate a good value for delta using eqn. (9) in Sanders (2012)
    INPUT:
       R,z = coordinates (if these are arrays, the median estimated delta is returned, i.e., if this is an orbit)
       pot= Potential instance or list thereof
    OUTPUT:
       delta
    HISTORY:
       2013-08-28 - Written - Bovy (IAS)
    """
    if pot is None:  #pragma: no cover
        raise IOError(
            "pot= needs to be set to a Potential instance or list thereof")
    if isinstance(R, nu.ndarray):
        delta2 = nu.array([
            (
                z[ii]**2. - R[ii]**2.  #eqn. (9) has a sign error
                + (3. * R[ii] * evaluatezforces(R[ii], z[ii], pot) - 3. *
                   z[ii] * evaluateRforces(R[ii], z[ii], pot) + R[ii] * z[ii] *
                   (evaluateR2derivs(R[ii], z[ii], pot) -
                    evaluatez2derivs(R[ii], z[ii], pot))) /
                evaluateRzderivs(R[ii], z[ii], pot)) for ii in range(len(R))
        ])
        indx = (delta2 < 0.) * (delta2 > -10.**-10.)
        delta2[indx] = 0.
        delta2 = nu.median(delta2[True - nu.isnan(delta2)])
    else:
        delta2 = (
            z**2. - R**2.  #eqn. (9) has a sign error
            + (3. * R * evaluatezforces(R, z, pot) -
               3. * z * evaluateRforces(R, z, pot) + R * z *
               (evaluateR2derivs(R, z, pot) - evaluatez2derivs(R, z, pot))) /
            evaluateRzderivs(R, z, pot))
        if delta2 < 0. and delta2 > -10.**-10.: delta2 = 0.
    return nu.sqrt(delta2)
Example #19
0
def accHernquistfix(x,y,z):
    x = x/kpctocm
    y = y/kpctocm
    z = z/kpctocm
    r = np.sqrt( x**2 + y**2)
    pot = HernquistPotential(2.e12*u.M_sun , 30e3*u.pc)
    az = evaluatezforces(pot,r*u.kpc , z*u.kpc)
    ar = evaluateRforces(pot,r*u.kpc , z*u.kpc)
    az = -az*1.e5/(1.e6*3.15e7)
    ar = ar*1.e5/(1.e6*3.15e7)
    ax = -ar*x/r
    ay = -ar*y/r
    return ax,ay,az
Example #20
0
def MWBHZfo(ldeg, bdeg, dkpc):

    b = bdeg*par.degtorad
    l = ldeg*par.degtorad
    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    Rpkpc = par.Rpkpc(ldeg, bdeg, dkpc)
    zkpc = dkpc*math.sin(b)
  
    MWPotential2014BH= [MWPotential2014,KeplerPotential(amp=4*10**6./bovy_conversion.mass_in_msol(par.Vs,par.Rskpc))]
    zf1 = evaluatezforces(MWPotential2014BH, Rpkpc/Rskpc,zkpc/Rskpc)*((Vs*1000.)**2.)/(Rskpc*par.kpctom) #m/ss
    Excz = zf1*math.sin(b)/par.c #s-1
    return Excz;
Example #21
0
def MWZfo(ldeg, bdeg, dkpc):

    b = bdeg * par.degtorad
    l = ldeg * par.degtorad
    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    Rpkpc = par.Rpkpc(ldeg, bdeg, dkpc)
    zkpc = dkpc * math.sin(b)

    zf1 = evaluatezforces(MWPotential2014, Rpkpc / Rskpc, zkpc / Rskpc) * (
        (Vs * 1000.)**2.) / (Rskpc * par.kpctom)  #m/ss
    Excz = zf1 * math.sin(b) / par.c  #s-1
    return Excz
Example #22
0
 def _zforce(self,R,z,phi=0.,t=0.):
     from galpy.potential import evaluatezforces
     if self._interpzforce:
         out= numpy.empty_like(R)
         indx= (R >= self._rgrid[0])*(R <= self._rgrid[-1])\
             *(z <= self._zgrid[-1])*(z >= self._zgrid[0])
         if numpy.sum(indx) > 0:
             if self._enable_c:
                 out[indx]= eval_force_c(self,R[indx],z[indx],
                                         zforce=True)[0]/self._amp
             else:
                 if self._logR:
                     out[indx]= self._zforceInterp.ev(numpy.log(R[indx]),
                                                      z[indx])
                 else:
                     out[indx]= self._zforceInterp.ev(R[indx],z[indx])
         if numpy.sum(True^indx) > 0:
             out[True^indx]= evaluatezforces(self._origPot,
                                             R[True^indx],
                                             z[True^indx])
         return out
     else:
         return evaluatezforces(self._origPot,R,z)
Example #23
0
def rv(x, y, z):

    conv = bovy_conversion.force_in_pcMyr2(220., 8) * u.pc / (
        u.Myr**2)  ##Unit conversion

    x *= u.kpc
    y *= u.kpc
    z *= u.kpc

    ##Sun's location
    sx = 8 * u.kpc
    sy = 0 * u.kpc
    sz = 4 * u.kpc

    sun_ar = evaluateRforces(poten, sx, sz, phi=0 * u.deg) * conv
    sun_az = evaluatezforces(poten, sx, sz, phi=0 * u.deg) * conv

    sun_acc = Vector(sun_ar, 0 * conv, sun_az)

    star_ar = evaluateRforces(poten, np.sqrt(x**2 + y**2), z,
                              phi=0 * u.deg) * conv
    star_az = evaluatezforces(poten, np.sqrt(x**2 + y**2), z,
                              phi=0 * u.deg) * conv

    star_acc = Vector(star_ar, 0 * conv, star_az)

    heliocentric_acc = Vector(star_acc.x - sun_acc.x, star_acc.y - sun_acc.y,
                              star_acc.z - sun_acc.z)

    r = Vector(sx - x, sy - y, sz - z)

    acc = r.project(heliocentric_acc)

    delta_v = (acc.mag * 10 * u.yr).to(u.cm / u.s)

    return delta_v, r
Example #24
0
 def _getForces(folder):
     loc = "SCFAnalysis/Orbits/{0}".format(folder)
     Acos = nu.load(loc + "/Acos.npy")
     a_nfw = 200./8
     orbits_pos =nu.load(TIMEORBITS.format(loc, TIME,0.004,1*units.Myr))
     scf = potential.SCFPotential(Acos=Acos, a=a_nfw, normalize=.35)
     ps= potential.PowerSphericalPotentialwCutoff(alpha=1.8,rc=1.9/8.,normalize=0.05)
     mn= potential.MiyamotoNagaiPotential(a=3./8.,b=0.28/8.,normalize=.6)
     MWPotential= [ps,mn,scf]
     x,y,z = orbits_pos[-1,1:4]
     R, phi, z = rect_to_cyl(x,y,z)
     print "(R,z,phi) = ({0}, {1}, {2})".format(R,z,phi)
     Rforce = potential.evaluateRforces(MWPotential, R,z,phi)
     zforce = potential.evaluatezforces(MWPotential, R,z,phi)
     phiforce = potential.evaluatephiforces(MWPotential, R,z,phi)
     return Rforce, zforce, phiforce
Example #25
0
def FZStaeckel(u,v,pot,delta):
    """
    NAME:
       FZStaeckel
    PURPOSE:
       return the vertical force
    INPUT:
       u - confocal u
       v - confocal v
       pot - potential
       delta - focus
    OUTPUT:
       FZ(u,v)
    HISTORY:
       2012-11-30 - Written - Bovy (IAS)
    """
    R,z= bovy_coords.uv_to_Rz(u,v,delta=delta)
    return evaluatezforces(R,z,pot)
def MWBHZfo(bdeg, ldeg, dkpc):

    b = bdeg * par.degtorad
    l = ldeg * par.degtorad
    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    Rpkpc = Rpkpcfunc(dkpc, b, l, Rskpc)
    zkpc = dkpc * math.sin(b)

    MWPotential2014.append(
        KeplerPotential(amp=4 * 10**6. /
                        bovy_conversion.mass_in_msol(Vs, Rskpc)))
    zf1 = evaluatezforces(MWPotential2014, Rpkpc / Rskpc, zkpc /
                          Rskpc) * bovy_conversion.force_in_kmsMyr(Vs, Rskpc)
    Excz = zf1 * conversion * math.sin(b)  #s-1

    return Excz
Example #27
0
def FZStaeckel(u, v, pot, delta):  #pragma: no cover because unused
    """
    NAME:
       FZStaeckel
    PURPOSE:
       return the vertical force
    INPUT:
       u - confocal u
       v - confocal v
       pot - potential
       delta - focus
    OUTPUT:
       FZ(u,v)
    HISTORY:
       2012-11-30 - Written - Bovy (IAS)
    """
    R, z = bovy_coords.uv_to_Rz(u, v, delta=delta)
    return evaluatezforces(R, z, pot)
def bulge_dispersion(pot: PotentialType,
                     ro: float = REFR0,
                     vo: float = REFV0) -> float:
    """The expected dispersion in Baade's window, in km/s.

    Other Parameters
    ----------------
    ro: float
    vo: float

    """
    bar, baz = 0.0175, 0.068
    return (np.sqrt(1.0 / pot[0].dens(bar, baz) * integrate.quad(
        lambda x: -potential.evaluatezforces(pot, bar, x, phi=0.0) * pot[0].
        dens(bar, x),
        baz,
        np.inf,
    )[0]) * ro)
Example #29
0
def accMWpot(x,y,z,alpha=1.8, rc=1.9, a=3., b=0.28):
    x = x/kpctocm
    y = y/kpctocm
    z = z/kpctocm
    r = np.sqrt( x**2 + y**2)
    bp= gp.PowerSphericalPotentialwCutoff(alpha=1.8,rc=1.9/8.,normalize=0.05)
    mp= gp.MiyamotoNagaiPotential(a=a/8.,b=b/8.,normalize=.6)
    nfw= gp.NFWPotential(a=16/8.,normalize=.35)
    #print(help(MWPotential2014))
    #pot = [bp,mp,nfw]
    pot = MWPotential2014
    az = evaluatezforces(pot,r*u.kpc , z*u.kpc)*bovy_conversion.force_in_kmsMyr(Vlsr/1e5,8.122)
    ar = evaluateRforces(pot,r*u.kpc , z*u.kpc)*bovy_conversion.force_in_kmsMyr(Vlsr/1e5,8.122)
    ar = ar*1.e5/(1.e6*3.15e7)
    az = -az*1.e5/(1.e6*3.15e7)

    ax = -ar*x/r
    ay = -ar*y/r
    return ax,ay,az
def calAcc(r, v):
    N = r.shape[0]
    a = np.zeros([N, 3])
    dt_min = np.ones(N) * 1e5 * yrs
    dr = r
    dx = r[:, 0]
    dy = r[:, 1]
    dz = r[:, 2]
    dv = v
    dr_gp = np.sqrt(dx * dx + dy * dy) / (r0 * kpc)  # galpy units
    dz_gp = dz / (r0 * kpc)
    drNorm = np.linalg.norm(dr, axis=1)
    acc = None
    if useNFW:
        m, rho, sigma = NFWmass(drNorm)
        acc = -G * m / (drNorm *
                        drNorm)[:, np.newaxis] * dr / drNorm[:, np.newaxis]
    elif useHernquist:
        m, rho, sigma = hernquistmass(drNorm)
        acc = -G * m / (drNorm *
                        drNorm)[:, np.newaxis] * dr / drNorm[:, np.newaxis]
    else:
        acc = np.zeros([dr_gp.size, 3])
        conv = 1e-13 * 1e5
        for i, x_gp, y_gp, r_gp, z_gp in zip(range(dr_gp.size),
                                             dx / (r0 * kpc), dy / (r0 * kpc),
                                             dr_gp, dz_gp):
            a = gp.evaluateRforces(MWpot, r_gp,
                                   z_gp) * bovy_conversion.force_in_10m13kms2(
                                       v0, r0) * conv
            acc[i, 0] = a * x_gp / r_gp
            acc[i, 1] = a * y_gp / r_gp
            acc[i, 2] = gp.evaluatezforces(
                MWpot, r_gp, z_gp) * bovy_conversion.force_in_10m13kms2(
                    v0, r0) * conv
    dt_rmin = np.min(drNorm / np.linalg.norm(dv, axis=1))
    dt_amin = np.min(
        np.linalg.norm(dv, axis=1) /
        np.maximum(np.linalg.norm(acc, axis=1), TINY))
    dt_min = min(dt_rmin, dt_amin)
    if (args.use_DF):
        acc = acc + accDF(r, v)
    return acc, dt_min
def force_gd1(pot, ro, vo):
    """Return the force at GD-1.

    Parameters
    ----------
    pot: Potential
    ro, vo: float

    Return
    ------
    force: tuple
        [fx, fy, fz]

    """
    # Just use R=12.5 kpc, Z= 6.675 kpc, phi=0
    R1 = 12.5
    Z1 = 6.675
    p1 = 0.0

    return (
        potential.evaluateRforces(pot,
                                  R1 / ro,
                                  Z1 / ro,
                                  phi=p1,
                                  use_physical=True,
                                  ro=ro,
                                  vo=vo),
        potential.evaluatezforces(pot,
                                  R1 / ro,
                                  Z1 / ro,
                                  phi=p1,
                                  use_physical=True,
                                  ro=ro,
                                  vo=vo),
        potential.evaluatephiforces(pot,
                                    R1 / ro,
                                    Z1 / ro,
                                    phi=p1,
                                    use_physical=True,
                                    ro=ro,
                                    vo=vo),
    )
Example #32
0
def del_E(coord, custom_potential=None):
    """
    NAME:
        del_E

    PURPOSE:
        Given (m,6) array for a list of the position and velocity of stars in
        Cartesian coordinate, return the gradient vectors of energy in Cartesian
        form, in the corresponding row order.
        Assumes input and out put are in natrual unit.
        
    INPUT:
        coord = array([[x, y, z, vx, vy, vz], ...])
                where each row represents the coordinate of a star

    OUTPUT:
        del_E = gradient in Cartesian coordinate
                where each row represents the gradient of a star

    HISTORY:
        2018-07-10 - Written - Samuel Wong
        2018-07-24 - Changed to an array of points - Samuel Wong
    """
    if custom_potential == None:
        potential = MWPotential2014
    else:
        potential = custom_potential
    x, y, z, vx, vy, vz = coord.T
    R, vR, vT, z, vz, phi = rect_to_cyl(x, y, z, vx, vy, vz).T
    # get the force of the potential in cylindrical form
    F_phi = evaluatephiforces(potential, R, z, phi) / R
    F_R = evaluateRforces(potential, R, z, phi)
    F_z = evaluatezforces(potential, R, z, phi)
    # return the gradient in Cartesian coordinate
    gradient = [
        F_phi * np.sin(phi) - F_R * np.cos(phi),
        -F_R * np.sin(phi) - F_phi * np.cos(phi), -F_z, vx, vy, vz
    ]
    return np.array(gradient).T
Example #33
0
def calAcc(r, v) : 
    N = r.shape[0]
    dr = r
    dx = r[:,0]
    dy = r[:,1]
    dz = r[:,2]
    dv = v
    dr_gp = np.sqrt(dx*dx + dy*dy)/(r0*kpc) # galpy units
    dz_gp = dz/(r0*kpc)
    drNorm = np.linalg.norm(dr, axis = 1)
    acc = None
    if useNFW : 
        m, rho, sigma = NFWmass( drNorm)
        acc = -G*m/(drNorm*drNorm)[:,np.newaxis]*dr/drNorm[:,np.newaxis]
    elif useHernquist:
        m, rho, sigma = hernquistmass( drNorm)
        acc = (-G*m/(drNorm*drNorm*drNorm))[:,np.newaxis]*dr#[:,np.newaxis]*dr
    else : 
        acc = np.zeros([dr_gp.size,3])
        conv = 1e-13*1e5
        for i, x_gp, y_gp, r_gp, z_gp in zip(range(dr_gp.size), dx/(r0*kpc), dy/(r0*kpc), dr_gp, dz_gp) : 
            a = gp.evaluateRforces(MWpot,r_gp,z_gp)*bovy_conversion.force_in_10m13kms2(v0,r0)*conv
            acc[i,0] = a*x_gp/r_gp
            acc[i,1] = a*y_gp/r_gp
            acc[i,2] = gp.evaluatezforces(MWpot,r_gp,z_gp)*bovy_conversion.force_in_10m13kms2(v0,r0)*conv
    dt_rmin = np.min(drNorm/np.linalg.norm(dv, axis=1))
    dt_amin = np.min(np.linalg.norm(dv,axis=1)/np.maximum(np.linalg.norm(acc,axis=1), TINY))
    dt_min = min(dt_rmin, dt_amin)
    if(useDF) : 
        acc[:Nsat,:] = acc[:Nsat,:] + accDF( r[:Nsat,:], v[:Nsat,:])
    if(useTestParticles and Nsat < N and runSat) :
        # include accelerations from other satellites for test particles
        for i in range(Nsat) : 
            rsat = r[i]
            dr = r[Nsat:,:] - rsat[np.newaxis,:]
            drNorm = np.linalg.norm( dr, axis=1)
            m, rho, sigma = hernquistmass( drNorm, m0=msat[i], vc200=vc200sat[i], r200=r200sat[i], c0=c0sat[i])
            acc[Nsat:,:] =  acc[Nsat:,:] - (G*m/(drNorm*drNorm*drNorm))[:,np.newaxis]*dr
    return acc, dt_min
def plotKz(pot,surfrs,kzs,kzerrs,_REFR0,_REFV0):
    krs= numpy.linspace(4./_REFR0,10./_REFR0,1001)
    modelkz= numpy.array([-potential.evaluatezforces(pot,kr,1.1/_REFR0)\
                               *bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0) for kr in krs])
    bovy_plot.bovy_plot(krs*_REFR0,modelkz,'-',color='0.6',lw=2.,
                        xlabel=r'$R\ (\mathrm{kpc})$',
                        ylabel=r'$F_{Z}(R,|Z| = 1.1\,\mathrm{kpc})\ (2\pi G\,M_\odot\,\mathrm{pc}^{-2})$',
                        semilogy=True,
                        yrange=[10.,1000.],
                        xrange=[4.,10.],
                        zorder=0,gcf=True)
    pyplot.errorbar(_REFR0-8.+surfrs,
                    kzs,
                    yerr=kzerrs,
                    marker='o',
                    elinewidth=1.,capsize=3,zorder=1,
                    color='k',linestyle='none')  
    pyplot.errorbar([_REFR0],[69.],yerr=[6.],marker='d',ms=10.,
                    elinewidth=1.,capsize=3,zorder=10,
                    color='0.4',linestyle='none')
    #Do an exponential fit to the model Kz and return the scale length
    indx= krs < 9./_REFR0
    p= numpy.polyfit(krs[indx],numpy.log(modelkz[indx]),1)
    return -1./p[0]
def writeTable(pot,params,tablename,options,fzrd):
    outfile= open(tablename,'w')
    delimiter= ' & '
    #First list the explicit parameters
    printline= '$R_0\,(\kpc)$%s$8$%sfixed\\\\\n' % (delimiter,delimiter)
    outfile.write(printline)
    printline= '$v_c(R_0)\,(\kms)$%s$220$%sfixed\\\\\n' % (delimiter,delimiter)
    outfile.write(printline)
    if options.twodisks:
        printline= '$f_{b}$%s$%.2f$%s\ldots\\\\\n' % (delimiter,1.-params[0]-params[1]-params[2],delimiter)        
        outfile.write(printline)
        printline= '$f_{d,1}$%s$%.2f$%s\ldots\\\\\n' % (delimiter,params[0],delimiter)
        outfile.write(printline)
        printline= '$f_{d,2}$%s$%.2f$%s\ldots\\\\\n' % (delimiter,params[1],delimiter)        
        outfile.write(printline)
        printline= '$f_{h}$%s$%.2f$%s\ldots\\\\\n' % (delimiter,params[2],delimiter)        
        outfile.write(printline)
    else:
        printline= '$f_{b}$%s$%.2f$%s\ldots\\\\\n' % (delimiter,1.-params[0]-params[1],delimiter)        
        outfile.write(printline)
        printline= '$f_{d}$%s%.2f%s\ldots\\\\\n' % (delimiter,params[0],delimiter)
        outfile.write(printline)
        printline= '$f_{h}$%s$%.2f$%s\ldots\\\\\n' % (delimiter,params[1],delimiter)        
        outfile.write(printline)
    #Bulge power-law and rc
    printline= '$\mathrm{Bulge\ power}$%s$-1.8$%sfixed\\\\\n' % (delimiter,delimiter)        
    outfile.write(printline)
    printline= '$\mathrm{Bulge\ cut}\,(\kpc)$%s$1.9$%sfixed\\\\\n' % (delimiter,delimiter)        
    outfile.write(printline)
    #Disk scale length and height
    printline= '$a\,(\kpc)$%s$%.1f$%s\ldots\\\\\n' % (delimiter,numpy.exp(params[2+options.twodisks])*_REFR0,delimiter)        
    outfile.write(printline)
    printline= '$b\,(\pc)$%s$%.0f$%s\ldots\\\\\n' % (delimiter,1000.*numpy.exp(params[3+options.twodisks])*_REFR0,delimiter)        
    outfile.write(printline)
    printline= '$\mathrm{Halo}\ r_s\,(\kpc)$%s$%.0f$%s\ldots\\\\\n' % (delimiter,numpy.exp(params[4+options.twodisks])*_REFR0,delimiter)        
    outfile.write(printline)
    outfile.write('%s%s\\\\\n' % (delimiter,delimiter))
    #Now the constraints
    printline= '$\sigma_b\,(\kms)$%s$%.0f$%s$117\pm15$\\\\\n' % (delimiter,bulge_dispersion(pot),delimiter)
    outfile.write(printline)
    printline= '$F_Z(R_0,1.1\kpc)\,(2\pi G\,M_\odot\pc^{-2})$%s$%.0f$%s$67\pm6$\\\\\n' % (delimiter,-potential.evaluatezforces(1.,1.1/_REFR0,pot)*bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0),delimiter)
    outfile.write(printline)
    printline= '$\Sigma_{\mathrm{vis}}(R_0)\,(M_\odot\pc^{-2})$%s$%.0f$%s$55\pm5$\\\\\n' % (delimiter,visible_dens(pot,options),delimiter)
    outfile.write(printline)
    printline= '$F_Z\ \mathrm{scale\ length}\,(\kpc)$%s%.1f%s$2.7\pm0.1$\\\\\n' % (delimiter,fzrd*_REFR0,delimiter)
    outfile.write(printline)
    printline= '$\\rho(R_0,z=0)\,(M_\odot\pc^{-3})$%s$%.2f$%s$0.10\pm0.01$\\\\\n' % (delimiter,potential.evaluateDensities(1.,0.,pot)*bovy_conversion.dens_in_msolpc3(_REFV0,_REFR0),delimiter)
    outfile.write(printline)
    printline= '$(\dd \ln v_c/\dd \ln R)|_{R_0}$%s$%.2f$%s$-0.2\ \mathrm{to}\ 0$\\\\\n' % (delimiter,potential.dvcircdR(pot,1.),delimiter)
    outfile.write(printline)
    printline= '$M(r<60\kpc)\,(10^{11}\,M_\odot)$%s$%.1f$%s$4.0\pm0.7$\\\\\n' % (delimiter,mass60(pot,options),delimiter)
    outfile.write(printline)
    outfile.write('%s%s\\\\\n' % (delimiter,delimiter))
    #Now some derived properties
    printline= '$M_b\,(10^{10}\,M_\odot)$%s$%.1f$%s\ldots\\\\\n' % (delimiter,pot[0].mass(10.)*bovy_conversion.mass_in_1010msol(_REFV0,_REFR0),delimiter)
    outfile.write(printline)
    if options.twodisks:
        printline= '$M_d\,(10^{10}\,M_\odot)$%s$%.1f$%s\ldots\\\\\n' % (delimiter,(pot[1]._amp+pot[2]._amp)*bovy_conversion.mass_in_1010msol(_REFV0,_REFR0),delimiter)
    else:
        printline= '$M_d\,(10^{10}\,M_\odot)$%s$%.1f$%s\ldots\\\\\n' % (delimiter,pot[1]._amp*bovy_conversion.mass_in_1010msol(_REFV0,_REFR0),delimiter)
    outfile.write(printline)
    krs= numpy.linspace(4./_REFR0,9./_REFR0,101)
    disksurf= numpy.array([visible_dens(pot,options,r=kr) for kr in krs])
    p= numpy.polyfit(krs,numpy.log(disksurf),1)
    rd= -1./p[0]*_REFR0
    printline= '$R_{d}\,(\kpc)$%s$%.1f$%s\ldots\\\\\n' % (delimiter,rd,delimiter)
    outfile.write(printline)
    rvir= pot[2+options.twodisks].rvir(_REFV0,_REFR0,wrtcrit=True,overdens=96.7)
    printline= '$\\rho_{\mathrm{DM}}(R_0)\,(M_\odot\pc^{-3})$%s$%.3f$%s\\\\\n' % (delimiter,potential.evaluateDensities(1.,0.,pot[2+options.twodisks])*bovy_conversion.dens_in_msolpc3(_REFV0,_REFR0),delimiter)
    outfile.write(printline)
    printline= '$M_{\mathrm{vir}}\,(10^{12}\,M_\odot)$%s$%.1f$%s\ldots\\\\\n' % (delimiter,pot[2+options.twodisks].mass(rvir)*bovy_conversion.mass_in_1010msol(_REFV0,_REFR0)/100.,delimiter)
    outfile.write(printline)
    printline= '$r_{\mathrm{vir}}\,(\kpc)$%s$%.0f$%s\ldots\\\\\n' % (delimiter,rvir*_REFR0,delimiter)
    outfile.write(printline)
    printline= '$\mathrm{Concentration}$%s$%.1f$%s\ldots\\\\\n' % (delimiter,rvir/pot[2+options.twodisks].a,delimiter)
    outfile.write(printline)
    printline= '$v_{\mathrm{esc}}(R_0)\,(\kms)$%s$%.0f$%s\ldots\n' % (delimiter,potential.vesc(pot,1.)*_REFV0,delimiter)
    outfile.write(printline)
    #printline= '$r_{\mathrm{vir}}\,(\kpc)$%s$%.0f$%s\ldots\\\\\n' % (delimiter,delimiter)
    #outfile.write(printline)
    
    outfile.write('\\enddata\n')
    pass
Example #36
0
def fdotdotSB1cal(ldeg, bdeg, dkpc, mul, mub, vrad):

    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    yrts = par.yrts
    c = par.c
    kpctom = par.kpctom
    Rs = Rskpc * kpctom
    mastorad = par.mastorad

    normpottoSI = par.normpottoSI
    normForcetoSI = par.normForcetoSI
    normjerktoSI = par.normjerktoSI

    b = bdeg * par.degtorad
    l = ldeg * par.degtorad

    Rpkpc = par.Rpkpc(ldeg, bdeg, dkpc)

    zkpc = par.z(ldeg, bdeg, dkpc)

    fex_pl = excGal.Expl(ldeg, bdeg, dkpc)

    fex_z = excGal.Exz(ldeg, bdeg, dkpc)

    fex_shk = Shk.Exshk(dkpc, mul, mub)

    fex_tot = fex_pl + fex_z + fex_shk

    #mub = mu_alpha #mas/yr
    #mul = mu_delta

    muT = (mub**2. + mul**2.)**0.5
    #MWPotential2014= [MWPotential2014,KeplerPotential(amp=4*10**6./bovy_conversion.mass_in_msol(par.Vs,par.Rskpc))]
    MWPot = MWPotential2014

    appl = -evaluateRforces(MWPot, Rpkpc / Rskpc, zkpc / Rskpc) * normForcetoSI
    aspl = -evaluateRforces(MWPot, Rskpc / Rskpc, 0.0 / Rskpc) * normForcetoSI
    apz = evaluatezforces(MWPot, Rpkpc / Rskpc, zkpc / Rskpc) * normForcetoSI

    be = (dkpc / Rskpc) * math.cos(b) - math.cos(l)
    coslam = be * (Rskpc / Rpkpc)
    coslpluslam = math.cos(l) * coslam - (Rskpc * math.sin(l) /
                                          Rpkpc) * math.sin(l)

    aTl1 = -(appl * (Rskpc * math.sin(l) / Rpkpc) - aspl * math.sin(l))
    aTb1 = appl * coslam * math.sin(b) + apz * math.cos(b) + aspl * math.cos(
        l) * math.sin(b)
    aTnet1 = (aTl1**2. + aTb1**2.)**(0.5)
    alphaV1 = math.atan2(mub, mul) / par.degtorad
    alphaA1 = math.atan2(aTb1, aTl1) / par.degtorad
    if alphaV1 < 0.:
        alphaV = 360. + alphaV1
    else:
        alphaV = alphaV1

    if alphaA1 < 0.:
        alphaA = 360. + alphaA1
    else:
        alphaA = alphaA1
    alpha = abs(alphaA - alphaV)

    aT1 = 2. * appl * aspl * coslpluslam
    aT2 = (c * (fex_pl + fex_z))**2.
    aTsq = appl**2. + aspl**2. + aT1 + apz**2. - aT2
    #if aTsq < 0.0:
    aT = (appl**2. + aspl**2. + aT1 + apz**2. - aT2)**0.5

    zdot = (1000.0 * vrad) * math.sin(b) + (mastorad / yrts) * mub * (
        dkpc * kpctom) * math.cos(b)
    Rpdot = (1. / (Rpkpc * kpctom)) * (
        ((dkpc * kpctom) *
         (math.cos(b)**2.) - Rs * math.cos(b) * math.cos(l)) *
        (1000.0 * vrad) + (Rs * (dkpc * kpctom) * math.sin(b) * math.cos(l) -
                           ((dkpc * kpctom)**2.) * math.cos(b) * math.sin(b)) *
        ((mastorad / yrts) * mub) + Rs * (dkpc * kpctom) * math.sin(l) *
        ((mastorad / yrts) * mul))

    phiR2 = normjerktoSI * evaluateR2derivs(MWPot, Rpkpc / Rskpc, zkpc / Rskpc)
    phiz2 = normjerktoSI * evaluatez2derivs(MWPot, Rpkpc / Rskpc, zkpc / Rskpc)
    phiRz = normjerktoSI * evaluateRzderivs(MWPot, Rpkpc / Rskpc, zkpc / Rskpc)
    phiR2sun = normjerktoSI * evaluateR2derivs(MWPot, Rskpc / Rskpc,
                                               0.0 / Rskpc)
    phiRzsun = normjerktoSI * evaluateRzderivs(MWPot, Rskpc / Rskpc,
                                               0.0 / Rskpc)
    aspldot = phiR2sun * Rpdot + phiRzsun * zdot
    appldot = phiR2 * Rpdot + phiRz * zdot
    if b > 0:
        apzdot = phiRz * Rpdot + phiz2 * zdot
    else:
        apzdot = -(phiRz * Rpdot + phiz2 * zdot)

    #if coslam != 0.0 and Rpkpc != 0.0 and math.cos(b) != 0.0:

    lamdot = (1. / coslam) * ((Rs * math.cos(l) * ((mastorad / yrts) * mul)) /
                              ((Rpkpc * kpctom) * math.cos(b)) -
                              (Rs * math.sin(l) /
                               ((Rpkpc * kpctom)**2.)) * Rpdot)
    ardot1 = math.sin(b) * (appl * coslam + aspl * math.cos(l)) * (
        (mastorad / yrts) * mub)
    ardot2 = math.cos(b) * (appldot * coslam + aspldot * math.cos(l))
    ardot3 = apzdot * math.sin(abs(b))
    ardot4 = appl * math.cos(b) * (Rskpc * math.sin(l) / Rpkpc) * lamdot
    ardot5 = aspl * math.sin(l) * ((mastorad / yrts) * mul)
    ardot6 = abs(apz) * math.cos(b) * ((mastorad / yrts) * mub) * (b / abs(b))
    ardot = ardot1 - ardot2 - ardot3 + ardot4 + ardot5 - ardot6

    jerkt = (1. / c) * (ardot - aT *
                        ((mastorad / yrts) * muT) * math.cos(alpha))
    return jerkt
def like_func(params,surfrs,kzs,kzerrs,
              termdata,options):
    #Check ranges
    if params[0] < 0. or params[0] > 1.: return numpy.finfo(numpy.dtype(numpy.float64)).max
    if params[1] < 0. or params[1] > 1.: return numpy.finfo(numpy.dtype(numpy.float64)).max
    if options.twodisks and (params[2] < 0. or params[2] > 1.): return numpy.finfo(numpy.dtype(numpy.float64)).max
    if (1.-params[0]-params[1]-options.twodisks*params[2]) < 0. or (1.-params[0]-params[1]-options.twodisks*params[2]) > 1.: return numpy.finfo(numpy.dtype(numpy.float64)).max
    if params[2+options.twodisks] < numpy.log(1./_REFR0) or params[2+options.twodisks] > numpy.log(8./_REFR0):
        return numpy.finfo(numpy.dtype(numpy.float64)).max
    if params[3+options.twodisks] < numpy.log(0.05/_REFR0) or params[3+options.twodisks] > numpy.log(1./_REFR0):
        return numpy.finfo(numpy.dtype(numpy.float64)).max
    if options.twodisks:
        if params[5] < numpy.log(1./_REFR0) or params[5] > numpy.log(8./_REFR0):
            return numpy.finfo(numpy.dtype(numpy.float64)).max
        if params[6] < numpy.log(0.05/_REFR0) or params[6] > numpy.log(1./_REFR0):
            return numpy.finfo(numpy.dtype(numpy.float64)).max
    #Setup potential
    if options.twodisks:
        pot= [potential.PowerSphericalPotentialwCutoff(normalize=1.-params[0]-params[1]-params[2],
                                                       alpha=1.8,rc=1.9/_REFR0),
              potential.MiyamotoNagaiPotential(normalize=params[0],
                                               a=numpy.exp(params[3]),
                                               b=numpy.exp(params[4])),
              potential.MiyamotoNagaiPotential(normalize=params[1],
                                               a=numpy.exp(params[5]),
                                               b=numpy.exp(params[6])),
              potential.NFWPotential(normalize=params[2],
                                     a=numpy.exp(params[7]))]
    else:
        pot= [potential.PowerSphericalPotentialwCutoff(normalize=1.-params[0]-params[1],
                                                       alpha=1.8,rc=1.9/_REFR0),
              potential.MiyamotoNagaiPotential(normalize=params[0],
                                               a=numpy.exp(params[2]),
                                               b=numpy.exp(params[3])),
              potential.NFWPotential(normalize=params[1],a=numpy.exp(params[4]))]
    #Calculate model surface density at surfrs
    modelkzs= numpy.empty_like(surfrs)
    for ii in range(len(surfrs)):
        modelkzs[ii]= -potential.evaluatezforces(surfrs[ii]/_REFR0,1.1/_REFR0,
                                                 pot)*bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0)
    out= 0.5*numpy.sum((kzs-modelkzs)**2./kzerrs**2.)
    #Add terminal velocities
    vrsun= params[5+3*options.twodisks]
    vtsun= params[6+3*options.twodisks]
    cl_glon, cl_vterm, cl_corr, mc_glon, mc_vterm, mc_corr= termdata
    #Calculate terminal velocities at data glon
    cl_vterm_model= numpy.zeros_like(cl_vterm)
    for ii in range(len(cl_glon)):
        cl_vterm_model[ii]= potential.vterm(pot,cl_glon[ii])
    cl_vterm_model+= vrsun*numpy.cos(cl_glon/180.*numpy.pi)\
        -vtsun*numpy.sin(cl_glon/180.*numpy.pi)
    mc_vterm_model= numpy.zeros_like(mc_vterm)
    for ii in range(len(mc_glon)):
        mc_vterm_model[ii]= potential.vterm(pot,mc_glon[ii])
    mc_vterm_model+= vrsun*numpy.cos(mc_glon/180.*numpy.pi)\
        -vtsun*numpy.sin(mc_glon/180.*numpy.pi)
    cl_dvterm= (cl_vterm-cl_vterm_model)/options.termsigma*_REFV0
    mc_dvterm= (mc_vterm-mc_vterm_model)/options.termsigma*_REFV0
    out+= 0.5*numpy.sum(cl_dvterm*numpy.dot(cl_corr,cl_dvterm))
    out+= 0.5*numpy.sum(mc_dvterm*numpy.dot(mc_corr,mc_dvterm))
    #Rotation curve constraint
    out-= logprior_dlnvcdlnr(potential.dvcircdR(pot,1.))
    #K dwarfs, Kz
    out+= 0.5*(-potential.evaluatezforces(1.,1.1/_REFR0,pot)*bovy_conversion.force_in_2piGmsolpc2(_REFV0,_REFR0)-67.)**2./36.
    #K dwarfs, visible
    out+= 0.5*(visible_dens(pot,options)-55.)**2./25.
    #Local density prior
    localdens= potential.evaluateDensities(1.,0.,pot)*bovy_conversion.dens_in_msolpc3(_REFV0,_REFR0)
    out+= 0.5*(localdens-0.102)**2./0.01**2.
    #Bulge velocity dispersion
    out+= 0.5*(bulge_dispersion(pot)-117.)**2./225.
    #Mass at 60 kpc
    out+= 0.5*(mass60(pot,options)-4.)**2./0.7**2.
    #Concentration prior?
    return out
Example #38
0
 def __init__(self,
              RZPot=None,rgrid=(0.01,2.,101),zgrid=(0.,0.2,101),logR=False,
              interpPot=False,interpRforce=False,interpzforce=False,
              interpDens=False,
              interpvcirc=False,
              interpdvcircdr=False,
              interpepifreq=False,interpverticalfreq=False,
              use_c=False,enable_c=False,zsym=True,
              numcores=None):
     """
     NAME:
        __init__
     PURPOSE:
        Initialize an interpRZPotential instance
     INPUT:
        RZPot - RZPotential to be interpolated
        rgrid - R grid to be given to linspace
        zgrid - z grid to be given to linspace
        logR - if True, rgrid is in the log of R
        interpPot, interpRfoce, interpzforce, interpDens,interpvcirc, interpeopifreq, interpverticalfreq, interpdvcircdr= if True, interpolate these functions
        use_c= use C to speed up the calculation
        enable_c= enable use of C for interpolations
        zsym= if True (default), the potential is assumed to be symmetric around z=0 (so you can use, e.g.,  zgrid=(0.,1.,101)).
        numcores= if set to an integer, use this many cores (only used for vcirc, dvcircdR, epifreq, and verticalfreq; NOT NECESSARILY FASTER, TIME TO MAKE SURE)
     OUTPUT:
        instance
     HISTORY:
        2010-07-21 - Written - Bovy (NYU)
        2013-01-24 - Started with new implementation - Bovy (IAS)
     """
     Potential.__init__(self,amp=1.)
     self.hasC= True
     self._origPot= RZPot
     self._rgrid= numpy.linspace(*rgrid)
     self._logR= logR
     if self._logR:
         self._rgrid= numpy.exp(self._rgrid)
         self._logrgrid= numpy.log(self._rgrid)
     self._zgrid= numpy.linspace(*zgrid)
     self._interpPot= interpPot
     self._interpRforce= interpRforce
     self._interpzforce= interpzforce
     self._interpDens= interpDens
     self._interpvcirc= interpvcirc
     self._interpdvcircdr= interpdvcircdr
     self._interpepifreq= interpepifreq
     self._interpverticalfreq= interpverticalfreq
     self._enable_c= enable_c*ext_loaded
     self._zsym= zsym
     if interpPot:
         if use_c*ext_loaded:
             self._potGrid, err= calc_potential_c(self._origPot,self._rgrid,self._zgrid)
         else:
             from galpy.potential import evaluatePotentials
             potGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
             for ii in range(len(self._rgrid)):
                 for jj in range(len(self._zgrid)):
                     potGrid[ii,jj]= evaluatePotentials(self._rgrid[ii],self._zgrid[jj],self._origPot)
             self._potGrid= potGrid
         if self._logR:
             self._potInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                              self._zgrid,
                                                              self._potGrid,
                                                              kx=3,ky=3,s=0.)
         else:
             self._potInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                              self._zgrid,
                                                              self._potGrid,
                                                              kx=3,ky=3,s=0.)
         if enable_c*ext_loaded:
             self._potGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._potGrid)
     if interpRforce:
         if use_c*ext_loaded:
             self._rforceGrid, err= calc_potential_c(self._origPot,self._rgrid,self._zgrid,rforce=True)
         else:
             from galpy.potential import evaluateRforces
             rforceGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
             for ii in range(len(self._rgrid)):
                 for jj in range(len(self._zgrid)):
                     rforceGrid[ii,jj]= evaluateRforces(self._rgrid[ii],self._zgrid[jj],self._origPot)
             self._rforceGrid= rforceGrid
         if self._logR:
             self._rforceInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                                 self._zgrid,
                                                                 self._rforceGrid,
                                                                 kx=3,ky=3,s=0.)
         else:
             self._rforceInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                                 self._zgrid,
                                                                 self._rforceGrid,
                                                                 kx=3,ky=3,s=0.)
         if enable_c*ext_loaded:
             self._rforceGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._rforceGrid)
     if interpzforce:
         if use_c*ext_loaded:
             self._zforceGrid, err= calc_potential_c(self._origPot,self._rgrid,self._zgrid,zforce=True)
         else:
             from galpy.potential import evaluatezforces
             zforceGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
             for ii in range(len(self._rgrid)):
                 for jj in range(len(self._zgrid)):
                     zforceGrid[ii,jj]= evaluatezforces(self._rgrid[ii],self._zgrid[jj],self._origPot)
             self._zforceGrid= zforceGrid
         if self._logR:
             self._zforceInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                                 self._zgrid,
                                                                 self._zforceGrid,
                                                                 kx=3,ky=3,s=0.)
         else:
             self._zforceInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                                 self._zgrid,
                                                                 self._zforceGrid,
                                                                 kx=3,ky=3,s=0.)
         if enable_c*ext_loaded:
             self._zforceGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._zforceGrid)
     if interpDens:
         if False:
             raise NotImplementedError("Using C to calculate an interpolation grid for the density is not supported currently")
             self._densGrid, err= calc_dens_c(self._origPot,self._rgrid,self._zgrid)
         else:
             from galpy.potential import evaluateDensities
             densGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
             for ii in range(len(self._rgrid)):
                 for jj in range(len(self._zgrid)):
                     densGrid[ii,jj]= evaluateDensities(self._rgrid[ii],self._zgrid[jj],self._origPot)
             self._densGrid= densGrid
         if self._logR:
             self._densInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                               self._zgrid,
                                                               numpy.log(self._densGrid+10.**-10.),
                                                               kx=3,ky=3,s=0.)
         else:
             self._densInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                               self._zgrid,
                                                               numpy.log(self._densGrid+10.**-10.),
                                                               kx=3,ky=3,s=0.)
         if False:
             self._densGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._densGrid)
     if interpvcirc:
         from galpy.potential import vcirc
         if not numcores is None:
             self._vcircGrid= multi.parallel_map((lambda x: vcirc(self._origPot,self._rgrid[x])),
                                                 range(len(self._rgrid)),numcores=numcores)
         else:
             self._vcircGrid= numpy.array([vcirc(self._origPot,r) for r in self._rgrid])
         if self._logR:
             self._vcircInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid,self._vcircGrid,k=3)
         else:
             self._vcircInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid,self._vcircGrid,k=3)
     if interpdvcircdr:
         from galpy.potential import dvcircdR
         if not numcores is None:
             self._dvcircdrGrid= multi.parallel_map((lambda x: dvcircdR(self._origPot,self._rgrid[x])),
                                                    range(len(self._rgrid)),numcores=numcores)
         else:
             self._dvcircdrGrid= numpy.array([dvcircdR(self._origPot,r) for r in self._rgrid])
         if self._logR:
             self._dvcircdrInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid,self._dvcircdrGrid,k=3)
         else:
             self._dvcircdrInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid,self._dvcircdrGrid,k=3)
     if interpepifreq:
         from galpy.potential import epifreq
         if not numcores is None:
             self._epifreqGrid= multi.parallel_map((lambda x: epifreq(self._origPot,self._rgrid[x])),
                                                   range(len(self._rgrid)),numcores=numcores)
         else:
             self._epifreqGrid= numpy.array([epifreq(self._origPot,r) for r in self._rgrid])
         indx= True-numpy.isnan(self._epifreqGrid)
         if numpy.sum(indx) < 4:
             if self._logR:
                 self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=1)
             else:
                 self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=1)
         else:
             if self._logR:
                 self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=3)
             else:
                 self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=3)
     if interpverticalfreq:
         from galpy.potential import verticalfreq
         if not numcores is None:
             self._verticalfreqGrid= multi.parallel_map((lambda x: verticalfreq(self._origPot,self._rgrid[x])),
                                                    range(len(self._rgrid)),numcores=numcores)
         else:
             self._verticalfreqGrid= numpy.array([verticalfreq(self._origPot,r) for r in self._rgrid])
         if self._logR:
             self._verticalfreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid,self._verticalfreqGrid,k=3)
         else:
             self._verticalfreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid,self._verticalfreqGrid,k=3)
     return None
Example #39
0
    def __init__(self,
                 RZPot=None,rgrid=(numpy.log(0.01),numpy.log(20.),101),
                 zgrid=(0.,1.,101),logR=True,
                 interpPot=False,interpRforce=False,interpzforce=False,
                 interpDens=False,
                 interpvcirc=False,
                 interpdvcircdr=False,
                 interpepifreq=False,interpverticalfreq=False,
                 ro=None,vo=None,
                 use_c=False,enable_c=False,zsym=True,
                 numcores=None):
        """
        NAME:

           __init__

        PURPOSE:

           Initialize an interpRZPotential instance

        INPUT:

           RZPot - RZPotential to be interpolated

           rgrid - R grid to be given to linspace as in rs= linspace(*rgrid)

           zgrid - z grid to be given to linspace as in zs= linspace(*zgrid)

           logR - if True, rgrid is in the log of R so logrs= linspace(*rgrid)

           interpPot, interpRforce, interpzforce, interpDens,interpvcirc, interpepifreq, interpverticalfreq, interpdvcircdr= if True, interpolate these functions

           use_c= use C to speed up the calculation of the grid

           enable_c= enable use of C for interpolations

           zsym= if True (default), the potential is assumed to be symmetric around z=0 (so you can use, e.g.,  zgrid=(0.,1.,101)).

           numcores= if set to an integer, use this many cores (only used for vcirc, dvcircdR, epifreq, and verticalfreq; NOT NECESSARILY FASTER, TIME TO MAKE SURE)

           ro=, vo= distance and velocity scales for translation into internal units (default from configuration file)

        OUTPUT:

           instance

        HISTORY:

           2010-07-21 - Written - Bovy (NYU)

           2013-01-24 - Started with new implementation - Bovy (IAS)

        """
        if isinstance(RZPot,interpRZPotential):
            from galpy.potential import PotentialError
            raise PotentialError('Cannot setup interpRZPotential with another interpRZPotential')
        # Propagate ro and vo
        roSet= True
        voSet= True
        if ro is None:
            if isinstance(RZPot,list):
                ro= RZPot[0]._ro
                roSet= RZPot[0]._roSet
            else:
                ro= RZPot._ro
                roSet= RZPot._roSet
        if vo is None:
            if isinstance(RZPot,list):
                vo= RZPot[0]._vo
                voSet= RZPot[0]._voSet
            else:
                vo= RZPot._vo
                voSet= RZPot._voSet
        Potential.__init__(self,amp=1.,ro=ro,vo=vo)
        # Turn off physical if it hadn't been on
        if not roSet: self._roSet= False
        if not voSet: self._voSet= False
        self._origPot= RZPot
        self._rgrid= numpy.linspace(*rgrid)
        self._logR= logR
        if self._logR:
            self._rgrid= numpy.exp(self._rgrid)
            self._logrgrid= numpy.log(self._rgrid)
        self._zgrid= numpy.linspace(*zgrid)
        self._interpPot= interpPot
        self._interpRforce= interpRforce
        self._interpzforce= interpzforce
        self._interpDens= interpDens
        self._interpvcirc= interpvcirc
        self._interpdvcircdr= interpdvcircdr
        self._interpepifreq= interpepifreq
        self._interpverticalfreq= interpverticalfreq
        self._enable_c= enable_c*ext_loaded
        self.hasC= self._enable_c
        self._zsym= zsym
        if interpPot:
            if use_c*ext_loaded:
                self._potGrid, err= calc_potential_c(self._origPot,self._rgrid,self._zgrid)
            else:
                from galpy.potential import evaluatePotentials
                potGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
                for ii in range(len(self._rgrid)):
                    for jj in range(len(self._zgrid)):
                        potGrid[ii,jj]= evaluatePotentials(self._origPot,self._rgrid[ii],self._zgrid[jj])
                self._potGrid= potGrid
            if self._logR:
                self._potInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                                 self._zgrid,
                                                                 self._potGrid,
                                                                 kx=3,ky=3,s=0.)
            else:
                self._potInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                                 self._zgrid,
                                                                 self._potGrid,
                                                                 kx=3,ky=3,s=0.)
            if enable_c*ext_loaded:
                self._potGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._potGrid)
        if interpRforce:
            if use_c*ext_loaded:
                self._rforceGrid, err= calc_potential_c(self._origPot,self._rgrid,self._zgrid,rforce=True)
            else:
                from galpy.potential import evaluateRforces
                rforceGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
                for ii in range(len(self._rgrid)):
                    for jj in range(len(self._zgrid)):
                        rforceGrid[ii,jj]= evaluateRforces(self._origPot,self._rgrid[ii],self._zgrid[jj])
                self._rforceGrid= rforceGrid
            if self._logR:
                self._rforceInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                                    self._zgrid,
                                                                    self._rforceGrid,
                                                                    kx=3,ky=3,s=0.)
            else:
                self._rforceInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                                    self._zgrid,
                                                                    self._rforceGrid,
                                                                    kx=3,ky=3,s=0.)
            if enable_c*ext_loaded:
                self._rforceGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._rforceGrid)
        if interpzforce:
            if use_c*ext_loaded:
                self._zforceGrid, err= calc_potential_c(self._origPot,self._rgrid,self._zgrid,zforce=True)
            else:
                from galpy.potential import evaluatezforces
                zforceGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
                for ii in range(len(self._rgrid)):
                    for jj in range(len(self._zgrid)):
                        zforceGrid[ii,jj]= evaluatezforces(self._origPot,self._rgrid[ii],self._zgrid[jj])
                self._zforceGrid= zforceGrid
            if self._logR:
                self._zforceInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                                    self._zgrid,
                                                                    self._zforceGrid,
                                                                    kx=3,ky=3,s=0.)
            else:
                self._zforceInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                                    self._zgrid,
                                                                    self._zforceGrid,
                                                                    kx=3,ky=3,s=0.)
            if enable_c*ext_loaded:
                self._zforceGrid_splinecoeffs= calc_2dsplinecoeffs_c(self._zforceGrid)
        if interpDens:
            from galpy.potential import evaluateDensities
            densGrid= numpy.zeros((len(self._rgrid),len(self._zgrid)))
            for ii in range(len(self._rgrid)):
                for jj in range(len(self._zgrid)):
                    densGrid[ii,jj]= evaluateDensities(self._origPot,self._rgrid[ii],self._zgrid[jj])
            self._densGrid= densGrid
            if self._logR:
                self._densInterp= interpolate.RectBivariateSpline(self._logrgrid,
                                                                  self._zgrid,
                                                                  numpy.log(self._densGrid+10.**-10.),
                                                                  kx=3,ky=3,s=0.)
            else:
                self._densInterp= interpolate.RectBivariateSpline(self._rgrid,
                                                                  self._zgrid,
                                                                  numpy.log(self._densGrid+10.**-10.),
                                                                  kx=3,ky=3,s=0.)
        if interpvcirc:
            from galpy.potential import vcirc
            if not numcores is None:
                self._vcircGrid= multi.parallel_map((lambda x: vcirc(self._origPot,self._rgrid[x])),
                                                    list(range(len(self._rgrid))),numcores=numcores)
            else:
                self._vcircGrid= numpy.array([vcirc(self._origPot,r) for r in self._rgrid])
            if self._logR:
                self._vcircInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid,self._vcircGrid,k=3)
            else:
                self._vcircInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid,self._vcircGrid,k=3)
        if interpdvcircdr:
            from galpy.potential import dvcircdR
            if not numcores is None:
                self._dvcircdrGrid= multi.parallel_map((lambda x: dvcircdR(self._origPot,self._rgrid[x])),
                                                       list(range(len(self._rgrid))),numcores=numcores)
            else:
                self._dvcircdrGrid= numpy.array([dvcircdR(self._origPot,r) for r in self._rgrid])
            if self._logR:
                self._dvcircdrInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid,self._dvcircdrGrid,k=3)
            else:
                self._dvcircdrInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid,self._dvcircdrGrid,k=3)
        if interpepifreq:
            from galpy.potential import epifreq
            if not numcores is None:
                self._epifreqGrid= numpy.array(multi.parallel_map((lambda x: epifreq(self._origPot,self._rgrid[x])),
                                                      list(range(len(self._rgrid))),numcores=numcores))
            else:
                self._epifreqGrid= numpy.array([epifreq(self._origPot,r) for r in self._rgrid])
            indx= True^numpy.isnan(self._epifreqGrid)
            if numpy.sum(indx) < 4:
                if self._logR:
                    self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=1)
                else:
                    self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=1)
            else:
                if self._logR:
                    self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=3)
                else:
                    self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=3)
        if interpverticalfreq:
            from galpy.potential import verticalfreq
            if not numcores is None:
                self._verticalfreqGrid= multi.parallel_map((lambda x: verticalfreq(self._origPot,self._rgrid[x])),
                                                       list(range(len(self._rgrid))),numcores=numcores)
            else:
                self._verticalfreqGrid= numpy.array([verticalfreq(self._origPot,r) for r in self._rgrid])
            if self._logR:
                self._verticalfreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid,self._verticalfreqGrid,k=3)
            else:
                self._verticalfreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid,self._verticalfreqGrid,k=3)
        return None
Example #40
0
def fdotdotexcwBHcal(ldeg, bdeg, dkpc, mul, mub, Rpkpc, zkpc, f, fdotobs, vrad,
                     fex_pl, fex_z, fex_shk):

    Rskpc = par.Rskpc
    Vs = par.Vs
    conversion = par.conversion
    yrts = par.yrts
    c = par.c
    kpctom = par.kpctom
    Rs = Rskpc * kpctom
    mastorad = par.mastorad

    normpottoSI = par.normpottoSI
    normForcetoSI = par.normForcetoSI
    normjerktoSI = par.normjerktoSI

    b = bdeg * par.degtorad
    l = ldeg * par.degtorad

    fex_tot = fex_pl + fex_z + fex_shk

    #mub = mu_alpha #mas/yr
    #mul = mu_delta

    muT = (mub**2. + mul**2.)**0.5
    #MWPotential2014= [MWPotential2014,KeplerPotential(amp=4*10**6./bovy_conversion.mass_in_msol(par.Vs,par.Rskpc))]
    MWPot = [
        MWPotential2014,
        KeplerPotential(amp=4 * 10**6. /
                        bovy_conversion.mass_in_msol(par.Vs, par.Rskpc))
    ]

    appl = evaluateRforces(MWPot, Rpkpc / Rskpc, zkpc / Rskpc) * normForcetoSI
    aspl = evaluateRforces(MWPot, Rskpc / Rskpc, 0.0 / Rskpc) * normForcetoSI
    apz = evaluatezforces(MWPot, Rpkpc / Rskpc, zkpc / Rskpc) * normForcetoSI

    be = (dkpc / Rskpc) * math.cos(b) - math.cos(l)
    coslam = be * (Rskpc / Rpkpc)
    coslpluslam = math.cos(l) * coslam - (Rskpc * math.sin(l) /
                                          Rpkpc) * math.sin(l)

    aTl1 = -(appl * (Rskpc * math.sin(l) / Rpkpc) - aspl * math.sin(l))
    aTb1 = appl * coslam * math.sin(b) - apz * math.cos(b) + aspl * math.cos(
        l) * math.sin(b)
    aTnet1 = (aTl1**2. + aTb1**2.)**(0.5)
    alphaV1 = math.atan2(mub, mul) / par.degtorad
    alphaA1 = math.atan2(aTb1, aTl1) / par.degtorad
    if alphaV1 < 0.:
        alphaV = 360. + alphaV1
    else:
        alphaV = alphaV1

    if alphaA1 < 0.:
        alphaA = 360. + alphaA1
    else:
        alphaA = alphaA1
    alpha = abs(alphaA - alphaV)

    aT1 = 2. * appl * aspl * coslpluslam
    aT2 = (c * (fex_pl + fex_z))**2.
    aTsq = appl**2. + aspl**2. + aT1 + apz**2. - aT2
    #if aTsq < 0.0:
    aT = (appl**2. + aspl**2. + aT1 + apz**2. - aT2)**0.5

    Combterm = fdotdotSB1cal(
        ldeg, bdeg, dkpc, mul, mub, Rpkpc, zkpc, vrad, coslam,
        alpha, appl, apz, aspl, aT, MWPot) + fdotdotSB2cal(
            ldeg, bdeg, dkpc, mul, mub, Rpkpc, zkpc, fex_pl, fex_z, fex_shk,
            appl, apz, aspl) + fdotdotSB3cal(vrad, aT, muT, alpha)

    fddotfex = -Combterm + fdotdotSB4cal(f, fdotobs, fex_pl, fex_z, fex_shk)

    #fdotint = fdotobs-fs*fex_tot
    #fddotint = fddotobs-fs*fddotfex

    return fddotfex
Example #41
0
def plot_DFsingles(options,args):
    raw= read_rawdata(options)
    #Bin the data
    binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe)
    if options.tighten:
        tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe,
                                 fehmin=-1.6,fehmax=0.5,afemin=-0.05,
                                 afemax=0.55)
    else:
        tightbinned= binned
    #Map the bins with ndata > minndata in 1D
    fehs, afes= [], []
    counter= 0
    abindx= numpy.zeros((len(binned.fehedges)-1,len(binned.afeedges)-1),
                        dtype='int')
    for ii in range(len(binned.fehedges)-1):
        for jj in range(len(binned.afeedges)-1):
            data= binned(binned.feh(ii),binned.afe(jj))
            if len(data) < options.minndata:
                continue
            #print binned.feh(ii), binned.afe(jj), len(data)
            fehs.append(binned.feh(ii))
            afes.append(binned.afe(jj))
            abindx[ii,jj]= counter
            counter+= 1
    nabundancebins= len(fehs)
    fehs= numpy.array(fehs)
    afes= numpy.array(afes)
    #Load each solutions
    sols= []
    savename= args[0]
    initname= options.init
    for ii in range(nabundancebins):
        spl= savename.split('.')
        newname= ''
        for jj in range(len(spl)-1):
            newname+= spl[jj]
            if not jj == len(spl)-2: newname+= '.'
        newname+= '_%i.' % ii
        newname+= spl[-1]
        savefilename= newname
        #Read savefile
        try:
            savefile= open(savefilename,'rb')
        except IOError:
            print "WARNING: MISSING ABUNDANCE BIN"
            sols.append(None)
        else:
            sols.append(pickle.load(savefile))
            savefile.close()
        #Load samples as well
        if options.mcsample:
            #Do the same for init
            spl= initname.split('.')
            newname= ''
            for jj in range(len(spl)-1):
                newname+= spl[jj]
                if not jj == len(spl)-2: newname+= '.'
            newname+= '_%i.' % ii
            newname+= spl[-1]
            options.init= newname
    mapfehs= monoAbundanceMW.fehs()
    mapafes= monoAbundanceMW.afes()
    #Now plot
    #Run through the pixels and gather
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe' \
            or options.type.lower() == 'afefeh':
        plotthis= []
        errors= []
    else:
        plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe()))
    for ii in range(tightbinned.npixfeh()):
        for jj in range(tightbinned.npixafe()):
            data= binned(tightbinned.feh(ii),tightbinned.afe(jj))
            if len(data) < options.minndata:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            #Find abundance indx
            fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning
            afeindx= binned.afeindx(tightbinned.afe(jj))
            solindx= abindx[fehindx,afeindx]
            monoabindx= numpy.argmin((tightbinned.feh(ii)-mapfehs)**2./0.01 \
                                         +(tightbinned.afe(jj)-mapafes)**2./0.0025)
            if sols[solindx] is None:
                if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                        or options.type.lower() == 'afefeh':
                    continue
                else:
                    plotthis[ii,jj]= numpy.nan
                    continue
            if options.type.lower() == 'q':
                s= get_potparams(sols[solindx],options,1)
                plotthis[ii,jj]= s[0]
                if not options.flatten is None:
                    plotthis[ii,jj]/= options.flatten
            elif options.type.lower() == 'vc':
                if options.fixvo:
                    plotthis[ii,jj]= 1.
                else:
                    s= get_potparams(sols[solindx],options,1)
                    plotthis[ii,jj]= s[1]
            elif options.type.lower() == 'rd':
                s= get_potparams(sols[solindx],options,1)
                plotthis[ii,jj]= numpy.exp(s[0])
            elif options.type.lower() == 'zh':
                s= get_potparams(sols[solindx],options,1)
                plotthis[ii,jj]= numpy.exp(s[2-(1-(options.fixvo is None))])
            elif options.type.lower() == 'ndata':
                plotthis[ii,jj]= len(data)
            elif options.type.lower() == 'hr':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[0]*_REFR0
                if options.relative:
                    thishr= monoAbundanceMW.hr(mapfehs[monoabindx],mapafes[monoabindx])
                    plotthis[ii,jj]/= thishr
            elif options.type.lower() == 'sz':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[2]*_REFV0
                if options.relative:
                    thissz= monoAbundanceMW.sigmaz(mapfehs[monoabindx],mapafes[monoabindx])
                    plotthis[ii,jj]/= thissz
            elif options.type.lower() == 'sr':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[1]*_REFV0
                if options.relative:
                    thissr= monoAbundanceMW.sigmaz(mapfehs[monoabindx],mapafes[monoabindx])*2.
                    plotthis[ii,jj]/= thissr
            elif options.type.lower() == 'srsz':
                #Setup everything
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                aA= setup_aA(pot,options)               
                dfparams= get_dfparams(sols[solindx],0,options,log=False)
                if options.dfmodel.lower() == 'qdf':
                    #Normalize
                    hr= dfparams[0]/ro
                    sr= dfparams[1]/vo
                    sz= dfparams[2]/vo
                    hsr= dfparams[3]/ro
                    hsz= dfparams[4]/ro
                    #Setup
                    qdf= quasiisothermaldf(hr,sr,sz,hsr,hsz,pot=pot,
                                           aA=aA,cutcounter=True)              
                plotthis[ii,jj]= numpy.sqrt(qdf.sigmaR2(1.,1./_REFR0/ro,
                                                        ngl=options.ngl,gl=True)\
                                                /qdf.sigmaz2(1.,1./_REFR0/ro,
                                                            ngl=options.ngl,gl=True))
            elif options.type.lower() == 'outfrac':
                s= get_dfparams(sols[solindx],0,options)
                plotthis[ii,jj]= s[5]
            elif options.type.lower() == 'rhodm':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                    plotthis[ii,jj]= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                elif options.potential.lower() == 'mpdiskflplhalofixplfixbulgeflat':
                    plotthis[ii,jj]= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
            elif options.type.lower() == 'rhoo':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= potential.evaluateDensities(1.,0.,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
            elif options.type.lower() == 'surfz':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
            elif options.type.lower() == 'surfzdisk':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mpdisk' in options.potential.lower() or 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot[0])),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
            elif options.type.lower() == 'kz':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= numpy.fabs(potential.evaluatezforces(1.,options.height/ro/_REFR0,pot)/2./numpy.pi/4.302*_REFV0**2.*vo**2./_REFR0/ro)
            elif options.type.lower() == 'plhalo':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                    plotthis[ii,jj]= pot[1].alpha
            elif options.type.lower() == 'qhalo':
                #Setup potential
                s= get_potparams(sols[solindx],options,1)
                if options.potential.lower() == 'mpdiskflplhalofixplfixbulgeflat':
                    plotthis[ii,jj]= s[4]
            elif options.type.lower() == 'dlnvcdlnr':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                plotthis[ii,jj]= potential.dvcircdR(pot,1.)
            elif options.type.lower() == 'fd':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= (pot[0].vcirc(1.))**2.
            elif options.type.lower() == 'fh':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= (pot[1].vcirc(1.))**2.
            elif options.type.lower() == 'fb':
                #Setup potential
                pot= setup_potential(sols[solindx],options,1)
                vo= get_vo(sols[solindx],options,1)
                ro= get_ro(sols[solindx],options)
                if 'mwpotential' in options.potential.lower():
                    plotthis[ii,jj]= (pot[2].vcirc(1.))**2.
            elif options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \
                    or options.type.lower() == 'afefeh':
                thisplot=[tightbinned.feh(ii),
                          tightbinned.afe(jj),
                          len(data)]
                if options.subtype.lower() == 'qvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisq= s[0]
                    if not options.flatten is None:
                        thisq/= options.flatten
                    thisvc= s[1]
                    thisplot.extend([thisq,thisvc])
                elif options.subtype.lower() == 'rdzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisplot.extend([thisrd,thiszh])
                elif options.subtype.lower() == 'zhvc':
                    s= get_potparams(sols[solindx],options,1)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisvc= s[1]*_REFV0
                    thisplot.extend([thiszh,thisvc])
                elif options.subtype.lower() == 'dlnvcdlnrvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisslope= s[3-(1-(options.fixvo is None))]/30.
                    thisvc= s[1]*_REFV0
                    thisplot.extend([thisslope,thisvc])
                elif options.subtype.lower() == 'rdvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    thisvc= s[1]*_REFV0
                    thisplot.extend([thisrd,thisvc])
                elif options.subtype.lower() == 'rdplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thisrd,thisplhalo])
                elif options.subtype.lower() == 'dlnvcdlnrplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thisslope= s[3-(1-(options.fixvo is None))]/30.
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thisslope,thisplhalo])
                elif options.subtype.lower() == 'dlnvcdlnrzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisslope= s[3-(1-(options.fixvo is None))]/30.
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisplot.extend([thisslope,thiszh])
                elif options.subtype.lower() == 'vc14plhalo':
                    s= get_potparams(sols[solindx],options,1)
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisvc14= potential.vcirc(pot,14./_REFR0/ro)*_REFV0*vo
                    thisplot.extend([thisplhalo,thisvc14])
                elif options.subtype.lower() == 'plhalovc':
                    s= get_potparams(sols[solindx],options,1)
                    thisvc= s[1]*_REFV0
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thisplhalo,thisvc])
                elif options.subtype.lower() == 'zhplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    thisplot.extend([thiszh,thisplhalo])
                elif options.subtype.lower() == 'rhodmzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thiszh])
                elif options.subtype.lower() == 'rhodmsurfz':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thissurfz= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thissurfz])
                elif options.subtype.lower() == 'surfzzh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thissurfz= 2.*integrate.quad((lambda zz: potential.evaluateDensities(1.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
                    thisplot.extend([thissurfz,thiszh])
                elif options.subtype.lower() == 'rhoozh':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thiszh= numpy.exp(s[2-(1-(options.fixvo is None))])
                    thisrhoo= potential.evaluateDensities(1.,0.,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhoo,thiszh])
                elif options.subtype.lower() == 'rhodmvc':
                    s= get_potparams(sols[solindx],options,1)
                    thisvc= s[1]*_REFV0
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thisvc])
                elif options.subtype.lower() == 'rhodmrd':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    thisrdh= numpy.exp(s[0])
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thisrd])
                elif options.subtype.lower() == 'rhodmplhalo':
                    s= get_potparams(sols[solindx],options,1)
                    thisrd= numpy.exp(s[0])
                    #Setup potential
                    pot= setup_potential(sols[solindx],options,1)
                    vo= get_vo(sols[solindx],options,1)
                    ro= get_ro(sols[solindx],options)
                    if options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisplhalo= pot[1].alpha
                    if 'mwpotential' in options.potential.lower():
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    elif options.potential.lower() == 'mpdiskplhalofixbulgeflat':
                        thisrhodm= pot[1].dens(1.,0.)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*10.**-3.
                    thisplot.extend([thisrhodm,thisplhalo])
                plotthis.append(thisplot)
    #Set up plot
    if options.type.lower() == 'q':
        if not options.flatten is None:
            vmin, vmax= 0.9, 1.1
            zlabel=r'$\mathrm{flattening}\ q / %.1f$' % options.flatten
        elif 'real' in options.outfilename.lower():
            vmin, vmax= 0.9, 1.1
            medianq= numpy.median(plotthis[numpy.isfinite(plotthis)])
            plotthis/= medianq
            zlabel=r'$\mathrm{flattening}\ q / %.2f$' % medianq
        else:
            vmin, vmax= 0.5, 1.2
            zlabel=r'$\mathrm{flattening}\ q$'
    elif options.type.lower() == 'vc':
        vmin, vmax= 0.95, 1.05
        zlabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0)
        if 'real' in options.outfilename.lower():
           medianvc= numpy.median(plotthis[numpy.isfinite(plotthis)])
           plotthis/= medianvc
           zlabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0*medianvc)
    elif options.type.lower() == 'rhodm':
        vmin, vmax= 0.00, 0.02
        zlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
    elif options.type.lower() == 'rhoo':
        vmin, vmax= 0.00, 0.2
        zlabel=r'$\rho(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
    elif options.type.lower() == 'surfz':
        vmin, vmax= 50.,120.
        zlabel=r'$\Sigma(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
    elif options.type.lower() == 'surfzdisk':
        vmin, vmax= 20.,90.
        zlabel=r'$\Sigma_{\mathrm{disk}}(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
    elif options.type.lower() == 'kz':
        vmin, vmax= 50.,120.
        zlabel=r'$K_Z(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
    elif options.type.lower() == 'dlnvcdlnr':
        vmin, vmax= -0.3,0.2
        zlabel=r'$\frac{\mathrm{d} \ln V_c}{\mathrm{d} \ln R}$'
    elif options.type.lower() == 'fd':
        vmin, vmax= 0.00, 1.
        zlabel=r'$V_{c,\mathrm{disk}} / V_c\,(R_0)$'
    elif options.type.lower() == 'fh':
        vmin, vmax= 0.00, 1.
        zlabel=r'$V_{c,\mathrm{halo}} / V_c\,(R_0)$'
    elif options.type.lower() == 'fb':
        vmin, vmax= 0.00, .1
        zlabel=r'$V_{c,\mathrm{halo}} / V_c\,(R_0)$'
    elif options.type.lower() == 'rd':
        vmin, vmax= 0.2, 0.6
        zlabel=r'$R_d / R_0$'
    elif options.type.lower() == 'zh':
        vmin, vmax= 0.0125, 0.075
        zlabel=r'$z_h / R_0$'
    elif options.type.lower() == 'plhalo':
        vmin, vmax= 0.0, 2.
        zlabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
    elif options.type.lower() == 'qhalo':
        vmin, vmax= 0.4, 1.15
        zlabel=r'$q_\Phi^{\mathrm{halo}}$'
    elif options.type.lower() == 'ndata':
        vmin, vmax= numpy.nanmin(plotthis), numpy.nanmax(plotthis)
        zlabel=r'$N_\mathrm{data}$'
    elif options.type == 'hr':
        if options.relative:
            vmin, vmax= 0.8, 1.2
            zlabel=r'$\mathrm{input / output\ radial\ scale\ length}$'
        else:
            vmin, vmax= 1.35,4.5
            zlabel=r'$\mathrm{model\ radial\ scale\ length\ [kpc]}$'
    elif options.type == 'sz':
        if options.relative:
            vmin, vmax= 0.8, 1.2
            zlabel= r'$\mathrm{input / output\ model}\ \sigma_z$'
        else:
            vmin, vmax= 10.,60.
            zlabel= r'$\mathrm{model}\ \sigma_z\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'sr':
        if options.relative:
            vmin, vmax= 0.8, 1.2
            zlabel= r'$\mathrm{input/output\ model}\ \sigma_R$'
        else:
            vmin, vmax= 10.,60.
            zlabel= r'$\mathrm{model}\ \sigma_R\ [\mathrm{km\ s}^{-1}]$'
    elif options.type == 'srsz':
        vmin, vmax= 0.5,2.
        zlabel= r'$\sigma_R/\sigma_z\ (R_0,1\,\mathrm{kpc})$'
    elif options.type == 'outfrac':
        vmin, vmax= 0., 1.
        zlabel= r'$\mathrm{relative\ number\ of\ outliers}$'
    elif options.type == 'afe':
        vmin, vmax= 0.0,.5
        zlabel=r'$[\alpha/\mathrm{Fe}]$'
    elif options.type == 'feh':
        vmin, vmax= -1.6,0.4
        zlabel=r'$[\mathrm{Fe/H}]$'
    elif options.type == 'fehafe':
        vmin, vmax= -.7,.7
        zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$'
    elif options.type == 'afefeh':
        vmin, vmax= -.15,.15
        zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$'
    if options.tighten:
        xrange=[-1.6,0.5]
        yrange=[-0.05,0.55]
    else:
        xrange=[-2.,0.5]
        yrange=[-0.2,0.6]
    #Now plot
    if options.type.lower() == 'afe' or options.type.lower() == 'feh' \
            or options.type.lower() == 'fehafe':
        #Gather everything
        afe, feh, ndata, x, y= [], [], [], [], []
        for ii in range(len(plotthis)):
            afe.append(plotthis[ii][1])
            feh.append(plotthis[ii][0])
            ndata.append(plotthis[ii][2])
            x.append(plotthis[ii][3])
            y.append(plotthis[ii][4])
        afe= numpy.array(afe)
        feh= numpy.array(feh)
        ndata= numpy.array(ndata)
        x= numpy.array(x)
        y= numpy.array(y)
        #Process ndata
        ndata= ndata**.5
        ndata= ndata/numpy.median(ndata)*35.
        if options.type.lower() == 'afe':
            plotc= afe
        elif options.type.lower() == 'feh':
            plotc= feh
        elif options.type.lower() == 'afefeh':
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(afe))
            for ii in range(tightbinned.npixfeh()):
                fehbin= ii
                data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\
                                           *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])]
                medianafe= numpy.median(data.afe)
                for jj in range(len(afe)):
                    if feh[jj] == tightbinned.feh(ii):
                        plotc[jj]= afe[jj]-medianafe
        else:
            #Go through the bins to determine whether feh is high or low for this alpha
            plotc= numpy.zeros(len(feh))
            for ii in range(tightbinned.npixafe()):
                afebin= ii
                data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\
                                           *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])]
                medianfeh= numpy.median(data.feh)
                for jj in range(len(feh)):
                    if afe[jj] == tightbinned.afe(ii):
                        plotc[jj]= feh[jj]-medianfeh
        onedhists=False
        if options.subtype.lower() == 'qvc':
            if not options.flatten is None:
                xrange= [0.9,1.1]
                xlabel=r'$\mathrm{flattening}\ q / %.1f$' % options.flatten
            elif 'real' in options.outfilename.lower():
                xrange= [0.9,1.1]
                medianq= numpy.median(x[numpy.isfinite(x)])
                x/= medianq
                xlabel=r'$\mathrm{flattening}\ q / %.2f$' % medianq
            else:
                xrange= [0.5, 1.2]
                xlabel=r'$\mathrm{flattening}\ q$'
            yrange= [0.95, 1.05]
            ylabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0)
            if 'real' in options.outfilename.lower():
                medianvc= numpy.median(y[numpy.isfinite(y)])
                y/= medianvc
                ylabel=r'$V_c / %i\ \mathrm{km\,s}^{-1}$' % int(_REFV0*medianvc)
        elif options.subtype.lower() == 'rdzh':
            yrange= [0.0125,0.1]
            xrange= [0.2,0.8]
            xlabel=r'$R_d / R_0$'
            ylabel=r'$z_h / R_0$'
        elif options.subtype.lower() == 'rdplhalo':
            yrange= [0.,2.]
            xrange= [0.2,0.8]
            xlabel=r'$R_d / R_0$'
            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
        elif options.subtype.lower() == 'vc14plhalo':
            yrange= [210.,280.]
            xrange= [0.,2.]
            xlabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            ylabel=r'$V_c (R=14\,\mathrm{kpc})\ [\mathrm{km\,s}^{-1}$]'
        elif options.subtype.lower() == 'zhplhalo':
            yrange= [0.,2.]
            xrange= [0.0125,0.1]

            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            xlabel=r'$z_h / R_0$'
        elif options.subtype.lower() == 'rhodmplhalo':
            xrange= [0.,0.02]
            yrange= [0.,2.]
            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rhodmzh':
            yrange= [0.0125,0.1]
            xrange= [0.,0.02]
            ylabel=r'$z_h / R_0$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rhoozh':
            yrange= [0.0125,0.1]
            xrange= [0.,0.2]
            ylabel=r'$z_h / R_0$'
            xlabel=r'$\rho(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'surfzzh':
            yrange= [0.0125,0.1]
            xrange= [50.+20.*(options.height-1.1),120.+20.*(options.height-1.1)]
            ylabel=r'$z_h / R_0$'
            xlabel=r'$\Sigma(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
        elif options.subtype.lower() == 'rhodmsurfz':
            yrange= [50.+20.*(options.height-1.1),120.+20.*(options.height-1.1)]
            xrange= [0.,0.02]
            ylabel=r'$\Sigma(%.1f\,\mathrm{kpc};R_0)\ [M_\odot\,\mathrm{pc}^{-2}]$' % options.height
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rhodmrd':
            yrange= [0.2,0.8]
            xrange= [0.,0.02]
            ylabel=r'$R_d / R_0$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'rdvc':
            yrange= [210.,250.]
            xrange= [0.2,0.8]
            xlabel=r'$R_d / R_0$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
        elif options.subtype.lower() == 'zhvc':
            yrange= [210.,250.]
            xrange= [0.0125,0.1]
            xlabel=r'$z_h / R_0$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
        elif options.subtype.lower() == 'dlnvcdlnrvc':
            yrange= [210.,250.]
            xrange= [-0.2,0.07]
            xlabel=r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
            onedhists=True
        elif options.subtype.lower() == 'dlnvcdlnrplhalo':
            yrange= [0.,2.]
            ylabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            xrange= [-0.2,0.07]
            xlabel=r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$'
        elif options.subtype.lower() == 'dlnvcdlnrzh':
            yrange= [0.0125,0.1]
            ylabel=r'$z_h / R_0$'
            xrange= [-0.2,0.07]
            xlabel=r'$\mathrm{d}\ln V_c / \mathrm{d}\ln R\, (R_0)$'
        elif options.subtype.lower() == 'rhodmvc':
            yrange= [210.,250.]
            xrange= [0.,0.02]
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}]$'
            xlabel=r'$\rho_{\mathrm{DM}}(R_0,0)\ [M_\odot\,\mathrm{pc}^{-3}]$'
        elif options.subtype.lower() == 'plhalovc':
            yrange= [210.,250.]
            xrange= [0.,2.]
            xlabel=r'$\alpha\ \mathrm{in}\ \rho_{\mathrm{halo}} \propto 1/r^\alpha$'
            ylabel=r'$V_c\ [\mathrm{km\,s}^{-1}$]'
        bovy_plot.bovy_print(fig_height=3.87,fig_width=5.)
        ax= bovy_plot.bovy_plot(x,y,
                            s=ndata,c=plotc,
                            cmap='jet',
                            xlabel=xlabel,ylabel=ylabel,
                            clabel=zlabel,
                            xrange=xrange,yrange=yrange,
                            vmin=vmin,vmax=vmax,
                            scatter=True,edgecolors='none',
                            colorbar=True-onedhists,
                            onedhists=onedhists,
                            onedhistxnormed=onedhists,
                            onedhistynormed=onedhists,
                            bins=15)
        if onedhists:
            axS, axx, axy= ax
        if options.subtype.lower() == 'dlnvcdlnrvc':
            #Plot prior on one-d axes
            sb= numpy.linspace(-0.2,0.0399,1001)
            fsb= numpy.exp(numpy.log((0.04-sb)/0.04)-(0.04-sb)/0.04)
            fsb/= numpy.sum(fsb)*(sb[1]-sb[0])
            axx.plot(sb,fsb,'-',color='0.65')
            tvc= numpy.linspace(150.,350.,1001)
            fvc= numpy.exp(-(tvc-225.)**2./2./15.**2.)
            fvc/= numpy.sum(fvc)*(tvc[1]-tvc[0])
            axy.plot(fvc,tvc,'-',color='0.65')
    else:
        bovy_plot.bovy_print()
        bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet',
                              interpolation='nearest',
                              xlabel=r'$[\mathrm{Fe/H}]$',
                              ylabel=r'$[\alpha/\mathrm{Fe}]$',
                              zlabel=zlabel,
                              xrange=xrange,yrange=yrange,
                              vmin=vmin,vmax=vmax,
                              contours=False,
                              colorbar=True,shrink=0.78)
        if options.type.lower() == 'q' or options.type.lower() == 'vc' \
                or options.relative or options.type.lower() == 'rd' \
                or options.type.lower() == 'fd' \
                or options.type.lower() == 'fh' \
                or options.type.lower() == 'fb' \
                or options.type.lower() == 'plhalo' \
                or options.type.lower() == 'surfz' \
                or options.type.lower() == 'surfzdisk' \
                or options.type.lower() == 'rhoo' \
                or options.type.lower() == 'qhalo' \
                or options.type.lower() == 'kz':
            bovy_plot.bovy_text(r'$\mathrm{median} = %.2f \pm %.2f$' % (numpy.median(plotthis[numpy.isfinite(plotthis)]),
                                                                        1.4826*numpy.median(numpy.fabs(plotthis[numpy.isfinite(plotthis)]-numpy.median(plotthis[numpy.isfinite(plotthis)])))),
                                bottom_left=True,size=14.)
        if options.type.lower() == 'zh' or options.type.lower() == 'rhodm':
            bovy_plot.bovy_text(r'$\mathrm{median} = %.4f \pm %.4f$' % (numpy.median(plotthis[numpy.isfinite(plotthis)]),
                                                                        1.4826*numpy.median(numpy.fabs(plotthis[numpy.isfinite(plotthis)]-numpy.median(plotthis[numpy.isfinite(plotthis)])))),
                                bottom_left=True,size=14.)
    bovy_plot.bovy_end_print(options.outfilename)
    return None
Example #42
0
 def my_f_z(self, r, ang, *args, **kwargs):
     """Return the force in the z-direction at (r, theta)"""
     z, r_cyl = self.spherical_to_cylindrical(r, ang)
     return evaluatezforces(self.func, r_cyl / self.R0,
                            z / self.R0) * self.force_to_kpckms2
def bulge_dispersion(pot):
    """The expected dispersion in Baade's window, in km/s"""
    bar, baz= 0.0175, 0.068
    return numpy.sqrt(1./pot[0].dens(bar,baz)*integrate.quad(lambda x: -potential.evaluatezforces(bar,x,pot)*pot[0].dens(bar,x),baz,numpy.inf)[0])*_REFV0
Example #44
0
def plotSurfRdfh(plotfilename):
    #Calculate the surface density profile for each trial potential, then plot in 2D
    if '.png' in plotfilename:
        savefilename= plotfilename.replace('.png','.sav')
    elif '.ps' in plotfilename:
        savefilename= plotfilename.replace('.ps','.sav')
    if not os.path.exists(savefilename):
        options= setup_options(None)
        options.potential= 'dpdiskplhalofixbulgeflatwgasalt'
        options.fitdvt= False
        rs= numpy.array([5.,8.,11.])
        rds= numpy.linspace(2.,3.4,_NRDS)
        fhs= numpy.linspace(0.,1.,_NFHS)
        surfz= numpy.zeros((len(rs),len(rds),len(fhs)))+numpy.nan
        ro= 1.
        vo= _VC/ _REFV0
        dlnvcdlnr= _DLNVCDLNR
        zh= _ZH
        for jj in range(len(rds)):
            for kk in range(len(fhs)):
                #Setup potential to calculate stuff
                potparams= numpy.array([numpy.log(rds[jj]/8.),vo,numpy.log(zh/8000.),fhs[kk],dlnvcdlnr])
                try:
                    pot= setup_potential(potparams,options,0,returnrawpot=True)
                except RuntimeError:
                    continue
                for ii in range(len(rs)):
                    if False:
                        surfz[ii,jj,kk]= -potential.evaluatezforces(rs[ii]/_REFR0,options.height/_REFR0/ro,pot)*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro/2./numpy.pi
                    else:
                        surfz[ii,jj,kk]= 2.*integrate.quad((lambda zz: potential.evaluateDensities(rs[ii]/8.,zz,pot)),0.,options.height/_REFR0/ro)[0]*_REFV0**2.*vo**2./_REFR0**2./ro**2./4.302*_REFR0*ro
        #Save
        save_pickles(savefilename,rs,rds,fhs,surfz)
    else:
        savefile= open(savefilename,'rb')
        rs= pickle.load(savefile)
        rds= pickle.load(savefile)
        fhs= pickle.load(savefile)
        surfz= pickle.load(savefile)
        savefile.close()
    #Now plot
    bovy_plot.bovy_print()
    data = numpy.ma.masked_invalid(surfz[1,:,:])
    bovy_plot.bovy_dens2d(data.filled(data.mean()).T,
                          origin='lower',
                          cmap='jet',
                          colorbar=True,
                          shrink=0.775,
                          xlabel=r'$\mathrm{disk\ scale\ length}\,(\mathrm{kpc})$',
                          ylabel=r'$\mathrm{relative\ halo\ contribution\ to}\ V^2_c(R_0)$',
                          zlabel=r'$\Sigma(R_0,|Z| \leq 1.1\,\mathrm{kpc})\, (M_\odot\,\mathrm{pc}^{-2})$',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.])
    #Fix bad data
    bad_data = numpy.ma.masked_where(~data.mask, data.mask)
    bovy_plot.bovy_dens2d(bad_data.T,
                          origin='lower',
                          interpolation='nearest',
                          cmap=cm.gray_r,
                          overplot=True,
                          
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.])
    #Overlay contours of sigma at other R
    bovy_plot.bovy_dens2d(surfz[0,:,:].T,origin='lower',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.],
                          overplot=True,
                          justcontours=True,
                          contours=True,
                          cntrcolors='k',
                          cntrls='-')
    bovy_plot.bovy_dens2d(surfz[2,:,:].T,origin='lower',
                          xrange=[rds[0]-(rds[1]-rds[0])/2.,
                                  rds[-1]+(rds[1]-rds[0])/2.],
                          yrange=[fhs[0]-(fhs[1]-fhs[0])/2.,
                                  fhs[-1]+(fhs[1]-fhs[0])/2.],
                          overplot=True,
                          justcontours=True,
                          contours=True,
                          cntrcolors='w',
#                          cntrlabel=True,
                          cntrls='--')
    #Add labels
    bovy_plot.bovy_text(r'$\Sigma(R=5\,\mathrm{kpc})$'
                        +'\n'
                        +r'$\Sigma(R=11\,\mathrm{kpc})$',
                        bottom_left=True,size=14.)
    bovy_plot.bovy_plot([2.575,2.8],[0.15,0.31],'-',color='0.5',overplot=True)
    bovy_plot.bovy_plot([2.625,2.95],[0.06,0.1525],'-',color='0.5',overplot=True)
    #overplot actual gridpoints
    gridrds= numpy.linspace(2.,3.4,8)
    gridfhs= numpy.linspace(0.,1.,16)
    for ii in range(len(gridrds)):
        bovy_plot.bovy_plot(gridrds[ii]+numpy.zeros(len(gridfhs)),
                            gridfhs,
                            's',
                            color='w',ms=3.,overplot=True,
                            markeredgecolor='none')
    bovy_plot.bovy_end_print(plotfilename)
    return None