Exemplo n.º 1
0
    def getTime(self):

        from yt import YTQuantity
        ct = self.ds.arr(math.sqrt(G), 'code_time')
        time = self.ds.current_time / ct
        sec = YTQuantity(1.0, 's')
        self.time = time * sec.in_units('day')
Exemplo n.º 2
0
def getTime(ds):

    ct = ds.arr(math.sqrt(G), 'code_time')
    time = ds.current_time / ct
    sec = YTQuantity(1.0, 's')

    time = time * sec.in_units(timelabel)

    return time
def constant_pressure_line(p):
    p = YTQuantity(p, 'dyn / cm**2')
    rho_list = []
    T_list = []
    e_list = np.linspace(-2, 3, 100)
    e_list = np.power(10, e_list)
    for e in e_list:
        e = YTQuantity(e, 'keV * cm**2')
        rho_list.append(calculate_density(e, p))
        T_list.append(calculate_temperature(e, p))
    return np.array(rho_list), np.array(T_list)
def constant_entropy_line(e):
    e = YTQuantity(e, 'keV * cm**2')
    rho_list = []
    T_list = []
    p_list = np.linspace(-15.5, -11, 100)
    p_list = np.power(10, p_list)
    for p in p_list:
        p = YTQuantity(p, 'dyn / cm**2')
        rho_list.append(calculate_density(e, p))
        T_list.append(calculate_temperature(e, p))
    return np.array(rho_list), np.array(T_list)
def calculate_entropy(rho, T):
    gammam1 = 2./3.
    mh    = YTQuantity(const.m_p.cgs.value, 'g')
    mu    = 1.22
    mu = 1
    kb    = YTQuantity(const.k_B.cgs.value, 'erg / K')    
    T     = YTQuantity(T, 'K')
    rho   = YTQuantity(rho, 'g/cm**3')

    kT = kb*T
    n = rho / (mu * mh)
    e = kT / np.power(n, gammam1)
    return  e.in_units('cm**2 * keV')
def calculate_rms_fluctuation(ds, field = 'density', zstart = .8, zend = 1.2, grid_rank = 3):
    if (grid_rank == 3):
        region1 = ds.r[0, 0, zstart:zend]
        region2 = ds.r[0, 0, -zend:-zstart]
        zlist    = np.append(region1[('gas', 'z')].in_units('kpc'),\
                             region2[('gas', 'z')].in_units('kpc'))

        dzfield = np.array([])
        for z in zlist:
            zslice  = ds.r[:, :, YTQuantity(z, 'kpc')]
            zfield     = zslice[('gas', field)]
            zfield_ave = np.mean(zfield)
            dzfield    = np.append(dzfield, (zfield - zfield_ave) / zfield_ave)
    else:
        all_y = ds.ortho_ray('y', (0, 0))[('gas', 'y')].in_units('kpc')
        ymask = np.abs(all_y / ds.length_unit.in_units('kpc') > zstart) & np.abs(all_y / ds.length_unit.in_units('kpc') < zend)
        ylist = all_y[ymask]
        dzfield = np.array([])
        for y in ylist:
            yray = ds.ortho_ray('x', (y, 0))
            zfield = yray[('gas', field)]
            zfield_ave = np.mean(zfield)
            dzfield    = np.append(dzfield, (zfield - zfield_ave) / zfield_ave)

    dzfield_rms = np.sqrt(np.mean(dzfield**2))
    return dzfield_rms
Exemplo n.º 7
0
def halo_distance_metric(halo_alpha, halo_beta):
    metric = 0.0

    #particle mass
    field = 'particle_mass'
    mass_factor = 1. / 3.
    mass_part_A = abs(halo_alpha[field] - halo_beta[field])
    mass_part_B = abs((1. / halo_alpha[field]) + (1. / halo_beta[field]))
    metric += (mass_part_A * mass_part_B) / (2 * mass_factor)

    field = 'virial_radius'
    radius_factor = 0.25 / 4.1
    radius_part_A = abs(halo_alpha[field] - halo_beta[field])
    radius_part_B = abs((1. / halo_alpha[field]) + (1. / halo_beta[field]))
    metric += (radius_part_A * radius_part_B) / (2 * radius_factor)

    position_factor = YTQuantity(0.25e23, 'cm')

    field = 'orig_particle_position_x'
    pos_x_part_A = abs(halo_alpha[field] - halo_beta[field])
    metric += pos_x_part_A / position_factor

    field = 'orig_particle_position_y'
    pos_y_part_A = abs(halo_alpha[field] - halo_beta[field])
    metric += pos_y_part_A / position_factor

    field = 'orig_particle_position_z'
    pos_z_part_A = abs(halo_alpha[field] - halo_beta[field])
    metric += pos_z_part_A / position_factor

    return metric
