Esempio n. 1
0
    def _parse_parameter_file(self):
        # Read all parameters.
        simu = self._read_log_simu()
        param = self._read_parameter()

        # Set up general information.
        self.filename_template = self.parameter_filename
        self.file_count = 1
        self.parameters.update(param)
        self.particle_types = ('halos')
        self.particle_types_raw = ('halos')

        # Set up geometrical information.
        self.refine_by = 2
        self.dimensionality = 3
        nz = 1 << self.over_refine_factor
        self.domain_dimensions = np.ones(self.dimensionality, "int32") * nz
        self.domain_left_edge = np.array([0.0, 0.0, 0.0])
        # Note that boxsize is in Mpc but particle positions are in kpc.
        self.domain_right_edge = np.array([simu['boxsize']] * 3) * 1000
        self.periodicity = (True, True, True)

        # Set up cosmological information.
        self.cosmological_simulation = 1
        self.current_redshift = param['z']
        self.omega_lambda = simu['lambda0']
        self.omega_matter = simu['omega0']
        cosmo = Cosmology(hubble_constant=self.hubble_constant,
                          omega_matter=self.omega_matter,
                          omega_lambda=self.omega_lambda)
        self.current_time = cosmo.lookback_time(param['z'], 1e6).in_units('s')
Esempio n. 2
0
 def _set_units(self):
     self.unit_registry = UnitRegistry()
     self.time_unit = self.quan(1.0, "s")
     if self.cosmological_simulation:
         # Instantiate Cosmology object for units and time conversions.
         self.cosmology = \
           Cosmology(hubble_constant=self.hubble_constant,
                     omega_matter=self.omega_matter,
                     omega_lambda=self.omega_lambda,
                     unit_registry=self.unit_registry)
         self.unit_registry.modify("h", self.hubble_constant)
         # Comoving lengths
         for my_unit in ["m", "pc", "AU", "au"]:
             new_unit = "%scm" % my_unit
             # technically not true, but should be ok
             self.unit_registry.add(new_unit,
                                    self.unit_registry.lut[my_unit][0],
                                    dimensions.length,
                                    "\\rm{%s}/(1+z)" % my_unit)
         self.length_unit = self.quan(self.unit_base["UnitLength_in_cm"],
                                      "cmcm / h",
                                      registry=self.unit_registry)
         self.box_size *= self.length_unit.in_units("Mpccm / h")
     else:
         # Read time from file for non-cosmological sim
         self.time_unit = self.quan(
             self.unit_base["UnitLength_in_cm"]/ \
                 self.unit_base["UnitVelocity_in_cm_per_s"], "s")
         self.unit_registry.add("code_time", 1.0, dimensions.time)
         self.unit_registry.modify("code_time", self.time_unit)
         # Length
         self.length_unit = self.quan(self.unit_base["UnitLength_in_cm"],
                                      "cm")
         self.unit_registry.add("code_length", 1.0, dimensions.length)
         self.unit_registry.modify("code_length", self.length_unit)
