本文整理汇总了Python中astropy.constants.G类的典型用法代码示例。如果您正苦于以下问题:Python G类的具体用法?Python G怎么用?Python G使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了G类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mass_enclosed
def mass_enclosed(self, x):
"""
Estimate the mass enclosed within the given position by assumine the potential
is spherical. This is basic, and assumes spherical symmetry.
Parameters
----------
x : array_like, numeric
Position to estimate the enclossed mass.
"""
# Fractional step-size in radius
h = 0.01
# Radius
r = np.sqrt(np.sum(x**2, axis=-1))
epsilon = h*x/r[...,np.newaxis]
dPhi_dr_plus = self.value(x + epsilon)
dPhi_dr_minus = self.value(x - epsilon)
diff = dPhi_dr_plus - dPhi_dr_minus
if self.units is None:
raise ValueError("No units specified when creating potential object.")
Gee = G.decompose(self.units).value
return np.abs(r*r * diff / Gee / (2.*h))
示例2: __init__
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
示例3: __init__
def __init__(self, m, a, units):
self.parameters = OrderedDict()
self.parameters['m'] = m
self.parameters['a'] = a
super(KuzminPotential, self).__init__(units=units)
self.G = G.decompose(units).value
示例4: _read_units
def _read_units(self):
"""
Read and parse the SCFPAR file containing simulation parameters
and initial conditions. Right now, only parse out the simulation units.
"""
pars = dict()
parfile = os.path.join(self.path, "SCFPAR")
with open(parfile) as f:
lines = f.readlines()
# find what G is set to
for i,line in enumerate(lines):
if line.split()[1].strip() == "G":
break
pars['G'] = float(lines[i].split()[0])
pars['length'] = float(lines[i+10].split()[0])
pars['mass'] = float(lines[i+11].split()[0])
self.x0 = np.array(map(float, lines[19].split()))*u.kpc
self.v0 = np.array(map(float, lines[20].split()))*u.km/u.s
_G = G.decompose(bases=[u.kpc,u.M_sun,u.Myr]).value
X = (_G / pars['length']**3 * pars['mass'])**-0.5
length_unit = u.Unit("{0} kpc".format(pars['length']))
mass_unit = u.Unit("{0} M_sun".format(pars['mass']))
time_unit = u.Unit("{:08f} Myr".format(X))
# units = dict(length=length_unit,
# mass=mass_unit,
# time=time_unit,
# speed=length_unit/time_unit,
# dimensionless=u.dimensionless_unscaled)
return UnitSystem(length_unit, mass_unit, time_unit, length_unit/time_unit, u.radian)
示例5: test_against_gary
def test_against_gary():
cos_coeff = np.array([[[1.509, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-2.606, 0.0, 0.665, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [6.406, 0.0, -0.66, 0.0, 0.044, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-5.859, 0.0, 0.984, 0.0, -0.03, 0.0, 0.001]], [[-0.086, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.221, 0.0, 0.129, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.295, 0.0, -0.14, 0.0, -0.012, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [[-0.033, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.001, 0.0, 0.006, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [[-0.02, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]])
sin_coeff = np.zeros_like(cos_coeff)
nmax = sin_coeff.shape[0]-1
lmax = sin_coeff.shape[1]-1
max_x = 10.
grid = np.linspace(-max_x,max_x,8)
grid = grid[grid != 0.]
xyz = np.ascontiguousarray(np.vstack(map(np.ravel, np.meshgrid(grid,grid,grid))).T)
# xyz = np.array([[1.,1.,1.]])
grad = np.zeros_like(xyz)
acceleration(xyz, grad, sin_coeff, cos_coeff, nmax, lmax)
grad *= -1.
val = np.zeros(len(grad))
value(xyz, val, sin_coeff, cos_coeff, nmax, lmax)
# gary
import gary.potential as gp
from gary.units import galactic
G = _G.decompose(galactic).value
potential = gp.SCFPotential(m=1/G, r_s=1.,
sin_coeff=sin_coeff, cos_coeff=cos_coeff,
units=galactic)
gary_val = potential.value(xyz)
gary_grad = potential.gradient(xyz)
np.testing.assert_allclose(gary_val, val, rtol=1E-5)
np.testing.assert_allclose(gary_grad, grad, rtol=1E-5)
示例6: __init__
def __init__(self, parameters, origin=None, R=None,
ndim=3, units=None):
self._units = self._validate_units(units)
self.parameters = self._prepare_parameters(parameters, self.units)
try:
self.G = G.decompose(self.units).value
except u.UnitConversionError:
self.G = 1. # TODO: this is a HACK and could lead to user confusion
self.ndim = ndim
if origin is None:
origin = np.zeros(self.ndim)
self.origin = self._remove_units(origin)
if R is not None and ndim not in [2, 3]:
raise NotImplementedError('Gala potentials currently only support '
'rotations when ndim=2 or ndim=3.')
if R is not None:
if isinstance(R, Rotation):
R = R.as_dcm()
R = np.array(R)
if R.shape != (ndim, ndim):
raise ValueError('Rotation matrix passed to potential {0} has '
'an invalid shape: expected {1}, got {2}'
.format(self.__class__.__name__,
(ndim, ndim), R.shape))
self.R = R
示例7: __init__
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)
示例8: mass_enclosed
def mass_enclosed(self, q, t=0.):
"""
Estimate the mass enclosed within the given position by assuming the potential
is spherical.
Parameters
----------
q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like
Position(s) to estimate the enclossed mass.
Returns
-------
menc : `~astropy.units.Quantity`
Mass enclosed at the given position(s). If the input position
has shape ``q.shape``, the output energy will have shape
``q.shape[1:]``.
"""
q = self._remove_units_prepare_shape(q)
orig_shape, q = self._get_c_valid_arr(q)
t = self._validate_prepare_time(t, q)
# small step-size in direction of q
h = 1E-3 # MAGIC NUMBER
# Radius
r = np.sqrt(np.sum(q**2, axis=1))
epsilon = h*q/r[:, np.newaxis]
dPhi_dr_plus = self._energy(q + epsilon, t=t)
dPhi_dr_minus = self._energy(q - epsilon, t=t)
diff = (dPhi_dr_plus - dPhi_dr_minus)
if isinstance(self.units, DimensionlessUnitSystem):
Gee = 1.
else:
Gee = G.decompose(self.units).value
Menc = np.abs(r*r * diff / Gee / (2.*h))
Menc = Menc.reshape(orig_shape[1:])
sgn = 1.
if 'm' in self.parameters and self.parameters['m'] < 0:
sgn = -1.
return sgn * Menc * self.units['mass']
示例9: _units_from_file
def _units_from_file(scfpar):
""" Generate a unit system from an SCFPAR file. """
with open(scfpar) as f:
lines = f.readlines()
length = float(lines[16].split()[0])
mass = float(lines[17].split()[0])
GG = G.decompose(bases=[u.kpc,u.M_sun,u.Myr]).value
X = (GG / length**3 * mass)**-0.5
length_unit = u.Unit("{0} kpc".format(length))
mass_unit = u.Unit("{0} M_sun".format(mass))
time_unit = u.Unit("{:08f} Myr".format(X))
return dict(length=length_unit,
mass=mass_unit,
time=time_unit)
示例10: __init__
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)
示例11: tdyn
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
示例12: __init__
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)
示例13: __init__
def __init__(self, parameters, units=None):
# make sure the units specified are a UnitSystem instance
if units is not None and not isinstance(units, UnitSystem):
units = UnitSystem(*units)
elif units is None:
units = DimensionlessUnitSystem()
self.units = units
# in case the user specified an ordered dict
self.parameters = OrderedDict()
for k,v in parameters.items():
if hasattr(v, 'unit'):
self.parameters[k] = v.decompose(self.units)
else:
self.parameters[k] = v*u.one
try:
self.G = G.decompose(self.units).value
except u.UnitConversionError:
self.G = 1. # TODO: this is a HACK and could lead to user confusion
示例14: mass_enclosed
def mass_enclosed(self, q, t=0.):
"""
Estimate the mass enclosed within the given position by assuming the potential
is spherical.
Parameters
----------
x : array_like, numeric
Position to estimate the enclossed mass.
Returns
-------
menc : `~numpy.ndarray`
The mass. Will have the same shape as the input position,
array, ``q``, but without the coordinate axis, ``axis=0``
"""
q = np.ascontiguousarray(atleast_2d(q, insert_axis=1))
# Fractional step-size in radius
h = 0.01
# Radius
r = np.sqrt(np.sum(q**2, axis=0))
epsilon = h*q/r[np.newaxis]
dPhi_dr_plus = self.value(q + epsilon, t=t)
dPhi_dr_minus = self.value(q - epsilon, t=t)
diff = dPhi_dr_plus - dPhi_dr_minus
if self.units is None:
raise ValueError("No units specified when creating potential object.")
Gee = G.decompose(self.units).value
return np.abs(r*r * diff / Gee / (2.*h))
示例15: mass_enclosed
def mass_enclosed(self, q, t=0.):
"""
Estimate the mass enclosed within the given position by assuming the potential
is spherical.
Parameters
----------
x : array_like, numeric
Position to estimate the enclossed mass.
Returns
-------
menc : `~astropy.units.Quantity`
The potential energy or value of the potential. If the input
position has shape ``q.shape``, the output energy will have
shape ``q.shape[1:]``.
"""
q = self._prefilter_pos(q)
# Fractional step-size in radius
h = 0.01
# Radius
r = np.sqrt(np.sum(q**2, axis=0))
epsilon = h*q/r[np.newaxis]
dPhi_dr_plus = self.value(q + epsilon, t=t)
dPhi_dr_minus = self.value(q - epsilon, t=t)
diff = dPhi_dr_plus - dPhi_dr_minus
if isinstance(self.units, DimensionlessUnitSystem):
raise ValueError("No units specified when creating potential object.")
Gee = G.decompose(self.units).value
return np.abs(r*r * diff / Gee / (2.*h)) * self.units['mass']