Exemplo n.º 8
0
def _crentropy(field, data):
    crgamma = 4. / 3.
    mh = YTQuantity(const.m_p.cgs.value, 'g')
    mu = 1.22

    pcr = data[('gas', 'cr_pressure')]
    n = data[('gas', 'density')] / (mu * mh)
    return pcr / np.power(n, crgamma)
def calculate_density(e, p):
    invgamma = 3./5.
    mh    = YTQuantity(const.m_p.cgs.value, 'g')
    mu    = 1.22
    temp = (p / e).in_units('cm**-5')
    n     = np.power(temp, invgamma)

    return n * mu * mh
Exemplo n.º 10
0
def _gasentropy(field, data):
    gamma = 5. / 3.
    mh = YTQuantity(const.m_p.cgs.value, 'g')
    mu = 1.22

    p = data[('gas', 'pressure')]
    n = data[('gas', 'density')] / (mu * mh)
    return p / np.power(n, gamma)
Exemplo n.º 11
0
def test_parse_value():
    t_yt = parse_value(YTQuantity(300.0, "ks"), "s")
    t_astropy = parse_value(Quantity(300.0, "ks"), "s")
    t_float = parse_value(300000.0, "s")
    t_tuple = parse_value((300.0, "ks"), "s")

    assert t_astropy == t_yt
    assert t_float == t_yt
    assert t_tuple == t_yt
Exemplo n.º 12
0
 def getGridInput(self, text):
     """Read out grid unit input and give feedback"""
     # reference unit
     fieldUnit = YTQuantity(1, "au").units
     from yt.units.unit_object import UnitParseError
     lineEdit = self.Misc_Dict["gridunit"]
     try:
         textUnit = YTQuantity(1, text).units
         if fieldUnit.same_dimensions_as(textUnit):
             lineEdit.turnTextBlack()
             newUnit = lineEdit.text()
         else:
             lineEdit.turnTextRed()
             newUnit = str(fieldUnit)
     except (UnitParseError, AttributeError, TypeError):
         lineEdit.turnTextRed()
         newUnit = str(fieldUnit)
     self.Config_Dict["Misc_gridunit"] = newUnit
Exemplo n.º 13
0
 def _get_dict_for_halo(self, I):
     val_dict = {}
     for field in self.catalog_ds.field_list:
         if field[0] != 'halos':
             continue
         if field[1] in self.banned_fields:
             continue
         val_dict[field[1]] = self.catalog_ad[field][I]
     val_dict['num_halos'] = YTQuantity(len(self), 'dimensionless')
     return val_dict
Exemplo n.º 14
0
def constant_rho_line(rho):
    rho = YTQuantity(rho, 'g/cm**3')
    p_list = []
    entropy_list = []
    T_list = np.linspace(3, 8, 100)
    T_list = np.power(10, T_list)
    for T in T_list:
        p_list.append(calculate_pressure(rho, T))
        entropy_list.append(calculate_entropy(rho, T))
    return np.array(p_list), np.array(entropy_list)
Exemplo n.º 15
0
def test_pixel_to_cel():

    prng = RandomState(24)

    n_evt = 100000

    sky_center = YTArray([30.0, 45.0], "deg")

    rr = YTQuantity(100.0, "kpc")*prng.uniform(size=n_evt)
    theta = 2.0*np.pi*prng.uniform(size=n_evt)
    xx = rr*np.cos(theta)
    yy = rr*np.sin(theta)

    D_A = YTQuantity(100.0, "Mpc")

    d_a = D_A.to("kpc").v

    xx = xx.d / d_a
    yy = yy.d / d_a

    xsky1 = xx.copy()
    ysky1 = yy.copy()

    pixel_to_cel(xsky1, ysky1, sky_center.d)

    xx = np.rad2deg(xx) * 3600.0  # to arcsec
    yy = np.rad2deg(yy) * 3600.0  # to arcsec

    # We set a dummy pixel size of 1 arcsec just to compute a WCS
    dtheta = 1.0 / 3600.0

    wcs = pywcs.WCS(naxis=2)
    wcs.wcs.crpix = [0.0, 0.0]
    wcs.wcs.crval = list(sky_center)
    wcs.wcs.cdelt = [-dtheta, dtheta]
    wcs.wcs.ctype = ["RA---TAN", "DEC--TAN"]
    wcs.wcs.cunit = ["deg"]*2

    xsky2, ysky2 = wcs.wcs_pix2world(xx, yy, 1)

    assert_allclose(xsky1, xsky2)
    assert_allclose(ysky1, ysky2)
Exemplo n.º 16
0
def calculate_temperature(e, p):
    gamma     = 5./3.
    gammam1   = 2./3.
    invgamma  = 3./5.
    e = e.in_units('erg * cm**2')
    p = p.in_units('dyn / cm**2')

    temp1 = np.power(p, gammam1 / gamma)
    temp2 = np.power(e, invgamma) 
    kb    = YTQuantity(const.k_B.cgs.value, 'erg / K')
    T = temp1*temp2 / kb
#    print (temp1 * temp2)
    return T