Esempio n. 3
0
    def _load_star_data(self, select='all'):
        """If star is present load Metallicity if present"""
        if self.obj.simulation.nstar == 0:
            return

        if select is 'all': 
            flag = [True]*self.obj.simulation.nstar
        else:
            flag = (select>=0)

        if has_property(self.obj, 'star', 'metallicity'):
            self.sZ  = get_property(self.obj, 'metallicity', 'star')[flag]
        elif has_property(self.obj, 'star', 'met_tng'):  # try Illustris/TNG alias
            self.sZ  = get_property(self.obj, 'met_tng', 'star')[flag]  
            #self.sZ  = np.sum(self.sZ.T[2:],axis=0)  # first two are H,He; the rest sum to give metallicity
            #self.sZ[self.sZ<0] = 0.  # some (very small) negative values, set to 0
        else:
            mylog.warning('Metallicity not found: setting all stars to solar=0.0134')
            self.sZ = 0.0134*np.ones(self.obj.simulation.nstar,dtype=MY_DTYPE)

        ds = self.obj.yt_dataset
        if has_property(self.obj, 'star', 'aform'):
            self.age  = get_property(self.obj, 'aform', 'star')[flag]  # a_exp at time of formation
        elif has_property(self.obj, 'star', 'aform_tng'):  # try Illustris/TNG alias
            self.age  = get_property(self.obj, 'aform_tng', 'star')[flag]  
            self.age  = abs(self.age)  # some negative values here too; not sure what to do?
        else:
            self.age = np.zeros(self.obj.simulation.nstar,dtype=MY_DTYPE)
            mylog.warning('Stellar age not found -- photometry will be incorrect!')
        if ds.cosmological_simulation:
            from yt.utilities.cosmology import Cosmology
            co = Cosmology(hubble_constant=ds.hubble_constant, omega_matter=ds.omega_matter, omega_lambda=ds.omega_lambda)
            self.age = (ds.current_time - co.t_from_z(1./self.age-1.)).in_units('Gyr').astype(MY_DTYPE)  # age at time of snapshot 
    def _parse_parameter_file(self):

        hvals = self._get_hvals()

        self.dimensionality = 3
        self.refine_by = 2
        self.parameters["HydroMethod"] = "sph"
        self.unique_identifier = \
            int(os.stat(self.parameter_filename)[stat.ST_CTIME])
        # Set standard values

        # We may have an overridden bounding box.
        if self.domain_left_edge is None:
            self.domain_left_edge = np.zeros(3, "float64")
            self.domain_right_edge = np.ones(3, "float64") * hvals["BoxSize"]
        nz = 1 << self.over_refine_factor
        self.domain_dimensions = np.ones(3, "int32") * nz
        self.periodicity = (True, True, True)

        self.cosmological_simulation = 1

        self.current_redshift = hvals["Redshift"]
        self.omega_lambda = hvals["OmegaLambda"]
        self.omega_matter = hvals["Omega0"]
        self.hubble_constant = hvals["HubbleParam"]
        # According to the Gadget manual, OmegaLambda will be zero for
        # non-cosmological datasets.  However, it may be the case that
        # individuals are running cosmological simulations *without* Lambda, in
        # which case we may be doing something incorrect here.
        # It may be possible to deduce whether ComovingIntegration is on
        # somehow, but opinions on this vary.
        if self.omega_lambda == 0.0:
            mylog.info("Omega Lambda is 0.0, so we are turning off Cosmology.")
            self.hubble_constant = 1.0  # So that scaling comes out correct
            self.cosmological_simulation = 0
            self.current_redshift = 0.0
            # This may not be correct.
            self.current_time = hvals["Time"]
        else:
            # Now we calculate our time based on the cosmology, because in
            # ComovingIntegration hvals["Time"] will in fact be the expansion
            # factor, not the actual integration time, so we re-calculate
            # global time from our Cosmology.
            cosmo = Cosmology(self.hubble_constant,
                              self.omega_matter, self.omega_lambda)
            self.current_time = cosmo.hubble_time(self.current_redshift)
            mylog.info("Calculating time from %0.3e to be %0.3e seconds",
                       hvals["Time"], self.current_time)
        self.parameters = hvals

        prefix = os.path.abspath(
            os.path.join(os.path.dirname(self.parameter_filename),
                         os.path.basename(self.parameter_filename).split(".", 1)[0]))

        if hvals["NumFiles"] > 1:
            self.filename_template = "%s.%%(num)s%s" % (prefix, self._suffix)
        else:
            self.filename_template = self.parameter_filename

        self.file_count = hvals["NumFiles"]
Esempio n. 5
0
    def _parse_parameter_file(self):
        with h5py.File(self.parameter_filename, mode="r") as f:
            self.parameters = \
              dict((str(field), val)
                   for field, val in f["Header"].attrs.items())

        self.dimensionality = 3
        self.refine_by = 2

        # Set standard values
        self.domain_left_edge = np.zeros(3, "float64")
        self.domain_right_edge = np.ones(3, "float64") * \
          self.parameters["BoxSize"]
        self.domain_dimensions = np.ones(3, "int32")
        self.cosmological_simulation = 1
        self.periodicity = (True, True, True)
        self.current_redshift = self.parameters["Redshift"]
        self.omega_lambda = self.parameters["OmegaLambda"]
        self.omega_matter = self.parameters["Omega0"]
        self.hubble_constant = self.parameters["HubbleParam"]
        cosmology = Cosmology(hubble_constant=self.hubble_constant,
                              omega_matter=self.omega_matter,
                              omega_lambda=self.omega_lambda)
        self.current_time = cosmology.t_from_z(self.current_redshift)

        prefix = os.path.abspath(
            os.path.join(os.path.dirname(self.parameter_filename), 
                         os.path.basename(self.parameter_filename).split(".", 1)[0]))
        suffix = self.parameter_filename.rsplit(".", 1)[-1]
        self.filename_template = "%s.%%(num)i.%s" % (prefix, suffix)
        self.file_count = self.parameters["NumFiles"]
        self.particle_types = ("Group", "Subhalo")
        self.particle_types_raw = ("Group", "Subhalo")
def find_radius_mass(m_r, delta, z=0.0, cosmo=None):
    """
    Given a mass profile and an overdensity, find the radius 
    and mass (e.g. M200, r200)

    Parameters
    ----------
    m_r : RadialProfile
        The mass profile.
    delta : float
        The overdensity to compute the mass and radius for.
    z : float, optional
        The redshift of the halo formation. Default: 0.0
    cosmo : yt ``Cosmology`` object
        The cosmology to be used when computing the critical
        density. If not supplied, a default one from yt will 
        be used.
    """
    from yt.utilities.cosmology import Cosmology
    from scipy.optimize import bisect
    if cosmo is None:
        cosmo = Cosmology()
    rho_crit = cosmo.critical_density(z).to_value("Msun/kpc**3")
    f = lambda r: 3.0*m_r(r)/(4.*np.pi*r**3) - delta*rho_crit
    r_delta = bisect(f, 0.01, 10000.0)
    return r_delta, m_r(r_delta)
