def Rho_crit(self, cosmo=None): if not cosmo: cosmo = self.cosmo G2 = G.to(u.Mpc / u.Msun * u.km**2 / u.second**2) rc = 3 * cosmo.H0**2 / (8 * np.pi * G2) rc = rc.to(u.Msun / u.pc**2 / u.Mpc) # unit of Msun/pc^2/mpc return rc
def __init__(self, rc, Mtot, G='kpc km2 / (M_sun s2)'): """ Analytic Plummer model :param rc: Plummer scale length :param Mtot: Plummer total mass :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :return: """ self.rc = rc self.Mmax = Mtot if isinstance(G, float) or isinstance(G, int): self.G = G else: GG = conG.to(G) self.G = GG.value self._use_nparray = True self._analytic_radius = True self.use_c = False self._densnorm = (3 * Mtot) / (4 * np.pi * rc * rc * rc) self._potnorm = self.G * Mtot
def __init__(self,rc,Mtot,G='kpc km2 / (M_sun s2)'): """ Analytic Plummer model :param rc: Plummer scale length :param Mtot: Plummer total mass :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :return: """ self.rc=rc self.Mmax=Mtot if isinstance(G,float) or isinstance(G,int): self.G=G else: GG=conG.to(G) self.G=GG.value self._use_nparray=True self._analytic_radius=True self.use_c=False self._densnorm=(3*Mtot)/(4*np.pi*rc*rc*rc) self._sdensnorm=Mtot/(np.pi*rc*rc) self._potnorm=self.G*Mtot
def __init__(self,rc, G='kpc km2 / (M_sun s2)', Mmax=None, rmax=None, Vinf=None, d0=None): """ PseudoIsothermal Model: d=d0/((1+r^2/rc^2) Given that the Mass diverge at infinty it is possibile to initialize the model in different ways: Mmax (rmax): The model will have a mass of Mmax at radius rmax, if rmax is not supplied it is equal to 10*rc d0: Central density. The unity depends on the combinations of gthe value of G and rc. By default is Msun/kpc^3. Vinf: asymptotic circular velocity in km/s. The routine gives priority firstly to Mmax, then to d0 and finally to Vinf. :param rc: :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :param Mmax: Total Mass in Msun at radius rmax. :param rmax: Radius to cut the density distribution, by default is equal to 10*rc. :param d0: Central density. The unity depends on the combinations of gthe value of G and rc. By default is Msun/kpc^3. Available only if Mmax is None. :param Vinf: asymptotic circular velocity in km/s. Available only if Mmax and d0 are None. :return: """ if rmax is None: self.rmax=10*rc else: self.rmax=rmax self.rc=rc self.use_c=False self._use_nparray=True if isinstance(G,float) or isinstance(G,int): self.G=G else: GG=conG.to(G) self.G=GG.value self.Mc=1 self.dc=1 self.pc=1 if Mmax is not None: totmass=self._evaluatemass(self.rmax) self.Mc=Mmax/totmass self.dc=self.Mc/(4*np.pi) self.pc=self.G*self.Mc elif d0 is not None: self.dc=d0 self.Mc=(4*np.pi)*self.dc self.pc=self.G*self.Mc elif Vinf is not None: self.pc=(Vinf*Vinf)/(self.rc*self.rc) self.Mc=self.pc/self.G self.dc=self.Mc/(4*np.pi)
def __init__(self, zs_bins=None, zg_bins=None, logger=None, l=None): self.logger = logger self.l = l #Gravitaional const to get Rho crit in right units self.G2 = G.to(u.Mpc / u.Msun * u.km**2 / u.second**2) self.G2 *= 8 * np.pi / 3. self.zs_bins = zs_bins self.zg_bins = zg_bins self.SN = {} if zs_bins is not None: #sometimes we call this class just to access some of the functions self.set_zbins(z_bins=zs_bins, tracer='shear') if zg_bins is not None: #sometimes we call this class just to access some of the functions self.set_zbins(z_bins=zg_bins, tracer='galaxy')
def attract(self, other): dx = self.x - other.x dy = self.y - other.y theta = math.atan2(dy, dx) distance = math.hypot(dx, dy) # calculate attractive force due to gravity using Newton's law of universal gravitation: # F = G * m1 * m2 / r^2 # for consistency, G = [AU^3 * kg^-1 * d^-2] force = G.to('AU3 / (kg d2)').value * self.mass * other.mass / ( distance**2) # accelerate both bodies towards each other by acceleration vector a = F/m, rearranged from Newton's second law self.accelerate((force / self.mass, theta - (math.pi / 2))) other.accelerate((force / other.mass, theta + (math.pi / 2)))
def _calculate_gravitational_acceleration(self): # direction and strength of force # F = Gm/r^2 acceleration = [] for body in self.current_ephem: r_vector = body[1].rv()[0] - self.spaceship.rv[0] r_magnitude = np.linalg.norm(r_vector) a_magnitude = (G.to("km3/kg s2") * body[0].mass) / (r_magnitude**2) a_vector = a_magnitude * r_vector / r_magnitude acceleration.append(a_vector) total_acceleration = 0 for a in acceleration: total_acceleration += a return total_acceleration
def compute_rotation_curve(self, arr): """ Compute the rotation curve. """ # Compute distance to centre. r = np.linalg.norm(arr['coords'] - self.centre, axis=1) mask = np.argsort(r) r = r[mask] # Compute cumulative mass. cmass = np.cumsum(arr['mass'][mask]) # Compute velocity. myG = G.to(u.km**2 * u.Mpc * u.Msun**-1 * u.s**-2).value v = np.sqrt((myG * cmass) / r) # Return r in Mpc and v in km/s. return r, v
def __init__(self,dprof,sprof,mprof,amodel='isotropic',G='kpc km2 / (M_sun s2)'): self.amodel=amodel self.dprof=dprof self.sprof=sprof self.mprof=mprof if isinstance(G,float) or isinstance(G,int): self.G=G else: GG=conG.to(G) self.G=GG.value if amodel=='isotropic': self.kernel=self._kerneliso self.cost=sqrt(2.*self.G)
def __init__(self, table,span, ts): global au data = table self.g = G.to(((u.km)**3)/(u.kg*((u.day)**2))).value self.bodies = data['body'] self.span = float(span) self.t = float(ts*u.hour.to(u.day)) self.timestep = int(self.span/self.t) self.masses = [0.0 for i in range(len(self.bodies))] self.pos = [origin for i in range(len(self.bodies))] self.vel = [origin for i in range(len(self.bodies))] #self.pos_err = [origin for i in range(len(self.bodies))] self.barycenter = origin self.tot_mass = 0.0 self.tab = [Table(names=['body', 'cycle', 'time', 'x', 'y', 'z', 'vx',\ 'vy', 'vz'], dtype=['S16', 'i8', 'f16', 'f16', 'f16', 'f16', 'f16',\ 'f16', 'f16']) for i in range(len(self.bodies))] for i in range(len(self.bodies)): self.masses[i] = data['mass'][i] self.pos[i] = vector(data['x'][i], data['y'][i], data['z'][i]) #self.pos_err[i] = vector(data['ex'][i], data['ey'][i], data['ez'][i]) self.vel[i] = vector(data['vx'][i], data['vy'][i], data['vz'][i]) self.barycenter = self.barycenter + (self.pos[i])*(self.masses[i]) self.tot_mass = self.tot_mass + self.masses[i] self.barycenter = self.barycenter*(1/self.tot_mass) for i in range(len(self.bodies)): self.tab[i].add_row([self.bodies[i], 0, 0, self.pos[i].x,\ self.pos[i].y, self.pos[i].z, self.vel[i].x, self.vel[i].y,\ self.vel[i].z])
def tdyn(self,mq=100,type=None,G='(kpc3)/(M_sun Gyr2)'): """ Calculate the dynamical time of a stystem as Tdyn=0.5*pi*Sqrt(Rh^3/(G*Mh)). where Rh is the radius that contains the fraction Mh=h*M of the mass. This is the time for a particle at distance r to reach r=0 in a homogeneus spherical system with density rho. We do not have an homogenues sphere, but we use a medium value rho_mh equals to Mh/(4/3 * pi * Rh^3). :param mq: Fraction of the mass to use, it can ranges from 0 to 100 :param type: Type of particle to use, it need to be an array. If None use all :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :return: Dynamical tyme. The units wil depends on the units used in G, If used the G in default the time will be in unit of Gyr. """ if type is None: rad_array=self.p.Radius[:] mas_array=self.p.Mass[:] else: type= nparray_check(type) rad_array=self._make_array(self.p.Radius,type) mas_array=self._make_array(self.p.Mass,type) if isinstance(G,float) or isinstance(G,int): G=G else: GG=conG.to(G) G=GG.value rq,_=self.qradius_ext(rad_array,mas_array,mq) mass_phy=G*(mq/100)*np.sum(mas_array) tdyn=0.5*np.pi*rq*np.sqrt(rq/mass_phy) return tdyn
def __init__(self,m,rc,Mtot,G='kpc km2 / (M_sun s2)'): """ Analytic Sersic model: Surface density: S(R)=S(0) * Exp(-(R/rc)^(1/m)) for the 3D deprojection we use the analytic approximation of Lima Neto, Gerbal and Marquez, 1999. Density: d(r)=d(0) * Exp(-(r/rc)^(1/m)) * (r/rc)^(-p) where p=1 - 0.6097*(1/m) + 0.05463*(1/m^2) :param m: Sersic exponent :param rc: Sersic scale length :param Mtot: Sersic total mass :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :return: """ self.rc=rc self.Mmax=Mtot self.m=m self.nu=1/m self.p=1-0.6097*self.nu+0.05463*self.nu*self.nu self.use_c=False self._use_nparray=True self._analytic_radius=True if isinstance(G,float) or isinstance(G,int): self.G=G else: GG=conG.to(G) self.G=GG.value dmgamma= self.m*gamma(self.m*(3-self.p)) #Mtot=4*pi*d0*rc^3 * m* *Gamma(m*(3-p)) self._densnorm=Mtot/(4*np.pi*rc*rc*rc*dmgamma) sdmgamma= self.m*gamma(2*self.m) #Mtot=2*pi*S0*rc^2 * m * Gamma(2*m) self._sdensnorm=Mtot/(2*np.pi*rc*rc*sdmgamma) self._potnorm=(self.G*Mtot)
def tdyn(self, mq=100, type=None, G='(kpc3)/(M_sun s2)'): """ Calculate the dynamical time of a stystem as Tdyn=0.5*pi*Sqrt(Rh^3/(G*Mh)). where Rh is the radius that contains the fraction Mh=h*M of the mass. This is the time for a particle at distance r to reach r=0 in a homogeneus spherical system with density rho. We do not have an homogenues sphere, but we use a medium value rho_mh equals to Mh/(4/3 * pi * Rh^3). :param mq: Fraction of the mass to use, it can ranges from 0 to 100 :param type: Type of particle to use, it need to be an array. If None use all :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :return: Dynamical tyme. The units wil depends on the units used in G, If used the G in default the time will be in unit of Gyr. """ if type is None: rad_array = self.p.Radius[:] mas_array = self.p.Mass[:] else: type = nparray_check(type) rad_array = self._make_array(self.p.Radius, type) mas_array = self._make_array(self.p.Mass, type) if isinstance(G, float) or isinstance(G, int): G = G else: GG = conG.to(G) G = GG.value rq, _ = self.qradius_ext(rad_array, mas_array, mq) mass_phy = G * (mq / 100) * np.sum(mas_array) tdyn = 0.5 * np.pi * rq * np.sqrt(rq / mass_phy) return tdyn
def __init__(self, galaxy, snap): # construct filename ilbl = '000' + str(snap) # add string of filenumber to 000 ilbl = ilbl[-3:] # keep last 3 digits self.filename = '/home/agibbs/' + "%s_" % (galaxy) + ilbl + '.txt' # set delta for all com calculations self.comdel = 0.3 # too small a value may fail to converge and can result in an ERROR!!! # set G to correct units self.G = G.to(u.kpc * u.km**2 / u.s**2 / u.Msun) # store galaxy name (used to separate out M33 later) self.gname = galaxy # read in the file and particle type self.time, self.total, self.data = Read(self.filename) # store the mass, positions of all particle types self.m = self.data['m'] self.x = self.data['x'] * u.kpc self.y = self.data['y'] * u.kpc self.z = self.data['z'] * u.kpc
def external_delta_sigma(galaxies, particles, rp_bins, period, projection_period, cosmology=default_cosmology): r""" Parameters ---------- galaxies : array_like Ngal x 2 numpy array containing 2-d positions of galaxies. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. particles : array_like Npart x 2 numpy array containing 2-d positions of particles. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. Assumes constant particle masses, but can use weighted pair counts as scipy 0.19.0 is released. scipy.spatial.cKDTree will acquire a weighted pair count functionality rp_bins : array_like array of projected radial boundaries defining the bins in which the result is calculated. The minimum of rp_bins must be > 0.0. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. period : array_like Length-2 sequence defining the periodic boundary conditions in each dimension. If you instead provide a single scalar, Lbox, period is assumed to be the same in all Cartesian directions. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. projection_period : float The period along the direction of projection cosmology : instance of `astropy.cosmology`, optional Default value is set in `~halotools.sim_manager.default_cosmology` module. Typically you should use the `cosmology` attribute of the halo catalog you used to populate mock galaxies. Returns ------- rmids : np.array The bins at which :math:`\Delta\Sigma` is calculated. The units of `rmids` is :math:`hinv Mpc`, where distances are in comoving units. You can convert to physical units using the input cosmology and redshift. Note that little h = 1 here and throughout Halotools. Delta_Sigma : np.array :math:`\Delta\Sigma(r_p)` calculated at projected comoving radial distances ``rp_bins``. The units of `ds` are :math:`h * M_{\odot} / Mpc^2`, where distances are in comoving units. You can convert to physical units using the input cosmology and redshift. Note that little h = 1 here and throughout Halotools. Notes ----- :math:`\Delta\Sigma` is calculated by first calculating the projected surface density :math:`\Sigma` using the particles passed to the code and then, .. math:: \Delta\Sigma(r_p) = \bar{\Sigma}(<r_p) - \Sigma(r_p) """ from scipy.spatial import cKDTree from astropy.constants import G Ngal = float(galaxies.shape[0]) Npart = float(particles.shape[0]) if np.isscalar(period): Area = period**2 else: Area = period[0] * period[1] tree = cKDTree(galaxies, boxsize=period) ptree = cKDTree(particles, boxsize=period) pairs_inside_rad = tree.count_neighbors(ptree, rp_bins) pairs_in_annuli = np.diff(pairs_inside_rad) # rhobar = 3H0^2/(8 pi G) Om0 rhobar = 3.e4 / (8 * np.pi * G.to('km^2 Mpc/(s^2 Msun)').value) * cosmology.Om0 sigmabar = rhobar * projection_period # This initializes sigma(rmids) rmids = rp_bins[1:] / 2 + rp_bins[:-1] / 2 xi2d = pairs_in_annuli / (Ngal * Npart / Area * (np.pi * (rp_bins[1:]**2 - rp_bins[:-1]**2))) - 1.0 sigma = sigmabar * xi2d # Now initialize sigmainside(rp_bins) xi2dinside = pairs_inside_rad / (Npart * Ngal / Area * (np.pi * rp_bins**2)) - 1.0 sigmainside = sigmabar * xi2dinside from scipy.interpolate import interp1d spl = interp1d(np.log(rp_bins), np.log(sigmainside), kind="cubic") return rmids, np.exp(spl(np.log(rmids))) - sigma
import numpy as np from astropy.constants import G from NFW import normalizedNFWMass c = 299792.0 # Km/s G = G.to("Mpc Msun^-1 km^2 s^-2").value # G Newton in Mpc/Msun x (km/s)^2 def randomSpherePoint(n=1, theta_max=np.pi, phi_max=2.0 * np.pi): ''' Returns random distributes theta (0,pi) and phi (0, 2pi) ''' u = 1.0 - np.random.rand(n) * theta_max / np.pi v = np.random.rand(n) return np.arccos(2 * u - 1), phi_max * v def getDeltaZ(x, y, z, vx, vy, vz): ''' Returns the redshift due to Pec. Vel. x, y, z: Cartesian coordinates [Not Spec. Units] vx, vy, vz: Cartesian velocities [It must be in km/s] ''' return (x * vx + y * vy + z * vz) / np.sqrt(x * x + y * y + z * z) / c def circularVelocity(cx, r): ''' Returns the circular velocity at r=R/Rx divided by np.sqrt(MDelta/RDelta)
def __init__(self,R,dens,rc=1,Mmax=1, G='kpc km2 / (M_sun s2)', denorm=True, use_c=False): """ The purpose of the general model is to start from a density law R-dens to build a galaxy model. Attenzione per come è creato il modello assume sempre che per R>rmax la densita sia 0, la massa resti costante al suo valore massimo e il potenziale vada come M/r. Per modelli che raggiungono la massa massima all infinito questo potrebbe essere un problema, quindi si dovrebbero usare modelli con massa finita o troncarli e campionarli fino a quanto la massa non raggiunge il suo valore max. Per modelli non troncati è meglio utilizzare modelli analitici se possibile. Anche nel calcolo del potenziale Rinf è settato uguale all ultimo punto di R, poichè cmq per R>Rmax dens=0 e l integrale int_Rmax^inf dens r dr=0 sempre. :param R: list of radii, it needs to be in the form r/rc :param dens: list of dens at radii R. It can be also a function or a lambda function that depends only on the variable R=r/rc :param rc: Scale length of the model, the R in input will be multiplyed by rc before start all the calculation :param Mmax: Physical Value of the Mass at Rmax (the last point of the R grid). The physical unity of dens and pot and mass will depends on the unity of Mmax :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :param denorm: If True, the output value of mass, dens and pot will be de normalized using Mmax and G. :param use_c: To calculate pot and mass with a C-cyle, WARNING it creates more noisy results """ self.rc=rc self.Mmax=Mmax if isinstance(G,float) or isinstance(G,int): self.G=G else: GG=conG.to(G) self.G=GG.value if isinstance(dens,list) or isinstance(dens,tuple) or isinstance(dens,np.ndarray): self.dens_arr=np.array(dens,dtype=float,order='C') else: self.dens_arr=dens(R) self.R=np.array(R,dtype=float,order='C')*self.rc self.mass_arr=np.empty_like(self.dens_arr,dtype=float,order='C') self.pot_arr=np.empty_like(self.dens_arr,dtype=float,order='C') self.use_c=use_c self._use_nparray=False self._dens=UnivariateSpline(self.R,self.dens_arr, k=1, s=0, ext=1) #for R>rmax, dens=0 if self.use_c==True: #add to path to use relative path dll_name='model_c_ext/GeneralModel.so' dllabspath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + dll_name lib = ct.CDLL(dllabspath) #add to path to use relativ path mass_func=lib.evalmass mass_func.restype=None mass_func.argtypes=[ndpointer(ct.c_double, flags="C_CONTIGUOUS"), ndpointer(ct.c_double, flags="C_CONTIGUOUS"),ct.c_int,ndpointer(ct.c_double, flags="C_CONTIGUOUS")] mass_func(self.R,self.dens_arr,len(self.dens_arr),self.mass_arr) self._mass_int=UnivariateSpline(self.R,self.mass_arr, k=1, s=0, ext=3) #ext=3, const for R>Rmax non ci osno piu particelle e la massa rimane uguale pot_func=lib.evalpot pot_func.restype=None pot_func.argtypes=[ndpointer(ct.c_double, flags="C_CONTIGUOUS"),ndpointer(ct.c_double, flags="C_CONTIGUOUS"),ndpointer(ct.c_double, flags="C_CONTIGUOUS"),ct.c_int,ndpointer(ct.c_double, flags="C_CONTIGUOUS")] pot_func(self.R,self.dens_arr,self.mass_arr,len(self.dens_arr),self.pot_arr) self._pot_int=UnivariateSpline(self.R,self.pot_arr, k=1, s=0, ext=1) else: self._dm2=UnivariateSpline(self.R,self.R*self.R*self.dens_arr, k=2, s=0,ext=1) self._dm=UnivariateSpline(self.R,self.R*self.dens_arr, k=1, s=0,ext=1) #Evaluate mass and pot on the R grid in input #mass func=np.vectorize(self._dm2.integral) self.mass_arr=func(0,self.R) #pot a=(1/self.R)*self.mass_arr func=np.vectorize(self._dm.integral) b=func(self.R,self.R[-1]) self.pot_arr=a+b if denorm==True: self._set_denorm(self.Mmax) else: self.Mc=1 self.dc=1 self.pc=1
height = prof_stars_mass.x.to('kpc') accum_mass = prof_stars_mass['stars', 'particle_mass'].to('Msun') # Making the arrays dimensionless npheight = np.array(height) npaccum = np.array(accum_mass) # Fitting the mass profiles m_init = sech_sq_model(amp = np.max(npaccum), z_prime = npheight[np.argmax(npaccum)], z_0 = 1.) fit = LevMarLSQFitter() m = fit(m_init, npheight, npaccum) h_z[int(shell)] = m.z_0.value # Calculating sigma from eqn 1 in the proposal; differentiating by stars, stars and gas, and complete dynamical mass const = args.const G_conv = G.to('km3/(kg s2)') z_0 = (m.z_0 * u.kpc).to('km') outer_conv = (outer_rad * u.kpc).to('km') inner_conv = (inner_rad * u.kpc).to('km') proj_area = np.pi * (outer_conv**2 - inner_conv**2) sigma_dyn = ((mass_quant * u.Msun).to('kg') + (gas_quant * u.Msun).to('kg') + (dm_quant * u.Msun).to('kg')) / (proj_area) mass_dens = (mass_quant * u.Msun).to('kg') / (proj_area) smd_mass[int(shell)] = mass_dens.value mass_gas = ((mass_quant * u.Msun).to('kg') + (gas_quant * u.Msun).to('kg')) / (proj_area) smd_mg[int(shell)] = mass_gas.value sigma_mass_calc = np.sqrt(const*np.pi*G_conv*z_0*mass_dens) sigma_mg_calc = np.sqrt(const*np.pi*G_conv*z_0*mass_gas) sigma_dyn_calc = np.sqrt(const*np.pi*G_conv*z_0*sigma_dyn) sigma_mass[int(shell)] = sigma_mass_calc.value sigma_mg[int(shell)] = sigma_mg_calc.value sigma_all[int(shell)] = sigma_dyn_calc.value
import getetide reload(getetide) import numpy as np from scipy.interpolate import interp1d,spline from scipy.misc import derivative from scipy.integrate import quad from scipy.optimize import minimize from astropy import units from astropy.constants import G from astropy.convolution import convolve, Box1DKernel import datetime import matplotlib.pyplot as plt import potdenfunc reload(potdenfunc) import profileclass GN=(G.to(units.kpc**3/units.s**2/units.M_sun)).value def chi2(params,rhoint,massint,r): rhor=lambda params,r: potdenfunc.zhaorho(r,10**params[0],10**params[1],params[2],params[3],params[4]) w=np.where(rhoint(r)>100)[0] mtot=lambda params: profileclass.getmassfromzhao0(params[2],params[3],params[4],10**params[0],10**params[1],r[w[-1]]) chi2=0 npts=0 d2=(np.log10(rhor(params,r[w]))-np.log10(rhoint(r[w])))**2+(np.log10(mtot(params))-np.log10(massint))**2 if np.any(~np.isfinite(d2)): return np.inf
z_high = float(sys.argv[5]) z_nbins = int(sys.argv[6]) fn_out = sys.argv[7] # Read in n(z) data = np.loadtxt(fn_nz) z_sources = data[:, 0] n_z = data[:, 1] delta_z_sources = data[1, 0] - data[0, 0] # Create cosmology cosmo = FlatLambdaCDM(H0=H0, Om0=Omm) # Get constants c_conv = c.to('Mpc/s') #speed-of-light in Mpc/c G_conv = G.to('Mpc3/(Msun s2)') # Create lens redshift bins z_bins = np.linspace(z_low, z_high, z_nbins) sig_crit = np.zeros(z_nbins) # Calculate SigCrit for i, z_l in enumerate(z_bins): for j, z_s in enumerate(z_sources): if (z_s > z_l): sig_crit[i] += delta_z_sources * n_z[j] * sigma_crit_inv( cosmo, z_l, z_s).value # Inverting sig_crit = 1 / sig_crit # Prefactor for Sigma_crit [Msun/Mpc]
# Project Piece 1 # Velocity dispersion # William Lake # import modules import numpy as np import astropy.units as u from ReadFile import Read from CenterOfMass2 import CenterOfMass import math import matplotlib.pyplot as plt plt.ioff() from astropy.constants import G G = G.to(u.kpc * u.km**2 / u.s**2 / u.Msun) # Converts the gravitational constant to our desired units # In[44]: class VelocityDispersion: '''This class aids in finding the velocity dispersions of bulge particles over radius. It will eventually do the same over time, held at constant radius''' def __init__(self, galaxy, snap): # This function/class takes the galaxy name and snapshot number as inputs # The following three lines create the part of the filename that describe the Snap number, and then generate the filename ilbl = '000' + str(snap) ilbl = ilbl[-3:] self.filename = "HighRes/%s_" % (galaxy) + ilbl + '.txt' time, total, data = Read(self.filename) # Read the data
def external_delta_sigma(galaxies, particles, rp_bins, period, projection_period, cosmology=default_cosmology): r""" Parameters ---------- galaxies : array_like Ngal x 2 numpy array containing 2-d positions of galaxies. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. particles : array_like Npart x 2 numpy array containing 2-d positions of particles. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. Assumes constant particle masses, but can use weighted pair counts as scipy 0.19.0 is released. scipy.spatial.cKDTree will acquire a weighted pair count functionality rp_bins : array_like array of projected radial boundaries defining the bins in which the result is calculated. The minimum of rp_bins must be > 0.0. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. period : array_like Length-2 sequence defining the periodic boundary conditions in each dimension. If you instead provide a single scalar, Lbox, period is assumed to be the same in all Cartesian directions. Length units are comoving and assumed to be in Mpc/h, here and throughout Halotools. projection_period : float The period along the direction of projection cosmology : instance of `astropy.cosmology`, optional Default value is set in `~halotools.sim_manager.default_cosmology` module. Typically you should use the `cosmology` attribute of the halo catalog you used to populate mock galaxies. Returns ------- rmids : np.array The bins at which :math:`\Delta\Sigma` is calculated. The units of `rmids` is :math:`hinv Mpc`, where distances are in comoving units. You can convert to physical units using the input cosmology and redshift. Note that little h = 1 here and throughout Halotools. Delta_Sigma : np.array :math:`\Delta\Sigma(r_p)` calculated at projected comoving radial distances ``rp_bins``. The units of `ds` are :math:`h * M_{\odot} / Mpc^2`, where distances are in comoving units. You can convert to physical units using the input cosmology and redshift. Note that little h = 1 here and throughout Halotools. Notes ----- :math:`\Delta\Sigma` is calculated by first calculating the projected surface density :math:`\Sigma` using the particles passed to the code and then, .. math:: \Delta\Sigma(r_p) = \bar{\Sigma}(<r_p) - \Sigma(r_p) """ from scipy.spatial import cKDTree from astropy.constants import G Ngal = float(galaxies.shape[0]) Npart = float(particles.shape[0]) if np.isscalar(period): Area = period**2 else: Area = period[0] * period[1] tree = cKDTree(galaxies, boxsize=period) ptree = cKDTree(particles, boxsize=period) pairs_inside_rad = tree.count_neighbors(ptree, rp_bins) pairs_in_annuli = np.diff(pairs_inside_rad) # rhobar = 3H0^2/(8 pi G) Om0 rhobar = 3.e4/(8*np.pi*G.to('km^2 Mpc/(s^2 Msun)').value)*cosmology.Om0 sigmabar = rhobar*projection_period # This initializes sigma(rmids) rmids = rp_bins[1:]/2+rp_bins[:-1]/2 xi2d = pairs_in_annuli/(Ngal*Npart/Area*(np.pi*(rp_bins[1:]**2-rp_bins[:-1]**2))) - 1.0 sigma = sigmabar*xi2d # Now initialize sigmainside(rp_bins) xi2dinside = pairs_inside_rad/(Npart*Ngal/Area*(np.pi*rp_bins**2)) - 1.0 sigmainside = sigmabar*xi2dinside from scipy.interpolate import interp1d spl = interp1d(np.log(rp_bins), np.log(sigmainside), kind="cubic") return rmids, np.exp(spl(np.log(rmids)))-sigma
def __init__(self, R, dens, rc=1, Mmax=1, G='kpc km2 / (M_sun s2)', denorm=True, use_c=False): """ The purpose of the general model is to start from a density law R-dens to build a galaxy model. Attenzione per come è creato il modello assume sempre che per R>rmax la densita sia 0, la massa resti costante al suo valore massimo e il potenziale vada come M/r. Per modelli che raggiungono la massa massima all infinito questo potrebbe essere un problema, quindi si dovrebbero usare modelli con massa finita o troncarli e campionarli fino a quanto la massa non raggiunge il suo valore max. Per modelli non troncati è meglio utilizzare modelli analitici se possibile. Anche nel calcolo del potenziale Rinf è settato uguale all ultimo punto di R, poichè cmq per R>Rmax dens=0 e l integrale int_Rmax^inf dens r dr=0 sempre. :param R: list of radii, it needs to be in the form r/rc :param dens: list of dens at radii R. It can be also a function or a lambda function that depends only on the variable R=r/rc :param rc: Scale length of the model, the R in input will be multiplyed by rc before start all the calculation :param Mmax: Physical Value of the Mass at Rmax (the last point of the R grid). The physical unity of dens and pot and mass will depends on the unity of Mmax :param G: Value of the gravitational constant G, it can be a number of a string. If G=1, the physical value of the potential will be Phi/G. If string it must follow the rule of the unity of the module.astropy constants. E.g. to have G in unit of kpc3/Msun s2, the input string is 'kpc3 / (M_sun s2)' See http://astrofrog-debug.readthedocs.org/en/latest/constants/ :param denorm: If True, the output value of mass, dens and pot will be de normalized using Mmax and G. :param use_c: To calculate pot and mass with a C-cyle, WARNING it creates more noisy results """ self.rc = rc self.Mmax = Mmax if isinstance(G, float) or isinstance(G, int): self.G = G else: GG = conG.to(G) self.G = GG.value if isinstance(dens, list) or isinstance(dens, tuple) or isinstance( dens, np.ndarray): self.dens_arr = np.array(dens, dtype=float, order='C') else: self.dens_arr = dens(R) self.R = np.array(R, dtype=float, order='C') * self.rc self.mass_arr = np.empty_like(self.dens_arr, dtype=float, order='C') self.pot_arr = np.empty_like(self.dens_arr, dtype=float, order='C') self.use_c = use_c self._use_nparray = False self._dens = UnivariateSpline(self.R, self.dens_arr, k=1, s=0, ext=1) #for R>rmax, dens=0 if self.use_c == True: #add to path to use relative path dll_name = 'model_c_ext/GeneralModel.so' dllabspath = os.path.dirname( os.path.abspath(__file__)) + os.path.sep + dll_name lib = ct.CDLL(dllabspath) #add to path to use relativ path mass_func = lib.evalmass mass_func.restype = None mass_func.argtypes = [ ndpointer(ct.c_double, flags="C_CONTIGUOUS"), ndpointer(ct.c_double, flags="C_CONTIGUOUS"), ct.c_int, ndpointer(ct.c_double, flags="C_CONTIGUOUS") ] mass_func(self.R, self.dens_arr, len(self.dens_arr), self.mass_arr) self._mass_int = UnivariateSpline( self.R, self.mass_arr, k=1, s=0, ext=3 ) #ext=3, const for R>Rmax non ci osno piu particelle e la massa rimane uguale pot_func = lib.evalpot pot_func.restype = None pot_func.argtypes = [ ndpointer(ct.c_double, flags="C_CONTIGUOUS"), ndpointer(ct.c_double, flags="C_CONTIGUOUS"), ndpointer(ct.c_double, flags="C_CONTIGUOUS"), ct.c_int, ndpointer(ct.c_double, flags="C_CONTIGUOUS") ] pot_func(self.R, self.dens_arr, self.mass_arr, len(self.dens_arr), self.pot_arr) self._pot_int = UnivariateSpline(self.R, self.pot_arr, k=1, s=0, ext=1) else: self._dm2 = UnivariateSpline(self.R, self.R * self.R * self.dens_arr, k=2, s=0, ext=1) self._dm = UnivariateSpline(self.R, self.R * self.dens_arr, k=1, s=0, ext=1) #Evaluate mass and pot on the R grid in input #mass func = np.vectorize(self._dm2.integral) self.mass_arr = func(0, self.R) #pot a = (1 / self.R) * self.mass_arr func = np.vectorize(self._dm.integral) b = func(self.R, self.R[-1]) self.pot_arr = a + b if denorm == True: self._set_denorm(self.Mmax) else: self.Mc = 1 self.dc = 1 self.pc = 1
package developed by Benedikt Diemer, http://bdiemer.bitbucket.org. Testing for this module is done in the `~halotools.empirical_models.test_profile_helpers` module. """ from __future__ import division, print_function, absolute_import, unicode_literals import numpy as np from astropy import cosmology as astropy_cosmology_obj from astropy import units as u from astropy.constants import G from ....custom_exceptions import HalotoolsError newtonG = G.to(u.km*u.km*u.Mpc/(u.Msun*u.s*u.s)) __all__ = ('density_threshold', 'delta_vir', 'halo_mass_to_halo_radius', 'halo_radius_to_halo_mass', 'halo_mass_to_virial_velocity') __author__ = ['Benedikt Diemer', 'Andrew Hearin'] def density_threshold(cosmology, redshift, mdef): """ The threshold density for a given spherical-overdensity mass definition. :math:`\\rho_{\\rm thresh}(z) = \\Delta_{\\rm ref}(z)\\rho_{\\rm ref}(z)`. See :ref:`halo_mass_definitions` for details.
#!/usr/bin/env python # coding: utf-8 # In[1]: # inputs import numpy as np import astropy.units as u import astropy.table as tbl import matplotlib.pyplot as plt from Readfile import Read from CenterOfMass import CenterOfMass as COM from astropy.constants import G # convert G to correct units G = G.to(u.kpc * u.km**2 / u.s**2 / u.Msun) # create class MassProfile class MassProfile: # Class to define the mass profile of a galaxy at a snapshot time def __init__(self, galaxy, snap): # inputs: # galaxy: a string with galaxy name, such as "MW" or "M31" # snap: the snapshot number, such as 0, 1, etc # Initialize instance of this class with the following properties: # store the name of the galaxy self.gname = galaxy
from astropy.table import Table, Column from astropy.io import ascii # illustris python functions from illustris_python.snapshot import loadHalo, snapPath, loadSubhalo from illustris_python.groupcat import gcPath, loadHalos, loadSubhalos, loadHeader # utilities from halotools.utils import normalized_vectors # Illustris simulation properties from simulation_props import sim_prop_dict # gravitational constant from astropy.constants import G G = G.to('Mpc km^2/(Msun s^2)').value # progress bar from tqdm import tqdm import time def specific_angular_momentum(x, v, m): """ specific angular momentum of a group of particles Parameters ---------- x : array_like array particle positions of shape (Nptcl, ndim)
# -*- coding: utf-8 -*- """ This provides a few useful units for this package using astropy units """ import numpy as np import os __author__ = "Eric Emsellem" __copyright__ = "Eric Emsellem" __license__ = "mit" from astropy import units as u from astropy.constants import G as Ggrav_cgs Ggrav = Ggrav_cgs.to(u.km**2 * u.pc / u.s**2 / u.M_sun) # Defining our default units pixel = u.pixel Lsun = u.Lsun Msun = u.Msun Lsunpc2 = Lsun / u.pc**2 Msunpc2 = Msun / u.pc**2 kms = u.km / u.s kmskpc = u.km / u.s / u.kpc kms2 = (u.km / u.s)**2 km_pc = u.pc.to(u.km) s_yr = u.yr.to(u.s) def get_conversion_factor(unit, newunit, equiv=[], verbose=True): """Get the conversion factor for astropy units
import numpy as np from scipy.integrate import quad from scipy.optimize import fsolve, minimize_scalar from scipy.misc import derivative from scipy import interpolate from astropy.constants import G from astropy import units import getaefromperi import getrvcorr reload(getrvcorr) import matplotlib.pyplot as plt from scipy.interpolate import interp1d from astropy import units kminkpc = 1 * units.kpc.to(units.km) GN = (G.to(units.kpc**3 / units.s**2 / units.M_sun)).value GNfront = (G.to(units.km**2 * units.kpc / units.s**2 / units.M_sun)).value #params=(pericenter (Mpc),omatpericenter (1/s),rho0host (msun/kpc**3),rshost (kpc),mvirhost (msun)) def getrfrompot(potfunc, e, dsidr, minr=1E-10): # print abs(np.log(abs(potfunc(10**-1)))-np.log(abs(2*(e)))) # print abs(np.log(abs(potfunc(10**-2)))-np.log(abs(2*(e)))) # print abs(np.log(abs(potfunc(10**1)))-np.log(abs(2*(e)))) if e != 0: r0 = np.log(1.0 / abs(e)) + np.log(abs(potfunc(minr))) else: r0 = 1.0 if r0 == None:
""" from __future__ import division, print_function, absolute_import, unicode_literals import numpy as np import six from abc import ABCMeta, abstractmethod from scipy.integrate import quad as quad_integration from scipy.optimize import minimize as scipy_minimize from astropy import units as u from astropy.constants import G from . import halo_boundary_functions from ... import model_defaults newtonG = G.to(u.km * u.km * u.Mpc / (u.Msun * u.s * u.s)) __author__ = ["Andrew Hearin", "Benedikt Diemer"] __all__ = ["AnalyticDensityProf"] @six.add_metaclass(ABCMeta) class AnalyticDensityProf(object): r""" Container class for any analytical radial profile model. See :ref:`profile_template_tutorial` for a review of the mathematics of halo profiles, and a thorough description of how the relevant equations are implemented in the `AnalyticDensityProf` source code. Notes
import getrhalfzhao reload(getrhalfzhao) import SIDM_thermal_nob SIDM_thermal_nob.sidm_setup() from astropy import units from scipy.optimize import minimize_scalar, minimize import numpy as np import profileclass reload(profileclass) from scipy import interpolate import getrhalfnfw import matplotlib.pyplot as plt from astropy.constants import G GN = G.to(units.kpc**3 / units.M_sun / (units.s)**2) def getafromsidm(vmax, rmax, age, rvir, gamma, cross=1.0, minr=.01 * units.kpc, rmatch='half', alpha=1, beta=4, mvirmatch=True): pnfw = profileclass.NFW(vmax=vmax, rmax=rmax, rvir=rvir) delta = (pnfw.mvir / (4.0 / 3 * np.pi * rvir**3)).to(units.M_sun / units.kpc**3)
import numpy as np import astropy.units as u from astropy.constants import G # import plotting modules import matplotlib.pyplot as plt import matplotlib # my modules from ReadFile import Read from CenterOfMass import CenterOfMass # Gravitational Constant # converting G to units of kpc*km^2/s^2/Msun G = G.to(u.kpc*u.km**2/u.s**2/u.Msun) # 4.498768e-6*u.kpc**3/u.Gyr**2/u.Msun class MassProfile: # Class to define the Mass and Rotation Curve of a Galaxy def __init__(self, galaxy, snap): # Initialize the instance of this Class with the following properties: # galaxy : string, e.g. "MW" # snap : integer, e.g 1 # Determine Filename # add a string of the filenumber to the value "000" ilbl = '000' + str(snap) # remove all but the last 3 digits ilbl = ilbl[-3:]
#!/usr/bin/env python import numpy as np from tqdm import tqdm from astropy.constants import G as Ggrav from .low_level_utils import fast_dist G = Ggrav.to('kpc Msun**-1 km**2 s**-2').value def all_profiles(bins, positions, velocities, masses, two_dimensional=False, zcut=None, ages=None, pbar_msg='Making profiles"', nexpr=False): """ assumes all positions and velocities are rotated in the same way, such that the angular momentum axis aligns with the z axis if two_dimensional == False, then compute: M(<r), M(r), rho = M(r)/dV, Vcirc = sqrt(GM(<r)/r), mag J(r), mag J(<r), J_z(r), J_z(<r) if two_dimensional == True, then compute: M(<R), M(R), rho = M(R)/dA, Vcirc = mean(vx**2 + vy**2), mag J(R), mag J(<R), J_z(R), J_z(<R) :bins : array-like : sorted (from small to large) bin edges to use :positions : array-like : particle positions, rotated such that z aligns with angular momentum axis