Exemplo n.º 17
0
    def __init__(self, name, hbox):
        import yt
        from yt import YTQuantity
        self.ds = yt.load(name, bounding_box=hbox)
        self.cl = self.ds.arr(1.0, 'code_length')
        self.cm = self.ds.arr(1.0, 'code_mass')
        self.cv = self.ds.arr(1.0, 'code_velocity')
        self.K = YTQuantity(1.0, 'K')
        self.cm3 = self.ds.arr(1.0, 'cm**(-3)')

        self.name = name
        namelength = len(name)
        self.setnum = float(name[namelength - 6:namelength])
Exemplo n.º 18
0
def test_bad_disk_input():
    # Fixes 1768
    ds = fake_random_ds(16)

    # Test invalid 3d array
    with assert_raises(TypeError) as ex:
        ds.disk(ds.domain_center, [0, 0, 1, 1], (10, "kpc"), (20, "kpc"))
    desired = "Expected an array of size (3,), received 'list' of length 4"
    assert_equal(str(ex.exception), desired)

    # Test invalid float
    with assert_raises(TypeError) as ex:
        ds.disk(ds.domain_center, [0, 0, 1], ds.domain_center, (20, "kpc"))
    desired = ("Expected a numeric value (or size-1 array),"
               " received 'unyt.array.unyt_array' of length 3")
    assert_equal(str(ex.exception), desired)

    # Test invalid float
    with assert_raises(TypeError) as ex:
        ds.disk(ds.domain_center, [0, 0, 1], (10, 10), (20, "kpc"))
    desired = ("Expected a numeric value (or tuple of format (float, String)),"
               " received an inconsistent tuple '(10, 10)'.")
    assert_equal(str(ex.exception), desired)

    # Test invalid iterable
    with assert_raises(TypeError) as ex:
        ds.disk(
            ds.domain_center,
            [0, 0, 1],
            (10, "kpc"),
            (20, "kpc"),
            fields=YTQuantity(1, "kpc"),
        )
    desired = "Expected an iterable object, received" " 'unyt.array.unyt_quantity'"
    assert_equal(str(ex.exception), desired)

    # Test invalid object
    with assert_raises(TypeError) as ex:
        ds.disk(ds.domain_center, [0, 0, 1], (10, "kpc"), (20, "kpc"),
                ds=ds.all_data())
    desired = ("Expected an object of 'yt.data_objects.static_output.Dataset' "
               "type, received "
               "'yt.data_objects.selection_objects.region.YTRegion'")
    assert_equal(str(ex.exception), desired)

    # Test valid disk
    ds.disk(ds.domain_center, [0, 0, 1], (10, "kpc"), (20, "kpc"))
    ds.disk(ds.domain_center, [0, 0, 1], 10, (20, "kpc"))
Exemplo n.º 19
0
def time_to_z(age, cosmology=None, v=False):
    """
    returns the redshift of a given age using an astropy cosmology

    age is taken to be in Gyr if they're all less than 15, years otherwise
    (unless it's passed in as a YTQuantity/YTArray, then it's figured out)
    """
    from yt import YTArray, YTQuantity
    if cosmology is None:
        from astropy.cosmology import Planck13 as cosmology
    from astropy.cosmology import z_at_value
    import astropy.units as u
    import numpy as np

    gyrconv = False
    #numpy array?
    if type(age) == type(np.array([1, 2, 3])):
        if (age < 15).all():
            gyrconv = True
            age = u.Quantity(age * 1e9, u.yr)
        else:
            age = u.Quantity(age, u.yr)
    #single number?
    elif type(age) == type(1.2) or type(age) == type(1):
        if age < 15:
            gyrconv = True
            age = u.Quantity(age * 1e9, u.yr)
        else:
            age = u.Quantity(age, u.yr)
    #yt quantity? convert it
    elif type(age) == type(YTQuantity(12e9, 'yr')) or type(age) == type(
            YTArray([1., 2.])):
        age = u.Quantity(age.in_units('yr'), u.yr)
    #otherwise, gotta by an astropy quantity already
    else:
        assert type(age) == type(u.Quantity(13.6, u.yr))
    if v and gyrconv:
        print "Converted to Gyr"

    try:
        it = iter(age)
        z = []
        for ii in it:
            z.append(z_at_value(cosmology.age, ii))
        z = np.array(z)
    except TypeError, te:
        # age is not iterable
        z = z_at_value(cosmology.age, age)