def nfw_scale_density(conc, z=0.0, delta=200.0, cosmo=None):
    """
    Compute a scale density parameter for an NFW profile
    given a concentration parameter, and optionally
    a redshift, overdensity, and cosmology.

    Parameters
    ----------
    conc : float
        The concentration parameter for the halo, which should 
        correspond the selected overdensity (which has a default
        of 200). 
    z : float, optional
        The redshift of the halo formation. Default: 0.0
    delta : float, optional
        The overdensity parameter for which the concentration
        is defined. Default: 200.0
    cosmo : yt Cosmology object
        The cosmology to be used when computing the critical
        density. If not supplied, a default one from yt will 
        be used.
    """
    from yt.utilities.cosmology import Cosmology
    if cosmo is None:
        cosmo = Cosmology()
    rho_crit = cosmo.critical_density(z).to_value("Msun/kpc**3")
    rho_s = delta*rho_crit*conc**3*_nfw_factor(conc)/3.
    return rho_s
Esempio n. 8
0
    def _parse_parameter_file(self):
        self.dimensionality = 3
        self._periodicity = (True, True, True)
        self.refine_by = 2
        self.unique_identifier = \
            int(os.stat(self.parameter_filename)[stat.ST_CTIME])
        self.file_count = 1

        ct_file = CTHLMiniFile(self, self.parameter_filename)
        self.parameters.update(ct_file.parameters)

        for par in [
                'hubble_constant', 'omega_matter', 'omega_lambda',
                'current_redshift'
        ]:
            setattr(self, par, self.parameters.get(par))

        self.cosmological_simulation = 1
        co = Cosmology(hubble_constant=self.hubble_constant,
                       omega_matter=self.omega_matter,
                       omega_lambda=self.omega_lambda)
        self.current_time = co.t_from_z(self.current_redshift)
        self.domain_left_edge = np.zeros(self.dimensionality)
        self.domain_right_edge = float(self.parameters['box_size'][0]) * \
          np.ones(self.dimensionality)
        self.domain_dimensions = np.ones(self.dimensionality, "int32")
Esempio n. 9
0
def test_cosmology_calculator_answers():
    """
    Test cosmology calculator functions against previously calculated values.
    """

    fn = os.path.join(local_dir, 'cosmology_answers.yml')
    data = yaml.load(open(fn, 'r'), Loader=yaml.FullLoader)

    cosmologies = data['cosmologies']
    functions = data['functions']

    for cname, copars in cosmologies.items():
        omega_curvature = 1 - copars['omega_matter'] - \
          copars['omega_lambda'] - copars['omega_radiation']

        cosmology = Cosmology(omega_curvature=omega_curvature, **copars)

        for fname, finfo in functions.items():
            func = getattr(cosmology, fname)
            args = finfo.get('args', [])
            val = func(*args)
            units = finfo.get('units')
            if units is not None:
                val.convert_to_units(units)
            val = float(val)

            err_msg = '%s answer has changed for %s cosmology, old: %f, new: %f.' % \
              (fname, cname, finfo['answers'][cname], val)
            assert_almost_equal(
                val, finfo['answers'][cname], 10,
                err_msg=err_msg)
Esempio n. 10
0
    def set_units(self):
        """
        Creates the unit registry for this dataset.

        """
        from yt.units.dimensions import length
        if hasattr(self, "cosmological_simulation") \
           and getattr(self, "cosmological_simulation"):
            # this dataset is cosmological, so add cosmological units.
            self.unit_registry.modify("h", self.hubble_constant)
            # Comoving lengths
            for my_unit in ["m", "pc", "AU", "au"]:
                new_unit = "%scm" % my_unit
                self.unit_registry.add(
                    new_unit, self.unit_registry.lut[my_unit][0] /
                    (1 + self.current_redshift), length,
                    "\\rm{%s}/(1+z)" % my_unit)

        self.set_code_units()

        if hasattr(self, "cosmological_simulation") \
           and getattr(self, "cosmological_simulation"):
            # this dataset is cosmological, add a cosmology object
            setattr(
                self, "cosmology",
                Cosmology(hubble_constant=self.hubble_constant,
                          omega_matter=self.omega_matter,
                          omega_lambda=self.omega_lambda,
                          unit_registry=self.unit_registry))
            setattr(self, "critical_density",
                    self.cosmology.critical_density(self.current_redshift))