Exemplo n.º 20
0
def time_to_z(t,
              cosmo=None,
              verbose=False):  # H0=YTQuantity(70.2,'km/s/Mpc')):
    from yt import YTQuantity, YTArray
    if cosmo is None:
        #use Planck 2015 from last column (TT, TE, EE+lowP+lensing+ext) of Table 4 from http://arxiv.org/pdf/1502.01589v2.pdf
        from yt.utilities.cosmology import Cosmology
        h = 0.6774
        om = 0.3089
        ol = 0.6911
        #behroozi parameters
        # h=.7
        # om=.27
        # ol=1-om
        if verbose:
            print "Assuming a Planck 2015 cosmology (H0 = {0}, Om0 = {1}, OL = {2})".format(
                h * 100, om, ol)
        cosmo = Cosmology(hubble_constant=h, omega_matter=om, omega_lambda=ol)

    if type(t) != type(YTQuantity(1, 'Gyr')) and type(t) != type(
            YTArray([1, 2, 3], 'Gyr')):
        #then I need to figure out units and wrap in a yt object
        if type(t) == type(1.23):  #single float
            if t < 15:  #assume Gyr
                t = YTArray(t, 'Gyr')
                if verbose: print "Assuming time in Gyr"
            elif t < 1e11:  #assume yr
                t = YTArray(t, 'yr')
                if verbose: print "Assuming time in yr"
            else:  #then it's probably in seconds
                t = YTArray(t, 's')
                if verbose: print "Assuming time in seconds"
        else:
            from numpy import array
            t = array(t)
            if (t < 15).all():
                t = YTArray(t, 'Gyr')
                if verbose: print "Assuming time in Gyr"
            elif (t < 1e11).all():  #assume yr
                t = YTArray(t, 'yr')
                if verbose: print "Assuming time in yr"
            else:  #then it's probably in seconds
                t = YTArray(t, 's')
                if verbose: print "Assuming time in seconds"

    return cosmo.z_from_t(t)
Exemplo n.º 21
0
def test_validate_center():
    validate_center("max")
    validate_center("MIN_")

    with assert_raises(TypeError) as ex:
        validate_center("avg")
    desired = ("Expected 'center' to be in ['c', 'center', 'm', 'max', 'min'] "
               "or the prefix to be 'max_'/'min_', received 'avg'.")
    assert_equal(str(ex.exception), desired)

    validate_center(YTQuantity(0.25, "cm"))
    validate_center([0.25, 0.25, 0.25])

    class CustomCenter:
        def __init__(self, center):
            self.center = center

    with assert_raises(TypeError) as ex:
        validate_center(CustomCenter(10))
    desired = ("Expected 'center' to be a numeric object of type "
               "list/tuple/np.ndarray/YTArray/YTQuantity, received "
               "'yt.tests.test_funcs.test_validate_center.<locals>."
               "CustomCenter'.")
    assert_equal(str(ex.exception)[:50], desired[:50])
Exemplo n.º 22
0
def calculate_mass_flux(ds, z_min = 0.8, z_max = 1.2, grid_rank = 3, T_min = 3.33333e5):
    if (grid_rank == 3):
        ad = ds.all_data()
        z_abs_code = np.abs(ad[('gas', 'z')] / ds.length_unit.in_units('kpc'))

        if z_max == None:
            z_max = ds.domain_right_edge[2].d

        # convert negative velocities to positive in bottom half                           
        vz = ad[('gas', 'velocity_z')]
        vz[ad[('gas', 'z')] < 0] *= -1

        zmask = (z_abs_code >= z_min) & (z_abs_code <= z_max)
        cold_influx_mask = zmask & (vz < 0) & (ad[('gas', 'temperature')] <= T_min)

        rho0 = YTQuantity(1e-27, 'g/cm**3')
        v_cool_flow = ds.length_unit / ds.time_unit # H / tff                                                                               
        cool_flow_flux = (rho0 * v_cool_flow).in_units('Msun / kpc**2 / yr')
#        cool_flow_flux = (ad[('gas', 'density')] * v_cool_flow).in_units('Msun / kpc**2 / yr')
        all_flux = (ad[('gas', 'density')] * ad[('gas', 'velocity_z')]).in_units('Msun / kpc**2 / yr')
        all_flux_norm =(all_flux / cool_flow_flux).d

        cold_influx = all_flux_norm[cold_influx_mask]
        return np.sqrt(np.mean(cold_influx**2))
Exemplo n.º 23
0
 def __init__(self, data, catalog_helpers):
     self.mass_mean = YTQuantity(data['mass_mean']['value'],
                                 data['mass_mean']['unit'])
     self.mass_root_variance = YTQuantity(
         data['mass_root_variance']['value'],
         data['mass_root_variance']['unit'])
     self.mass_fourth_root_variance_of_variance = YTQuantity(
         data['mass_fourth_root_variance_of_variance']['value'],
         data['mass_fourth_root_variance_of_variance']['unit'])
     self.radius_mean = YTQuantity(data['radius_mean']['value'],
                                   data['radius_mean']['unit'])
     self.radius_root_variance = YTQuantity(
         data['radius_root_variance']['value'],
         data['radius_root_variance']['unit'])
     self.radius_fourth_root_variance_of_variance = YTQuantity(
         data['radius_fourth_root_variance_of_variance']['value'],
         data['radius_fourth_root_variance_of_variance']['unit'])
     self.halos = []
     for halo_data in data['superhalo_content']:
         self.halos.append(
             catalog_helpers[halo_data['sim_num']][halo_data['halo']])
Exemplo n.º 24
0
                sp, ('darkmatter', 'particle_radius'),
                [('darkmatter', 'particle_mass')],
                accumulation=True,
                units={
                    ('darkmatter', 'particle_radius'): 'kpc',
                    ('darkmatter', 'particle_mass'): 'Msun'
                },
                weight_field=None,
                override_bins={('darkmatter', 'particle_radius'): radius_bins})

            #now loop through the bins to find the right delta_vir
            z = ds.current_redshift
            a = 1 / (1 + z)
            omega_matter = ds.omega_matter
            omega_lambda = ds.omega_lambda
            h_0 = YTQuantity(0.699999988079071, '100*km/s/Mpc')
            G1 = YTQuantity(6.67430e-11, 'm*m*m/kg/s/s')

            delta_vir_actual = delta_vir_calculator(z, omega_matter,
                                                    omega_lambda)
            print('Wanted detla_vir: {}'.format(delta_vir_actual))
            #now use the omega_matter_current, and the critical density to find the current matter_density
            critical_density = 3 * ((h_0)**2) / (8 * np.pi * G1) * a**-3

            rho_matter = omega_matter * critical_density

            #this is where all of the differences of delta vir will be stored so that the clocest can be saved and recalculated
            delta_vir_distance = []

            gas_profile_list = []
            star_profile_list = []
Exemplo n.º 25
0
        print "Converted to Gyr"

    try:
        it = iter(age)
        z = []
        for ii in it:
            z.append(z_at_value(cosmology.age,ii))
        z = np.array(z)
    except TypeError, te:
        # age is not iterable
        z = z_at_value(cosmology.age,age)
    return z


th = cosmo.age(0)
thubble = YTQuantity(th*th.unit.in_units('yr'),'yr')

# thubble = 13.82e9*units.yr

# M1 = 30. * units.Msun
# M2 = 30. * units.Msun
# Mtot = M1 + M2
# # mu = (M**2/Mtot)
#
# Pmin = 2.*units.day
# amin = Period_to_Semimajor(Pmin,M1,M2)
# tmin = Semimajor_to_Coalescence(amin,M1,M2)
# # amin = (((phys_const.G*Mtot)/(4.*pi*pi)) * Pmin**2)**(1./3.) #.in_units('kpc')
# # tmin = 5./256.*(phys_const.clight**5 * amin**4)/(phys_const.G**3 * Mtot**2 * mu)
#
# Pmax = 20.*units.day
Exemplo n.º 26
0
from yt import YTQuantity
from berniter import *
from timestuff import *

userho = 0

num = 1000000 + dataset
numstr = str(num)
cut = numstr[1:7]

ds = yt.load(readpath + outprefix + cut, bounding_box = hbox )

cl = ds.arr(1.0, 'code_length')
cm = ds.arr(1.0, 'code_mass')
cv = ds.arr(1.0, 'code_velocity')
K = YTQuantity(1.0,'K')

def _bern(field, data) :
	PE = data[('Gas','Phi')]/cl
	posCM, velCM = getCM(data.ds, IE=useIE)
	v = np.linalg.norm( data[('Gas','Velocities')]/cv - velCM, axis=1 )
	KE = 0.5*np.multiply(v,v)
	if useIE:
		enthalpy = data[('Gas','ie')]
	else:
		enthalpy = gamma / (gamma-1.0) * R * data[('Gas','Temperature')] / K
	bern = PE + KE + enthalpy
	if userho :
		rho = data[('Gas','rho')]
		bern = np.multiply( bern, rho )
	return bern