Esempio n. 11
0
    def _parse_parameter_file(self):
        with open(self.parameter_filename, "rb") as f:
            hvals = fpu.read_cattrs(f, header_dt)
            hvals.pop("unused")
        self.dimensionality = 3
        self.refine_by = 2
        prefix = ".".join(self.parameter_filename.rsplit(".", 2)[:-2])
        self.filename_template = "%s.%%(num)s%s" % (prefix, self._suffix)
        self.file_count = len(glob.glob(prefix + ".*" + self._suffix))

        # Now we can set up things we already know.
        self.cosmological_simulation = 1
        self.current_redshift = (1.0 / hvals["scale"]) - 1.0
        self.hubble_constant = hvals["h0"]
        self.omega_lambda = hvals["Ol"]
        self.omega_matter = hvals["Om"]
        cosmo = Cosmology(
            hubble_constant=self.hubble_constant,
            omega_matter=self.omega_matter,
            omega_lambda=self.omega_lambda,
        )
        self.current_time = cosmo.lookback_time(self.current_redshift,
                                                1e6).in_units("s")
        self.periodicity = (True, True, True)
        self.particle_types = "halos"
        self.particle_types_raw = "halos"

        self.domain_left_edge = np.array([0.0, 0.0, 0.0])
        self.domain_right_edge = np.array([hvals["box_size"]] * 3)

        self.domain_dimensions = np.ones(3, "int32")
        self.parameters.update(hvals)
Esempio n. 12
0
def get_base_ds(nprocs):
    fields, units = [], []

    for fname, (code_units, aliases, dn) in StreamFieldInfo.known_other_fields:
        fields.append(("gas", fname))
        units.append(code_units)

    ds = fake_random_ds(4,
                        fields=fields,
                        units=units,
                        particles=20,
                        nprocs=nprocs)
    ds.parameters["HydroMethod"] = "streaming"
    ds.parameters["EOSType"] = 1.0
    ds.parameters["EOSSoundSpeed"] = 1.0
    ds.conversion_factors["Time"] = 1.0
    ds.conversion_factors.update(dict((f, 1.0) for f in fields))
    ds.gamma = 5.0 / 3.0
    ds.current_redshift = 0.0001
    ds.cosmological_simulation = 1
    ds.hubble_constant = 0.7
    ds.omega_matter = 0.27
    ds.omega_lambda = 0.73
    ds.cosmology = Cosmology(hubble_constant=ds.hubble_constant,
                             omega_matter=ds.omega_matter,
                             omega_lambda=ds.omega_lambda,
                             unit_registry=ds.unit_registry)
    # ensures field errors are raised during testing
    # see FieldInfoContainer.check_derived_fields
    ds._field_test_dataset = True
    ds.index
    return ds
Esempio n. 13
0
    def __init__(self,
                 ds,
                 bcdir="",
                 model="chabrier",
                 time_now=None,
                 star_filter=None):
        self._ds = ds
        if not os.path.isdir(bcdir):
            bcdir = os.path.join(ytcfg.get("yt", "test_data_dir"), bcdir)
            if not os.path.isdir(bcdir):
                raise RuntimeError("Failed to locate %s" % bcdir)
        self.bcdir = bcdir
        self._filter = star_filter
        self.filter_provided = self._filter is not None
        if model == "chabrier":
            self.model = CHABRIER
        elif model == "salpeter":
            self.model = SALPETER
        # Set up for time conversion.
        self.cosm = Cosmology(hubble_constant=self._ds.hubble_constant,
                              omega_matter=self._ds.omega_matter,
                              omega_lambda=self._ds.omega_lambda)
        # Find the time right now.

        if time_now is None:
            self.time_now = self._ds.current_time
        else:
            self.time_now = time_now

        # Read the tables.
        self.read_bclib()
Esempio n. 14
0
def read_caesar(c_file, selected_gals):
    print('Reading caesar file...')
    sim = caesar.load(c_file, LoadHalo=False)
    redshift = np.round(sim.simulation.redshift, decimals=2)
    h = sim.simulation.hubble_constant
    cosmo = Cosmology(hubble_constant=sim.simulation.hubble_constant,
                      omega_matter=sim.simulation.omega_matter,
                      omega_lambda=sim.simulation.omega_lambda,
                      omega_curvature=0)
    thubble = cosmo.hubble_time(redshift).in_units("Gyr")
    H0 = (100 * sim.simulation.hubble_constant) * km / s / Mpc
    rhocrit = 3. * H0.to('1/s')**2 / (8 * np.pi * sim.simulation.G)
    mlim = 32 * rhocrit.to('Msun/kpc**3') * sim.simulation.boxsize.to(
        'kpc'
    )**3 * sim.simulation.omega_baryon / sim.simulation.effective_resolution**3 / sim.simulation.scale_factor**3  # galaxy mass resolution limit: 32 gas particle masses

    gals = np.array([])
    # read galaxy particle data for the selected galaxies
    if isinstance(selected_gals, np.ndarray):
        gals = np.asarray([
            i for i in sim.galaxies
            if i.GroupID in selected_gals and i.masses['stellar'] > mlim
        ])  # select resolved galaxies
    print('Galaxy data from caesar file extracted and saved.')
    return sim, redshift, h, cosmo, thubble, H0, rhocrit, mlim, gals