Exemplo n.º 27
0
    def from_scratch(
        cls, mode, xmin, xmax, profiles, input_units=None, num_points=1000, geometry="spherical", P_amb=0.0
    ):
        r"""
        Generate a set of profiles of physical quantities based on the assumption
        of hydrostatic equilibrium. Currently assumes an ideal gas with a gamma-law
        equation of state.

        Parameters
        ----------
        mode : string
            The method to generate the profiles from an initial set. Can be
            one of the following:
                "dens_temp": Generate the profiles given a gas density and
                gas temperature profile.
                "dens_tden": Generate the profiles given a gas density and
                total density profile.
                "dens_grav": Generate the profiles given a gas density and
                gravitational acceleration profile.
                "dm_only": Generate profiles of gravitational potential
                and acceleration assuming an initial DM density profile.
        xmin : float
            The minimum radius or height for the profiles, assumed to be in kpc.
        xmax : float
            The maximum radius or height for the profiles, assumed to be in kpc.
        profiles : dict of functions
            A dictionary of callable functions of radius or height which return
            quantities such as density, total density, and so on. The functions 
            are not unit-aware for speed purposes, but they assume that the base
            units are:
                "length": "kpc"
                "time": "Myr"
                "mass": "Msun"
                "temperature": "keV"
        parameters : dict of floats
            A dictionary of parameters needed for the calculation, which include:
                "mu": The mean molecular weight of the gas. Default is to assume a
                primordial H/He gas.
                "gamma": The ratio of specific heats. Default: 5/3.
        num_points : integer
            The number of points at which to evaluate the profile.
        geometry : string
            The geometry of the model. Can be "cartesian" or "spherical", which will
            determine whether or not the profiles are of "radius" or "height".
        """

        if not isinstance(P_amb, YTQuantity):
            P_amb = YTQuantity(P_amb, "erg/cm**3")
        P_amb.convert_to_units("Msun/(Myr**2*kpc)")

        for p in modes[mode]:
            if p not in profiles:
                raise RequiredProfilesError(mode)

        if mode in ["dens_tden", "dm_only"] and geometry != "spherical":
            raise NotImplemented(
                "Constructing a HydrostaticEquilibrium from gas density and/or "
                "total density profiles is only allowed in spherical geometry!"
            )

        extra_fields = [field for field in profiles if field not in cls.default_fields]

        if geometry == "cartesian":
            x_field = "height"
        elif geometry == "spherical":
            x_field = "radius"

        fields = OrderedDict()

        xx = np.logspace(np.log10(xmin), np.log10(xmax), num_points, endpoint=True)
        fields[x_field] = YTArray(xx, "kpc")

        if mode == "dm_only":
            fields["density"] = YTArray(np.zeros(num_points), "Msun/kpc**3")
            fields["pressure"] = YTArray(np.zeros(num_points), "Msun/kpc/Myr**2")
            fields["temperature"] = YTArray(np.zeros(num_points), "keV")
        else:
            fields["density"] = YTArray(profiles["density"](xx), "Msun/kpc**3")

        if mode == "dens_temp":

            mylog.info("Computing the profiles from density and temperature.")

            fields["temperature"] = YTArray(profiles["temperature"](xx), "keV")
            fields["pressure"] = fields["density"] * fields["temperature"]
            fields["pressure"] *= muinv / mp
            fields["pressure"].convert_to_units("Msun/(Myr**2*kpc)")

            pressure_spline = InterpolatedUnivariateSpline(xx, fields["pressure"].v)
            dPdx = YTArray(pressure_spline(xx, 1), "Msun/(Myr**2*kpc**2)")
            fields["gravitational_field"] = dPdx / fields["density"]
            fields["gravitational_field"].convert_to_units("kpc/Myr**2")

        else:

            if mode == "dens_tden" or mode == "dm_only":
                mylog.info("Computing the profiles from density and total density.")
                fields["total_density"] = YTArray(profiles["total_density"](xx), "Msun/kpc**3")
                mylog.info("Integrating total mass profile.")
                fields["total_mass"] = YTArray(integrate_mass(profiles["total_density"], xx), "Msun")
                fields["gravitational_field"] = -G * fields["total_mass"] / (fields["radius"] ** 2)
                fields["gravitational_field"].convert_to_units("kpc/Myr**2")
            elif mode == "dens_grav":
                mylog.info("Computing the profiles from density and gravitational acceleration.")
                fields["gravitational_field"] = YTArray(profiles["gravitational_field"](xx), "kpc/Myr**2")

            if mode != "dm_only":
                g = fields["gravitational_field"].in_units("kpc/Myr**2").v
                g_r = InterpolatedUnivariateSpline(xx, g)
                dPdr_int = lambda r: profiles["density"](r) * g_r(r)
                mylog.info("Integrating pressure profile.")
                fields["pressure"] = -YTArray(integrate(dPdr_int, xx), "Msun/kpc/Myr**2")
                fields["temperature"] = fields["pressure"] * mp / fields["density"] / muinv
                fields["temperature"].convert_to_units("keV")

        if geometry == "spherical":
            if "total_mass" not in fields:
                fields["total_mass"] = -fields["radius"] ** 2 * fields["gravitational_field"] / G
            if "total_density" not in fields:
                total_mass_spline = InterpolatedUnivariateSpline(xx, fields["total_mass"].v)
                dMdr = YTArray(total_mass_spline(xx, 1), "Msun/kpc")
                fields["total_density"] = dMdr / (4.0 * np.pi * fields["radius"] ** 2)
            mylog.info("Integrating gravitational potential profile.")
            if "total_density" in profiles:
                tdens_func = profiles["total_density"]
            else:
                tdens_func = InterpolatedUnivariateSpline(xx, fields["total_density"].d)
            gpot_profile = lambda r: tdens_func(r) * r
            gpot = YTArray(4.0 * np.pi * integrate(gpot_profile, xx), "Msun/kpc")
            fields["gravitational_potential"] = -G * (fields["total_mass"] / fields["radius"] + gpot)
            fields["gravitational_potential"].convert_to_units("kpc**2/Myr**2")
            if mode != "dm_only":
                mylog.info("Integrating gas mass profile.")
                fields["gas_mass"] = YTArray(integrate_mass(profiles["density"], xx), "Msun")

        mdm = fields["total_mass"].copy()
        ddm = fields["total_density"].copy()
        if mode != "dm_only":
            mdm -= fields["gas_mass"]
            ddm -= fields["density"]
            mdm[ddm.v < 0.0][:] = mdm.max()
            ddm[ddm.v < 0.0][:] = 0.0
        fields["dark_matter_density"] = ddm
        fields["dark_matter_mass"] = mdm

        fields["pressure"] += P_amb

        for field in extra_fields:
            fields[field] = profiles[field](xx)

        return cls(num_points, fields, geometry)
Exemplo n.º 28
0
        return np.sqrt(data["gas","pressure"]/data["gas","density"])

def _T1(field, data):
        return data["gas","pressure"]/data["gas","density"]*mh/kboltz

def _mu(field, data):
        cf=pa.coolftn()
        T1=data["gas","T1"].d
        temp=cf.get_temp(T1)
        return temp/T1

def _temperature(field,data):
        return data["gas","T1"]*data["gas","mu"]

# rotation
Omega=YTQuantity(28,"km/s/kpc")
def _dvelocity(field,data):
        return data["gas","velocity_y"]+data["gas","x"]*Omega

def _dvelocity_mag(field,data):
        return np.sqrt(data["gas","velocity_x"]**2+data["gas","dvelocity_y"]**2+data["gas","velocity_z"]**2)

def _dkinetic_energy(field,data):
    return 0.5*data['gas','dvelocity_magnitude']**2*data['gas','density']

# magnetic fields
def _mag_pok(field,data):
        return data["gas","magnetic_pressure"]/kboltz

# metals
def _metallicity(field,data):
Exemplo n.º 29
0
        h2 = abundance_h2[glist]
        mass = gas_mass[glist]
        r_max = factor * gal_rad[gal_ids[i]]

        DR = r_max / NR
        r_plot = np.arange(0.5 * DR, (NR + 0.5) * DR, DR)  # bin centers
        if len(r_plot) > NR:
            r_plot = r_plot[1:]

        # do this all for h1
        pos = gas_pos[glist]
        vel = gas_v[glist]
        pos -= center_of_quantity(pos, h1 * mass)
        vel -= center_of_quantity(vel, h1 * mass)
        mask = np.linalg.norm(pos, axis=1) <= r_max
        mass_within_r = YTQuantity(np.sum(mass[mask]), 'Msun')

        sigv_h1[i] = sigma_vel(vel[mask])
        # get mass within r_max or within position of maximum velocity?
        vrot_grav_h1[i] = vrot_gravity(mass_within_r,
                                       YTArray(r_max, 'kpc').in_units('km'),
                                       YTQuantity(sigv_h1[i], 'km/s'), G)

        plot_name = results_dir + 'profiles/vrot_h1_profile_gal_' + str(
            i) + '.png'
        vrot_h1[i] = vrot_los(pos[mask], vel[mask], mass[mask], edge_vec, NR,
                              DR, (h1 * mass)[mask], r_plot, plot_name)

        # do this all for h2
        pos = gas_pos[glist]
        vel = gas_v[glist]
Exemplo n.º 30
0
def sigma(r,runit,outunit="Msun/AU**2"):
    from yt import YTQuantity #,YTArray
    rinau = YTQuantity(r,runit).in_units('AU').item()
    sig_gcm2 = YTQuantity(1700*(rinau**-3./2.),'g/cm**2')
    return sig_gcm2.in_units(outunit).item()
Exemplo n.º 31
0
def Semimajor_to_Period(A,M1,M2):
    Mtot = M1 + M2
    from numpy import sqrt,pi
    return sqrt((4*pi*pi) * A**3 / (phys_const.G*Mtot))

def Semimajor_to_Coalescence(a,M1,M2):
    mu = (M1*M2)/(M1+M2)
    Mtot = M1+M2
    return 5./256.*(phys_const.clight**5 * a**4)/(phys_const.G**3 * Mtot**2 * mu)

def Period_to_Coalescence(P,M1,M2):
    a = Period_to_Semimajor(P,M1,M2)
    return Semimajor_to_Coalescence(a,M1,M2)

th = cosmo.age(0)
thubble = YTQuantity(th*th.unit.in_units('yr'),'yr')

M1 = 30. * units.Msun
M2 = 30. * units.Msun
Mtot = M1 + M2
# mu = (M**2/Mtot)

Pmin = 2.*units.day
amin = Period_to_Semimajor(Pmin,M1,M2)
tmin = Semimajor_to_Coalescence(amin,M1,M2)
# amin = (((phys_const.G*Mtot)/(4.*pi*pi)) * Pmin**2)**(1./3.) #.in_units('kpc')
# tmin = 5./256.*(phys_const.clight**5 * amin**4)/(phys_const.G**3 * Mtot**2 * mu)