Esempio n. 15
0
    def _set_units(self):
        """
        Set "cm" units for explicitly comoving.
        Note, we are using comoving units all the time since
        we are dealing with data at multiple redshifts.
        """
        for my_unit in ["m", "pc", "AU"]:
            new_unit = f"{my_unit}cm"
            self.unit_registry.add(
                new_unit, self.unit_registry.lut[my_unit][0],
                length, self.unit_registry.lut[my_unit][3])

        setup = True
        for attr in ["hubble_constant",
                     "omega_matter",
                     "omega_lambda"]:
            if getattr(self, attr) is None:
                setup = False
                ytreeLogger.warning(
                    f"{attr} missing from data. "
                    "Arbor will have no cosmology calculator.")

        if setup:
            self.cosmology = Cosmology(
                hubble_constant=self.hubble_constant,
                omega_matter=self.omega_matter,
                omega_lambda=self.omega_lambda,
                omega_radiation=self.omega_radiation,
                unit_registry=self.unit_registry)
Esempio n. 16
0
    def _parse_parameter_file(self):
        with open(self.parameter_filename, "rb") as f:
            hvals = fpu.read_cattrs(f, header_dt)
            hvals.pop("unused")
        self.dimensionality = 3
        self.refine_by = 2
        self.unique_identifier = \
            int(os.stat(self.parameter_filename)[stat.ST_CTIME])
        prefix = ".".join(self.parameter_filename.rsplit(".", 2)[:-2])
        self.filename_template = "%s.%%(num)s%s" % (prefix, self._suffix)
        self.file_count = len(glob.glob(prefix + ".*" + self._suffix))

        # Now we can set up things we already know.
        self.cosmological_simulation = 1
        self.current_redshift = (1.0 / hvals['scale']) - 1.0
        self.hubble_constant = hvals['h0']
        self.omega_lambda = hvals['Ol']
        self.omega_matter = hvals['Om']
        cosmo = Cosmology(self.hubble_constant, self.omega_matter,
                          self.omega_lambda)
        self.current_time = cosmo.hubble_time(
            self.current_redshift).in_units("s")
        self.periodicity = (True, True, True)
        self.particle_types = ("halos")
        self.particle_types_raw = ("halos")

        self.domain_left_edge = np.array([0.0, 0.0, 0.0])
        self.domain_right_edge = np.array([hvals['box_size']] * 3)

        nz = 1 << self.over_refine_factor
        self.domain_dimensions = np.ones(3, "int32") * nz
        self.parameters.update(hvals)
Esempio n. 17
0
def find_virial_radius(ds,center):
    z = ds.current_redshift

    co = Cosmology(hubble_constant=ds.hubble_constant, omega_matter=ds.omega_matter,
                   omega_lambda=ds.omega_lambda, omega_curvature=0.0)
    rho_c = co.critical_density(z=z)
    
    r = 0
    rs = []
    densities = []
    density = np.inf
    while density > 200*rho_c:
        r+=5
        rs.append(r)
        sp = ds.sphere(center,(r,'kpc'))
        cell_mass,particle_mass = sp.quantities.total_mass()
        volume = 4/3*np.pi*ds.arr(r,'kpc')**3
        new_density = (cell_mass+particle_mass)/volume
        if new_density > density:
            print('density not decreasing!')
            break
        density = new_density.in_units('g/cm**3')
        densities.append(density)
        toprint = (r,cell_mass+particle_mass,(cell_mass+particle_mass).units,particle_mass,particle_mass.units,cell_mass,cell_mass.units)
    rs = np.array(rs)
    densities = np.array(densities)
    Rvir = np.interp(200*rho_c,np.flip(densities),np.flip(rs))
    Mvir = cell_mass+particle_mass
    return ds.arr(Rvir,'kpc'),ds.arr(Mvir,'g')
Esempio n. 18
0
def realistic_ds(fields, particle_fields, nprocs):
    np.random.seed(int(0x4d3d3d3))
    units = [base_ds._get_field_info(*f).units for f in fields]
    punits = [base_ds._get_field_info('io', f).units for f in particle_fields]
    fields = [_strip_ftype(f) for f in fields]

    ds = fake_random_ds(16,
                        fields=fields,
                        units=units,
                        nprocs=nprocs,
                        particle_fields=particle_fields,
                        particle_field_units=punits,
                        particles=base_ds.stream_handler.particle_count[0][0])

    ds.parameters["HydroMethod"] = "streaming"
    ds.parameters["EOSType"] = 1.0
    ds.parameters["EOSSoundSpeed"] = 1.0
    ds.conversion_factors["Time"] = 1.0
    ds.conversion_factors.update(dict((f, 1.0) for f in fields))
    ds.gamma = 5.0 / 3.0
    ds.current_redshift = 0.0001
    ds.cosmological_simulation = 1
    ds.hubble_constant = 0.7
    ds.omega_matter = 0.27
    ds.omega_lambda = 0.73
    ds.cosmology = Cosmology(hubble_constant=ds.hubble_constant,
                             omega_matter=ds.omega_matter,
                             omega_lambda=ds.omega_lambda,
                             unit_registry=ds.unit_registry)
    return ds
Esempio n. 19
0
    def _set_code_unit_attributes(self):
        # First try to set units based on parameter file
        if self.cosmological_simulation:
            mu = self.parameters.get("dMsolUnit", 1.0)
            self.mass_unit = self.quan(mu, "Msun")
            lu = self.parameters.get("dKpcUnit", 1000.0)
            # In cosmological runs, lengths are stored as length*scale_factor
            self.length_unit = self.quan(lu, "kpc") * self.scale_factor
            density_unit = self.mass_unit / (self.length_unit / self.scale_factor) ** 3
            if "dHubble0" in self.parameters:
                # Gasoline's internal hubble constant, dHubble0, is stored in
                # units of proper code time
                self.hubble_constant *= np.sqrt(G * density_unit)
                # Finally, we scale the hubble constant by 100 km/s/Mpc
                self.hubble_constant /= self.quan(100, "km/s/Mpc")
                # If we leave it as a YTQuantity, the cosmology object
                # used below will add units back on.
                self.hubble_constant = self.hubble_constant.to_value("")
        else:
            mu = self.parameters.get("dMsolUnit", 1.0)
            self.mass_unit = self.quan(mu, "Msun")
            lu = self.parameters.get("dKpcUnit", 1.0)
            self.length_unit = self.quan(lu, "kpc")

        # If unit base is defined by the user, override all relevant units
        if self._unit_base is not None:
            for my_unit in ["length", "mass", "time"]:
                if my_unit in self._unit_base:
                    my_val = self._unit_base[my_unit]
                    my_val = (
                        self.quan(*my_val)
                        if isinstance(my_val, tuple)
                        else self.quan(my_val)
                    )
                    setattr(self, f"{my_unit}_unit", my_val)

        # Finally, set the dependent units
        if self.cosmological_simulation:
            cosmo = Cosmology(
                hubble_constant=self.hubble_constant,
                omega_matter=self.omega_matter,
                omega_lambda=self.omega_lambda,
            )
            self.current_time = cosmo.lookback_time(self.current_redshift, 1e6)
            # mass units are rho_crit(z=0) * domain volume
            mu = (
                cosmo.critical_density(0.0)
                * (1 + self.current_redshift) ** 3
                * self.length_unit ** 3
            )
            self.mass_unit = self.quan(mu.in_units("Msun"), "Msun")
            density_unit = self.mass_unit / (self.length_unit / self.scale_factor) ** 3
            # need to do this again because we've modified the hubble constant
            self.unit_registry.modify("h", self.hubble_constant)
        else:
            density_unit = self.mass_unit / self.length_unit ** 3

        if not hasattr(self, "time_unit"):
            self.time_unit = 1.0 / np.sqrt(density_unit * G)
Esempio n. 20
0
    def __init__(self,
                 ds,
                 data_source=None,
                 star_mass=None,
                 star_creation_time=None,
                 bins=300,
                 volume=None,
                 star_filter=None):
        self._ds = ds
        self._data_source = data_source
        self._filter = star_filter
        self.ds_provided = self._data_source is not None
        self.filter_provided = self._filter is not None
        self.bin_count = bins

        # Set up for time conversion.
        self.cosm = Cosmology(hubble_constant=self._ds.hubble_constant,
                              omega_matter=self._ds.omega_matter,
                              omega_lambda=self._ds.omega_lambda)
        # Find the time right now.
        self.time_now = self._ds.current_time

        if not self.ds_provided:
            # Check to make sure we have the right set of informations.
            if star_mass is None or star_creation_time is None \
                    or volume is None:
                mylog.error("""
                    If data_source is not provided, all of these parameters
                    need to be set:
                        star_mass (array, Msun),
                        star_creation_time (array, code units),
                        volume (float, cMpc**3).""")
                return None

            if isinstance(star_mass, YTArray):
                assert star_mass.units.same_dimensions_as(g.units)
            elif star_mass is not None:
                star_mass = YTArray(star_mass, 'Msun')
            self.star_mass = star_mass

            if isinstance(star_creation_time, YTArray):
                assert star_creation_time.units.same_dimensions_as(s.units)
            elif star_creation_time is not None:
                star_creation_time = self._ds.arr(star_creation_time,
                                                  'code_time')
            self.star_creation_time = star_creation_time

            if isinstance(volume, YTQuantity):
                assert volume.units.same_dimensions_as(
                    self._ds.quan(1.0, 'Mpccm**3').units)
            elif volume is not None:
                volume = self._ds.quan(volume, 'Mpccm**3')
            self.volume = volume

        # Build the distribution.
        self.build_dist()
        # Attach some convenience arrays.
        self.attach_arrays()