Pmax = 20.*units.day
amax = Period_to_Semimajor(Pmax,M1,M2)
tmax = Semimajor_to_Coalescence(amax,M1,M2)
Exemplo n.º 32
0
    def _load_gas_data(self, select='all'):
        """If gas is present loads gas SFR, metallicities, temperatures, nH.
           If select is not 'all', return all particles with select>=0 """

        if self.obj.simulation.ngas == 0:
            return

        sfr_unit = '%s/%s' % (self.obj.units['mass'], self.obj.units['time'])
        dustmass_unit = '%s' % (self.obj.units['mass'])
        gnh_unit = '1/%s**3' % (self.obj.units['length'])

        sfr = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE), sfr_unit)
        gZ = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE), '')
        gT = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE),
            self.obj.units['temperature'])
        gnh = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE), gnh_unit)
        dustmass = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE), '')
        gfHI = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE), '')
        gfH2 = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE), '')
        ghsml = self.obj.yt_dataset.arr(
            np.zeros(self.obj.simulation.ngas, dtype=MY_DTYPE),
            self.obj.units['length'])
        #dustmass = self.obj.yt_dataset.arr(np.zeros(self.obj.simulation.ngas), '')#dustmass_unit)

        if isinstance(select, str) and select == 'all':
            flag = [True] * self.obj.simulation.ngas
        else:
            flag = (select >= 0)

        if has_property(self.obj, 'gas', 'sfr'):
            sfr = get_property(self.obj, 'sfr', 'gas')[flag].to(sfr_unit)

        if has_property(self.obj, 'gas', 'metallicity'):
            gZ = get_property(self.obj, 'metallicity', 'gas')[flag]
        elif has_property(self.obj, 'gas', 'met_tng'):
            gZ = get_property(self.obj, 'met_tng',
                              'gas')[flag]  # for Illustris, array of mets
        else:
            mylog.warning(
                'Metallicity not found: setting all gas to solar=0.0134')
            gZ = 0.0134 * np.ones(self.obj.simulation.nstar, dtype=MY_DTYPE)

        if has_property(self.obj, 'gas', 'nh'):
            gfHI = get_property(self.obj, 'nh', 'gas')[flag]
        else:
            mylog.warning(
                'HI fractions not found in snapshot, will compute later')

        if has_property(self.obj, 'gas', 'fh2'):
            gfH2 = get_property(self.obj, 'fh2', 'gas')[flag]
        else:
            mylog.warning(
                'H2 fractions not found in snapshot, will compute later')

        if has_property(self.obj, 'gas', 'temperature'):
            gT = get_property(self.obj, 'temperature',
                              'gas')[flag].to(self.obj.units['temperature'])

        if has_property(self.obj, 'gas', 'hsml'):
            ghsml = get_property(self.obj, 'hsml',
                                 'gas')[flag].to(self.obj.units['length'])

        if has_property(self.obj, 'gas', 'rho'):
            from astropy import constants as const
            from yt import YTQuantity
            redshift = self.obj.simulation.redshift
            m_p = YTQuantity.from_astropy(const.m_p)
            gnh = get_property(self.obj, 'rho',
                               'gas')[flag].in_cgs() * 0.76 / m_p.in_cgs()

        if has_property(self.obj, 'gas', 'dustmass'):
            dustmass = get_property(self.obj, 'dustmass', 'gas')[flag]
        else:
            mylog.warning('Dust masses not found in snapshot')

        self.gsfr = sfr
        self.gZ = gZ
        self.gT = gT
        self.gnh = gnh
        self.gfHI = gfHI
        self.gfH2 = gfH2
        self.hsml = ghsml
        self.dustmass = self.obj.yt_dataset.arr(dustmass,
                                                'code_mass').in_units('Msun')
        self.dustmass.dtype = MY_DTYPE
Exemplo n.º 33
0
magnetic_pressure_ratio = 0
constant_cr_pressure = 0
cr_pressure_ratio = 0

cr_streaming = 0
cr_heating = 0
cr_diffusion = 0

########### These parameters don't really need to change ###########
bfield_direction = [0, 1, 0]
resolution = 128  # resolution along z-axis; scaled for x-y axes
grid_rank = 3

# cooling function parameters
# Tmin should be ~ T0/20
T_min = YTQuantity(5e4, 'K')
T_max = YTQuantity(1e9, 'K')
T_power_law_index = (-2. / 3.)
smooth_factor = 0.02

####### gas parameters ######
# changing these will just rescale the units
T0 = YTQuantity(1e6, 'K')
rho0 = YTQuantity(1e-27, 'g/cm**3')
g0 = YTQuantity(5e-10, 'cm/s**2')
gsoft_scale = 0.1  # units of scale height

###### perturbatio default parameters
perturbation_amplitude = 0.02
default_n = resolution
default_kmin = 4