Esempio n. 21
0
def test_z_t_analytic():
    """
    Test z/t conversions against analytic solutions.
    """

    cosmos = (
        {
            "hubble_constant": 0.7,
            "omega_matter": 0.3,
            "omega_lambda": 0.7
        },
        {
            "hubble_constant": 0.7,
            "omega_matter": 1.0,
            "omega_lambda": 0.0
        },
        {
            "hubble_constant": 0.7,
            "omega_matter": 0.3,
            "omega_lambda": 0.0
        },
    )

    for cosmo in cosmos:
        omega_curvature = 1 - cosmo["omega_matter"] - cosmo["omega_lambda"]
        co = Cosmology(omega_curvature=omega_curvature, **cosmo)
        # random sample in log(a) from -6 to 6
        my_random = np.random.RandomState(10132324)
        la = 12 * my_random.random_sample(1000) - 6
        z = 1 / np.power(10, la) - 1

        t_an = t_from_z_analytic(z, **cosmo).to("Gyr")
        t_co = co.t_from_z(z).to("Gyr")

        assert_rel_equal(
            t_an,
            t_co,
            4,
            err_msg=
            f"t_from_z does not match analytic version for cosmology {cosmo}.",
        )

        # random sample in log(t/t0) from -3 to 1
        t0 = np.power(10, 4 * my_random.random_sample(1000) - 3)
        t = (t0 / co.hubble_constant).to("Gyr")

        z_an = z_from_t_analytic(t, **cosmo)
        z_co = co.z_from_t(t)

        # compare scale factors since z approaches 0
        assert_rel_equal(
            1 / (1 + z_an),
            1 / (1 + z_co),
            5,
            err_msg=
            f"z_from_t does not match analytic version for cosmology {cosmo}.",
        )
 def _set_units(self):
     self.unit_registry = UnitRegistry()
     self.time_unit = self.quan(1.0, "s")
     if self.cosmological_simulation:
         # Instantiate Cosmology object for units and time conversions.
         self.cosmology = Cosmology(
             hubble_constant=self.hubble_constant,
             omega_matter=self.omega_matter,
             omega_lambda=self.omega_lambda,
             unit_registry=self.unit_registry,
         )
         if "h" in self.unit_registry:
             self.unit_registry.modify("h", self.hubble_constant)
         else:
             self.unit_registry.add("h", self.hubble_constant,
                                    dimensions.dimensionless)
         # Comoving lengths
         for my_unit in ["m", "pc", "AU"]:
             new_unit = f"{my_unit}cm"
             # technically not true, but should be ok
             self.unit_registry.add(
                 new_unit,
                 self.unit_registry.lut[my_unit][0],
                 dimensions.length,
                 "\\rm{%s}/(1+z)" % my_unit,
                 prefixable=True,
             )
         self.length_unit = self.quan(
             self.unit_base["UnitLength_in_cm"],
             "cmcm / h",
             registry=self.unit_registry,
         )
         self.mass_unit = self.quan(self.unit_base["UnitMass_in_g"],
                                    "g / h",
                                    registry=self.unit_registry)
         self.box_size = self.box_size * self.length_unit
         self.domain_left_edge = self.domain_left_edge * self.length_unit
         self.domain_right_edge = self.domain_right_edge * self.length_unit
         self.unit_registry.add(
             "unitary",
             float(self.box_size.in_base()),
             self.length_unit.units.dimensions,
         )
     else:
         # Read time from file for non-cosmological sim
         self.time_unit = self.quan(
             self.unit_base["UnitLength_in_cm"] /
             self.unit_base["UnitVelocity_in_cm_per_s"],
             "s",
         )
         self.unit_registry.add("code_time", 1.0, dimensions.time)
         self.unit_registry.modify("code_time", self.time_unit)
         # Length
         self.length_unit = self.quan(self.unit_base["UnitLength_in_cm"],
                                      "cm")
         self.unit_registry.add("code_length", 1.0, dimensions.length)
         self.unit_registry.modify("code_length", self.length_unit)
    def __init__(self, parameter_filename, simulation_type, find_outputs=False):
        self.parameter_filename = parameter_filename
        self.simulation_type = simulation_type
        self.simulation = simulation(parameter_filename, simulation_type, 
                                     find_outputs=find_outputs)

        self.cosmology = Cosmology(
            hubble_constant=(self.simulation.hubble_constant),
            omega_matter=self.simulation.omega_matter,
            omega_lambda=self.simulation.omega_lambda)
Esempio n. 24
0
def test_dark_factor():
    """
    Test that dark factor returns same value for when not
    being used and when w_0 = -1 and w_z = 0.
    """

    co = Cosmology(w_0=-1, w_a=0, use_dark_factor=False)

    assert_equal(co.get_dark_factor(0), 1.0)
    co.use_dark_factor = True
    assert_equal(co.get_dark_factor(0), 1.0)
Esempio n. 25
0
def test_hubble_time():
    """
    Make sure hubble_time and t_from_z functions agree.

    """

    for i in range(10):
        co = Cosmology()
        # random sample over interval (-1,100]
        z = -101 * np.random.random() + 100
        assert_rel_equal(co.hubble_time(z), co.t_from_z(z), 5)
Esempio n. 26
0
def set_up_gizmo(ds):
    def star_mass_rename(field, data):
        return data['PartType4', 'particle_mass']

    ds.add_field(('stars', 'particle_mass'),
                 sampling_type='particle',
                 function=star_mass_rename,
                 units='g')

    ad = ds.all_data()
    m1 = ad['PartType1', 'Masses']
    unique_dm1_masses = np.unique(m1)
    m2 = ad['PartType2', 'Masses']
    unique_dm2_masses = np.unique(m2)

    def dm_filter(pfilter, data):
        allowed = np.zeros(data[pfilter.filtered_type, 'Masses'].shape,
                           dtype=bool)
        for v in ds.arr(
                np.concatenate([unique_dm1_masses, unique_dm2_masses]).v,
                m2.units):
            allowed = np.logical_or(allowed, data[pfilter.filtered_type,
                                                  'Masses'] == v)
        return allowed

    add_particle_filter('darkmatter',
                        function=dm_filter,
                        filtered_type='all',
                        requires=['Masses'])
    ds.add_particle_filter('darkmatter')

    co = Cosmology(hubble_constant=ds.hubble_constant,
                   omega_matter=ds.omega_matter,
                   omega_lambda=ds.omega_lambda,
                   omega_curvature=0.0)

    def particle_creation_time_rename(field, data):
        return co.t_from_a(data['PartType4', 'StellarFormationTime'])

    ds.add_field(('stars', 'particle_creation_time'),
                 sampling_type='particle',
                 function=particle_creation_time_rename,
                 units='s')

    def metal_density(field, data):
        return data['gas', 'metallicity'] * data['gas', 'density']

    ds.add_field(('gas', 'metal_density'),
                 sampling_type='particle',
                 function=metal_density,
                 units='g/cm**3')
    alias_default_velocities(ds, 'PartType0', 'particle')
Esempio n. 27
0
def test_z_t_conversion():
    """
    Make sure t_from_z and z_from_t are consistent.

    """

    for i in range(10):
        co = Cosmology()
        # random sample over interval (-1,100]
        z1 = -101 * np.random.random() + 100
        t = co.t_from_z(z1)
        z2 = co.z_from_t(t)
        assert_rel_equal(z1, z2, 10)
Esempio n. 28
0
def set_up_gadget(ds):
    def star_mass_rename(field, data):
        return data['PartType4', 'particle_mass']

    ds.add_field(('stars', 'particle_mass'),
                 sampling_type='particle',
                 function=star_mass_rename,
                 units='g')

    ad = ds.all_data()
    m1 = ad['PartType1', 'Masses']
    assert np.amin(m1) == np.amax(m1)
    unique_dm1_mass = np.amin(m1)
    m5 = ad['PartType5', 'Masses']
    unique_dm5_masses = np.unique(m5)

    def dm_filter(pfilter, data):
        allowed = data[pfilter.filtered_type, 'Masses'] == unique_dm1_mass
        for v in unique_dm5_masses:
            allowed = np.logical_or(allowed, data[pfilter.filtered_type,
                                                  'Masses'] == v)
        return allowed

    add_particle_filter('darkmatter',
                        function=dm_filter,
                        filtered_type='all',
                        requires=['Masses'])
    ds.add_particle_filter('darkmatter')

    co = Cosmology(hubble_constant=ds.hubble_constant,
                   omega_matter=ds.omega_matter,
                   omega_lambda=ds.omega_lambda,
                   omega_curvature=0.0)

    def particle_creation_time_rename(field, data):
        return co.t_from_a(data['PartType4', 'StellarFormationTime'])

    ds.add_field(('stars', 'particle_creation_time'),
                 sampling_type='particle',
                 function=particle_creation_time_rename,
                 units='s')

    def metal_density(field, data):
        return data['gas', 'metallicity'] * data['gas', 'density']

    ds.add_field(('gas', 'metal_density'),
                 sampling_type='particle',
                 function=metal_density,
                 units='g/cm**3')
    alias_default_velocities(ds, 'PartType0', 'particle')
Esempio n. 29
0
def test_z_t_roundtrip():
    """
    Make sure t_from_z and z_from_t are consistent.

    """

    co = Cosmology()
    # random sample in log(a) from -6 to 6
    my_random = np.random.RandomState(6132305)
    la = 12 * my_random.random_sample(10000) - 6
    z1 = 1 / np.power(10, la) - 1
    t = co.t_from_z(z1)
    z2 = co.z_from_t(t)
    assert_rel_equal(z1, z2, 4)
Esempio n. 30
0
def test_dataset_cosmology_calculator():
    """
    Test datasets's cosmology calculator against standalone.
    """

    ds = data_dir_load(enzotiny)

    co = Cosmology(hubble_constant=ds.hubble_constant,
                   omega_matter=ds.omega_matter,
                   omega_lambda=ds.omega_lambda)

    v1 = ds.cosmology.comoving_radial_distance(1, 5).to('Mpccm').v
    v2 = co.comoving_radial_distance(1, 5).to('Mpccm').v
    assert_equal(v1, v2)