Esempio n. 1
0
 def _set_code_unit_attributes(self):
     """
     Generates the conversion to various physical _units based on the parameter file
     """
     for unit, cgs in [("length", "cm"), ("time", "s"), ("mass", "g"),
                       ("velocity", "cm/s"), ("magnetic", "gauss")]:
         if unit == "magnetic":
             short_unit = "bfunit"
         else:
             short_unit = "%sunit" % unit[0]
         if short_unit in self.primary_header:
             # units should now be in header
             u = self.quan(self.primary_header[short_unit],
                           self.primary_header.comments[short_unit].strip("[]"))
             mylog.info("Found %s units of %s." % (unit, u))
         else:
             if unit == "length":
                 # Falling back to old way of getting units for length
                 # in old files
                 u = self.quan(1.0, str(self.wcs.wcs.cunit[0]))
                 mylog.info("Found %s units of %s." % (unit, u))
             else:
                 # Give up otherwise
                 u = self.quan(1.0, cgs)
                 mylog.warning("No unit for %s found. Assuming 1.0 code_%s = 1.0 %s" % (unit, unit, cgs))
         setdefaultattr(self, '%s_unit' % unit, u)
Esempio n. 2
0
    def _set_code_unit_attributes(self):
        if self.parameters['Opt__Unit']:
            # GAMER units are always in CGS
            setdefaultattr(self, 'length_unit',
                           self.quan(self.parameters['Unit_L'], 'cm'))
            setdefaultattr(self, 'mass_unit',
                           self.quan(self.parameters['Unit_M'], 'g'))
            setdefaultattr(self, 'time_unit',
                           self.quan(self.parameters['Unit_T'], 's'))

            if self.mhd:
                setdefaultattr(self, 'magnetic_unit',
                               self.quan(self.parameters['Unit_B'], 'gauss'))

        else:
            if len(self.units_override) == 0:
                mylog.warning("Cannot determine code units ==> " +
                              "Use units_override to specify the units")

            for unit, value, cgs in [("length", 1.0, "cm"), ("time", 1.0, "s"),
                                     ("mass", 1.0, "g"),
                                     ("magnetic", np.sqrt(4.0 * np.pi),
                                      "gauss")]:
                setdefaultattr(self, "%s_unit" % unit, self.quan(value, cgs))

                if len(self.units_override) == 0:
                    mylog.warning("Assuming %8s unit = %f %s", unit, value,
                                  cgs)
Esempio n. 3
0
    def _set_code_unit_attributes(self):
        if self.parameters["Opt__Unit"]:
            # GAMER units are always in CGS
            setdefaultattr(
                self, "length_unit", self.quan(self.parameters["Unit_L"], "cm")
            )
            setdefaultattr(self, "mass_unit", self.quan(self.parameters["Unit_M"], "g"))
            setdefaultattr(self, "time_unit", self.quan(self.parameters["Unit_T"], "s"))

            if self.mhd:
                setdefaultattr(
                    self, "magnetic_unit", self.quan(self.parameters["Unit_B"], "gauss")
                )

        else:
            if len(self.units_override) == 0:
                mylog.warning(
                    "Cannot determine code units ==> "
                    "Use units_override to specify the units"
                )

            for unit, value, cgs in [
                ("length", 1.0, "cm"),
                ("time", 1.0, "s"),
                ("mass", 1.0, "g"),
                ("magnetic", np.sqrt(4.0 * np.pi), "gauss"),
            ]:
                setdefaultattr(self, f"{unit}_unit", self.quan(value, cgs))

                if len(self.units_override) == 0:
                    mylog.warning("Assuming %8s unit = %f %s", unit, value, cgs)
Esempio n. 4
0
    def _set_code_unit_attributes(self):
        """
        Generates the conversion to various physical _units
        based on the parameter file
        """

        # This should be improved.
        h5f = h5py.File(self.parameter_filename, mode="r")
        for field_name in h5f["/field_types"]:
            current_field = h5f[f"/field_types/{field_name}"]
            if "field_to_cgs" in current_field.attrs:
                field_conv = current_field.attrs["field_to_cgs"]
                self.field_units[field_name] = just_one(field_conv)
            elif "field_units" in current_field.attrs:
                field_units = current_field.attrs["field_units"]
                if isinstance(field_units, str):
                    current_field_units = current_field.attrs["field_units"]
                else:
                    current_field_units = just_one(
                        current_field.attrs["field_units"])
                self.field_units[field_name] = current_field_units.decode(
                    "utf8")
            else:
                self.field_units[field_name] = ""

        if "dataset_units" in h5f:
            for unit_name in h5f["/dataset_units"]:
                current_unit = h5f[f"/dataset_units/{unit_name}"]
                value = current_unit[()]
                unit = current_unit.attrs["unit"]
                # need to convert to a Unit object and check dimensions
                # because unit can be things like
                # 'dimensionless/dimensionless**3' so naive string
                # comparisons are insufficient
                unit = Unit(unit, registry=self.unit_registry)
                if unit_name.endswith(
                        "_unit") and unit.dimensions is sympy_one:
                    # Catch code units and if they are dimensionless,
                    # assign CGS units. setdefaultattr will catch code units
                    # which have already been set via units_override.
                    un = unit_name[:-5]
                    un = un.replace("magnetic", "magnetic_field_cgs", 1)
                    unit = unit_system_registry["cgs"][un]
                    setdefaultattr(self, unit_name, self.quan(value, unit))
                setdefaultattr(self, unit_name, self.quan(value, unit))
                if unit_name in h5f["/field_types"]:
                    if unit_name in self.field_units:
                        mylog.warning(
                            "'field_units' was overridden by 'dataset_units/%s'",
                            unit_name,
                        )
                    self.field_units[unit_name] = str(unit)
        else:
            setdefaultattr(self, "length_unit", self.quan(1.0, "cm"))
            setdefaultattr(self, "mass_unit", self.quan(1.0, "g"))
            setdefaultattr(self, "time_unit", self.quan(1.0, "s"))

        h5f.close()
Esempio n. 5
0
    def _set_code_unit_attributes(self):
        """
        Generates the conversion to various physical _units
        based on the parameter file
        """

        # This should be improved.
        h5f = h5py.File(self.parameter_filename, "r")
        for field_name in h5f["/field_types"]:
            current_field = h5f["/field_types/%s" % field_name]
            if 'field_to_cgs' in current_field.attrs:
                field_conv = current_field.attrs['field_to_cgs']
                self.field_units[field_name] = just_one(field_conv)
            elif 'field_units' in current_field.attrs:
                field_units = current_field.attrs['field_units']
                if isinstance(field_units, string_types):
                    current_field_units = current_field.attrs['field_units']
                else:
                    current_field_units = \
                        just_one(current_field.attrs['field_units'])
                self.field_units[field_name] = current_field_units.decode(
                    "utf8")
            else:
                self.field_units[field_name] = ""

        if "dataset_units" in h5f:
            for unit_name in h5f["/dataset_units"]:
                current_unit = h5f["/dataset_units/%s" % unit_name]
                value = current_unit.value
                unit = current_unit.attrs["unit"]
                # need to convert to a Unit object and check dimensions
                # because unit can be things like
                # 'dimensionless/dimensionless**3' so naive string
                # comparisons are insufficient
                unit = Unit(unit, registry=self.unit_registry)
                if unit_name.endswith(
                        '_unit') and unit.dimensions is sympy_one:
                    un = unit_name[:-5]
                    un = un.replace('magnetic', 'magnetic_field', 1)
                    unit = self.unit_system[un]
                    setdefaultattr(self, unit_name, self.quan(value, unit))
                setdefaultattr(self, unit_name, self.quan(value, unit))
                if unit_name in h5f["/field_types"]:
                    if unit_name in self.field_units:
                        mylog.warning(
                            "'field_units' was overridden by 'dataset_units/%s'"
                            % (unit_name))
                    self.field_units[unit_name] = str(unit)
        else:
            setdefaultattr(self, 'length_unit', self.quan(1.0, "cm"))
            setdefaultattr(self, 'mass_unit', self.quan(1.0, "g"))
            setdefaultattr(self, 'time_unit', self.quan(1.0, "s"))

        h5f.close()
Esempio n. 6
0
    def _set_code_unit_attributes(self):
        # GAMER does not assume any unit yet ...
        if len(self.units_override) == 0:
            mylog.warning("GAMER does not assume any unit ==> " +
                          "Use units_override to specify the units")

        for unit, cgs in [("length", "cm"), ("time", "s"), ("mass", "g")]:
            setdefaultattr(self, "%s_unit" % unit, self.quan(1.0, cgs))

            if len(self.units_override) == 0:
                mylog.warning("Assuming 1.0 = 1.0 %s", cgs)
Esempio n. 7
0
    def _set_code_unit_attributes(self):
        """Handle conversion between different physical units and the code units.

        Every dataset in openPMD can have different code <-> physical scaling.
        The individual factor is obtained by multiplying with "unitSI" reading getting data from disk.
        """
        setdefaultattr(self, "length_unit", self.quan(1.0, "m"))
        setdefaultattr(self, "mass_unit", self.quan(1.0, "kg"))
        setdefaultattr(self, "time_unit", self.quan(1.0, "s"))
        setdefaultattr(self, "velocity_unit", self.quan(1.0, "m/s"))
        setdefaultattr(self, "magnetic_unit", self.quan(1.0, "T"))
Esempio n. 8
0
 def _set_code_unit_attributes(self):
     setdefaultattr(self, 'length_unit', self.quan(1, "cm"))
     setdefaultattr(self, 'mass_unit', self.quan(1, "g"))
     setdefaultattr(self, 'time_unit', self.quan(1, "s"))
     setdefaultattr(self, 'velocity_unit',
                    self.length_unit / self.time_unit)
     magnetic_unit = np.sqrt(4 * np.pi * self.mass_unit /
                             (self.time_unit**2 * self.length_unit))
     magnetic_unit = np.float64(magnetic_unit.in_cgs())
     setdefaultattr(self, 'magnetic_unit',
                    self.quan(magnetic_unit, "gauss"))
Esempio n. 9
0
    def _set_code_unit_attributes(self):
        """
        Generates the conversion to various physical units based
                on the parameters from the header
        """

        # spatial units
        z = self.current_redshift
        h = self.hubble_constant
        boxcm_cal = self.parameters["boxh"]
        boxcm_uncal = boxcm_cal / h
        box_proper = boxcm_uncal / (1 + z)
        aexpn = self.parameters["aexpn"]

        # all other units
        Om0 = self.parameters['Om0']
        ng = self.parameters['ng']
        boxh = self.parameters['boxh']
        aexpn = self.parameters["aexpn"]
        hubble = self.parameters['hubble']

        r0 = boxh / ng
        v0 = 50.0 * r0 * np.sqrt(Om0)
        rho0 = 2.776e11 * hubble**2.0 * Om0
        aM0 = rho0 * (boxh / hubble)**3.0 / ng**3.0
        velocity = v0 / aexpn * 1.0e5  # proper cm/s
        mass = aM0 * 1.98892e33

        self.cosmological_simulation = True
        setdefaultattr(self, 'mass_unit', self.quan(mass, "g*%s" % ng**3))
        setdefaultattr(self, 'length_unit', self.quan(box_proper, "Mpc"))
        setdefaultattr(self, 'velocity_unit', self.quan(velocity, "cm/s"))
        setdefaultattr(self, 'time_unit',
                       self.length_unit / self.velocity_unit)
Esempio n. 10
0
    def _set_code_unit_attributes(self):
        # Set a sane default for cosmological simulations.
        if self._unit_base is None and self.cosmological_simulation == 1:
            only_on_root(mylog.info,
                         "Assuming length units are in Mpc/h (comoving)")
            self._unit_base = dict(length=(1.0, "Mpccm/h"))
        # The other same defaults we will use from the standard Gadget
        # defaults.
        unit_base = self._unit_base or {}

        if "length" in unit_base:
            length_unit = unit_base["length"]
        elif "UnitLength_in_cm" in unit_base:
            if self.cosmological_simulation == 0:
                length_unit = (unit_base["UnitLength_in_cm"], "cm")
            else:
                length_unit = (unit_base["UnitLength_in_cm"], "cmcm/h")
        else:
            raise RuntimeError
        length_unit = _fix_unit_ordering(length_unit)
        setdefaultattr(self, 'length_unit',
                       self.quan(length_unit[0], length_unit[1]))

        if "velocity" in unit_base:
            velocity_unit = unit_base["velocity"]
        elif "UnitVelocity_in_cm_per_s" in unit_base:
            velocity_unit = (unit_base["UnitVelocity_in_cm_per_s"], "cm/s")
        else:
            if self.cosmological_simulation == 0:
                velocity_unit = (1e5, "cm/s")
            else:
                velocity_unit = (1e5, "cmcm/s")
        velocity_unit = _fix_unit_ordering(velocity_unit)
        setdefaultattr(self, 'velocity_unit',
                       self.quan(velocity_unit[0], velocity_unit[1]))

        # We set hubble_constant = 1.0 for non-cosmology, so this is safe.
        # Default to 1e10 Msun/h if mass is not specified.
        if "mass" in unit_base:
            mass_unit = unit_base["mass"]
        elif "UnitMass_in_g" in unit_base:
            if self.cosmological_simulation == 0:
                mass_unit = (unit_base["UnitMass_in_g"], "g")
            else:
                mass_unit = (unit_base["UnitMass_in_g"], "g/h")
        else:
            # Sane default
            mass_unit = (1.0, "1e10*Msun/h")
        mass_unit = _fix_unit_ordering(mass_unit)
        setdefaultattr(self, 'mass_unit', self.quan(mass_unit[0],
                                                    mass_unit[1]))

        if "time" in unit_base:
            time_unit = unit_base["time"]
        elif "UnitTime_in_s" in unit_base:
            time_unit = (unit_base["UnitTime_in_s"], "s")
        else:
            time_unit = (1., "s")
        setdefaultattr(self, 'time_unit', self.quan(time_unit[0],
                                                    time_unit[1]))
Esempio n. 11
0
 def _set_code_unit_attributes(self):
     if not hasattr(self, 'length_unit'):
         mylog.warning("Setting code length unit to be 1.0 cm")
     if not hasattr(self, 'mass_unit'):
         mylog.warning("Setting code mass unit to be 1.0 g")
     if not hasattr(self, 'time_unit'):
         mylog.warning("Setting code time unit to be 1.0 s")
     setdefaultattr(self, 'length_unit', self.quan(1.0, "cm"))
     setdefaultattr(self, 'mass_unit', self.quan(1.0, "g"))
     setdefaultattr(self, 'time_unit', self.quan(1.0, "s"))
     setdefaultattr(self, 'magnetic_unit',
                    self.quan(np.sqrt(4. * np.pi), "gauss"))
     setdefaultattr(self, 'velocity_unit',
                    self.length_unit / self.time_unit)
Esempio n. 12
0
 def _set_code_unit_attributes(self):
     setdefaultattr(self, "length_unit",
                    self.quan(self._code_length_to_Mpc, "Mpc"))
     setdefaultattr(self, "mass_unit", self.quan(1e11, "Msun"))
     setdefaultattr(self, "velocity_unit", self.quan(1.0, "km / s"))
     setdefaultattr(self, "time_unit",
                    self.length_unit / self.velocity_unit)
Esempio n. 13
0
 def _set_code_unit_attributes(self):
     setdefaultattr(self, 'mass_unit', self.quan(1.0, "Msun"))
     setdefaultattr(self, 'time_unit', self.quan(1.0 / 3.08568025e19, "s"))
     setdefaultattr(self, 'length_unit',
                    self.quan(1.0 / (1 + self.current_redshift), "Mpc"))
     setdefaultattr(self, 'velocity_unit',
                    self.length_unit / self.time_unit)
Esempio n. 14
0
 def _set_code_unit_attributes(self):
     z = self.current_redshift
     setdefaultattr(self, 'length_unit',
                    self.quan(1.0 / (1.0 + z), "Mpc / h"))
     setdefaultattr(self, 'mass_unit', self.quan(1.0, "Msun / h"))
     setdefaultattr(self, 'velocity_unit', self.quan(1.0, "km / s"))
     setdefaultattr(self, 'time_unit',
                    self.length_unit / self.velocity_unit)
Esempio n. 15
0
 def _set_code_unit_attributes(self):
     setdefaultattr(
         self, 'mass_unit', self.quan(self.parameters["unit_m"], "g"))
     setdefaultattr(
         self, 'length_unit', self.quan(self.parameters["unit_l"], "cm"))
     setdefaultattr(
         self, 'time_unit', self.quan(self.parameters["unit_t"], "s"))
     setdefaultattr(self, 'velocity_unit', self.length_unit / self.time_unit)
Esempio n. 16
0
 def _set_code_unit_attributes(self):
     """
     Generates the conversion to various physical _units based on the
     parameter file
     """
     if getattr(self, "length_unit", None) is None:
         default_length_units = [
             u for u, v in default_unit_symbol_lut.items()
             if str(v[1]) == "(length)"
         ]
         more_length_units = []
         for unit in default_length_units:
             if unit in self.unit_registry.prefixable_units:
                 more_length_units += [
                     prefix + unit for prefix in unit_prefixes
                 ]
         default_length_units += more_length_units
         file_units = []
         cunits = [
             self.wcs.wcs.cunit[i] for i in range(self.dimensionality)
         ]
         for unit in (_.to_string() for _ in cunits):
             if unit in default_length_units:
                 file_units.append(unit)
         if len(set(file_units)) == 1:
             length_factor = self.wcs.wcs.cdelt[0]
             length_unit = str(file_units[0])
             mylog.info("Found length units of %s.", length_unit)
         else:
             self.no_cgs_equiv_length = True
             mylog.warning(
                 "No length conversion provided. Assuming 1 = 1 cm.")
             length_factor = 1.0
             length_unit = "cm"
         setdefaultattr(self, "length_unit",
                        self.quan(length_factor, length_unit))
     for unit, cgs in [("time", "s"), ("mass", "g")]:
         # We set these to cgs for now, but they may have been overridden
         if getattr(self, unit + "_unit", None) is not None:
             continue
         mylog.warning("Assuming 1.0 = 1.0 %s", cgs)
         setdefaultattr(self, f"{unit}_unit", self.quan(1.0, cgs))
     self.magnetic_unit = np.sqrt(4 * np.pi * self.mass_unit /
                                  (self.time_unit**2 * self.length_unit))
     self.magnetic_unit.convert_to_units("gauss")
     self.velocity_unit = self.length_unit / self.time_unit
Esempio n. 17
0
    def _set_code_unit_attributes(self):
        # This is where quantities are created that represent the various
        # on-disk units.  These are the currently available quantities which
        # should be set, along with examples of how to set them to standard
        # values.
        #
        # self.length_unit = self.quan(1.0, "cm")
        # self.mass_unit = self.quan(1.0, "g")
        # self.time_unit = self.quan(1.0, "s")
        # self.time_unit = self.quan(1.0, "s")
        #
        # These can also be set:
        # self.velocity_unit = self.quan(1.0, "cm/s")
        # self.magnetic_unit = self.quan(1.0, "gauss")

        # this minimalistic implementation fills the requirements for
        # this frontend to run, change it to make it run _correctly_ !
        for key, unit in self.__class__.default_units.items():
            setdefaultattr(self, key, self.quan(1, unit))
Esempio n. 18
0
 def _set_code_unit_attributes(self):
     """
     Generates the conversion to various physical _units based on the parameter file
     """
     default_length_units = [
         u for u, v in default_unit_symbol_lut.items()
         if str(v[1]) == "(length)"
     ]
     more_length_units = []
     for unit in default_length_units:
         if unit in prefixable_units:
             more_length_units += [
                 prefix + unit for prefix in unit_prefixes
             ]
     default_length_units += more_length_units
     file_units = []
     cunits = [self.wcs.wcs.cunit[i] for i in range(self.dimensionality)]
     for unit in (_.to_string() for _ in cunits):
         if unit in default_length_units:
             file_units.append(unit)
     if len(set(file_units)) == 1:
         length_factor = self.wcs.wcs.cdelt[0]
         length_unit = str(file_units[0])
         mylog.info("Found length units of %s." % (length_unit))
     else:
         self.no_cgs_equiv_length = True
         mylog.warning("No length conversion provided. Assuming 1 = 1 cm.")
         length_factor = 1.0
         length_unit = "cm"
     setdefaultattr(self, 'length_unit',
                    self.quan(length_factor, length_unit))
     setdefaultattr(self, 'mass_unit', self.quan(1.0, "g"))
     setdefaultattr(self, 'time_unit', self.quan(1.0, "s"))
     setdefaultattr(self, 'velocity_unit', self.quan(1.0, "cm/s"))
     if "beam_size" in self.specified_parameters:
         beam_size = self.specified_parameters["beam_size"]
         beam_size = self.quan(beam_size[0], beam_size[1]).in_cgs().value
     else:
         beam_size = 1.0
     self.unit_registry.add("beam",
                            beam_size,
                            dimensions=dimensions.solid_angle)
     if self.spec_cube:
         units = self.wcs_2d.wcs.cunit[0]
         if units == "deg": units = "degree"
         if units == "rad": units = "radian"
         pixel_area = np.prod(np.abs(self.wcs_2d.wcs.cdelt))
         pixel_area = self.quan(pixel_area, "%s**2" % (units)).in_cgs()
         pixel_dims = pixel_area.units.dimensions
         self.unit_registry.add("pixel",
                                float(pixel_area.value),
                                dimensions=pixel_dims)
Esempio n. 19
0
 def _set_code_unit_attributes(self):
     setdefaultattr(
         self, 'length_unit',
         self.quan(1.0, self.parameters.get("length_unit", 'kpc')))
     setdefaultattr(
         self, 'velocity_unit',
         self.quan(1.0, self.parameters.get("velocity_unit", 'kpc/Gyr')))
     setdefaultattr(self, 'time_unit',
                    self.quan(1.0, self.parameters.get("time_unit", 'Gyr')))
     mass_unit = self.parameters.get("mass_unit", '1e10 Msun')
     if ' ' in mass_unit:
         factor, unit = mass_unit.split(' ')
     else:
         factor = 1.0
         unit = mass_unit
     setdefaultattr(self, 'mass_unit', self.quan(float(factor), unit))
Esempio n. 20
0
 def _set_code_unit_attributes(self):
     # This is where quantities are created that represent the various
     # on-disk units.  These are the currently available quantities which
     # should be set, along with examples of how to set them to standard
     # values.
     #
     setdefaultattr(self, "length_unit", self.quan(1.0, "cm"))
     setdefaultattr(self, "mass_unit", self.quan(1.0, "g"))
     setdefaultattr(self, "time_unit", self.quan(1.0, "s"))
Esempio n. 21
0
 def _set_code_unit_attributes(self):
     setdefaultattr(
         self,
         "length_unit",
         self.quan(1.0, self.parameters.get("length_unit", "kpc")),
     )
     setdefaultattr(
         self,
         "velocity_unit",
         self.quan(1.0, self.parameters.get("velocity_unit", "kpc/Gyr")),
     )
     setdefaultattr(self, "time_unit",
                    self.quan(1.0, self.parameters.get("time_unit", "Gyr")))
     mass_unit = self.parameters.get("mass_unit", "1e10 Msun")
     if " " in mass_unit:
         factor, unit = mass_unit.split(" ")
     else:
         factor = 1.0
         unit = mass_unit
     setdefaultattr(self, "mass_unit", self.quan(float(factor), unit))
Esempio n. 22
0
    def _set_code_unit_attributes(self):

        if "unitsystem" in self.parameters:
            # Some versions of FLASH inject quotes in the runtime parameters
            # See issue #1721
            us = self["unitsystem"].replace("'", "").replace('"', "").lower()
            if us == "cgs":
                b_factor = 1.0
            elif us == "si":
                b_factor = np.sqrt(4 * np.pi / 1e7)
            elif us == "none":
                b_factor = np.sqrt(4 * np.pi)
            else:
                raise RuntimeError("Runtime parameter unitsystem with "
                                   "value %s is unrecognized" %
                                   self["unitsystem"])
        else:
            b_factor = 1.0
        if self.cosmological_simulation == 1:
            length_factor = 1.0 / (1.0 + self.current_redshift)
            temperature_factor = 1.0 / (1.0 + self.current_redshift)**2
        else:
            length_factor = 1.0
            temperature_factor = 1.0

        setdefaultattr(self, "magnetic_unit", self.quan(b_factor, "gauss"))
        setdefaultattr(self, "length_unit", self.quan(length_factor, "cm"))
        setdefaultattr(self, "mass_unit", self.quan(1.0, "g"))
        setdefaultattr(self, "time_unit", self.quan(1.0, "s"))
        setdefaultattr(self, "velocity_unit", self.quan(1.0, "cm/s"))
        setdefaultattr(self, "temperature_unit",
                       self.quan(temperature_factor, "K"))
Esempio n. 23
0
    def _set_code_unit_attributes(self):
        if self.cosmological_simulation:
            box_size = \
              self.parameters["Physics"]["cosmology"]["comoving_box_size"]
            k = cosmology_get_units(
                self.hubble_constant, self.omega_matter, box_size,
                self.parameters["Physics"]["cosmology"]["initial_redshift"],
                self.current_redshift)
            # Now some CGS values
            setdefaultattr(self, 'length_unit', self.quan(box_size, "Mpccm/h"))
            setdefaultattr(
                self, 'mass_unit',
                self.quan(k['urho'], 'g/cm**3') * (self.length_unit.in_cgs())**3)
            setdefaultattr(self, 'velocity_unit', self.quan(k['uvel'], 'cm/s'))
        else:
            p = self.parameters
            for d, u in zip(("length", "time"),
                            ("cm", "s")):
                val = nested_dict_get(p, ("Units", d), default=1)
                setdefaultattr(self, '%s_unit' % d, self.quan(val, u))
            mass = nested_dict_get(p, ("Units", "mass"))
            if mass is None:
                density = nested_dict_get(p, ("Units", "density"))
                if density is not None:
                    mass = density * self.length_unit**3
                else:
                    mass = 1
            setdefaultattr(self, 'mass_unit', self.quan(mass, "g"))
            setdefaultattr(self, 'velocity_unit',
                           self.length_unit / self.time_unit)

        magnetic_unit = np.sqrt(4*np.pi * self.mass_unit /
                                (self.time_unit**2 * self.length_unit))
        magnetic_unit = np.float64(magnetic_unit.in_cgs())
        setdefaultattr(self, 'magnetic_unit',
                       self.quan(magnetic_unit, "gauss"))
Esempio n. 24
0
    def _set_code_unit_attributes(self):
        if self.cosmological_simulation:
            k = cosmology_get_units(
                self.hubble_constant, self.omega_matter,
                self.parameters["CosmologyComovingBoxSize"],
                self.parameters["CosmologyInitialRedshift"],
                self.current_redshift)
            # Now some CGS values
            box_size = self.parameters["CosmologyComovingBoxSize"]
            setdefaultattr(self, 'length_unit', self.quan(box_size, "Mpccm/h"))
            setdefaultattr(
                self, 'mass_unit',
                self.quan(k['urho'], 'g/cm**3') * (self.length_unit.in_cgs())**3)
            setdefaultattr(self, 'time_unit', self.quan(k['utim'], 's'))
            setdefaultattr(self, 'velocity_unit', self.quan(k['uvel'], 'cm/s'))
        else:
            if "LengthUnits" in self.parameters:
                length_unit = self.parameters["LengthUnits"]
                mass_unit = self.parameters["DensityUnits"] * length_unit**3
                time_unit = self.parameters["TimeUnits"]
            elif "SimulationControl" in self.parameters:
                units = self.parameters["SimulationControl"]["Units"]
                length_unit = units["Length"]
                mass_unit = units["Density"] * length_unit**3
                time_unit = units["Time"]
            else:
                mylog.warning("Setting 1.0 in code units to be 1.0 cm")
                mylog.warning("Setting 1.0 in code units to be 1.0 s")
                length_unit = mass_unit = time_unit = 1.0

            setdefaultattr(self, 'length_unit', self.quan(length_unit, "cm"))
            setdefaultattr(self, 'mass_unit', self.quan(mass_unit, "g"))
            setdefaultattr(self, 'time_unit', self.quan(time_unit, "s"))
            setdefaultattr(
                self, 'velocity_unit', self.length_unit / self.time_unit)

        density_unit = self.mass_unit / self.length_unit**3
        magnetic_unit = np.sqrt(4*np.pi * density_unit) * self.velocity_unit
        magnetic_unit = np.float64(magnetic_unit.in_cgs())
        setdefaultattr(self, 'magnetic_unit', self.quan(magnetic_unit, "gauss"))
Esempio n. 25
0
 def _set_code_unit_attributes(self):
     setdefaultattr(self, 'length_unit', self.quan(1.0, "cm"))
     setdefaultattr(self, 'mass_unit', self.quan(1.0, "g"))
     setdefaultattr(self, 'time_unit', self.quan(1.0, "s"))
     setdefaultattr(self, 'velocity_unit', self.quan(1.0, "cm/s"))
Esempio n. 26
0
    def _set_code_unit_attributes(self):
        """
        Generates the conversion to various physical _units based on the parameter file
        """
        # loading the units from the info file
        boxlen = self.parameters["boxlen"]
        length_unit = self.parameters["unit_l"]
        density_unit = self.parameters["unit_d"]
        time_unit = self.parameters["unit_t"]

        # calculating derived units (except velocity and temperature, done below)
        mass_unit = density_unit * length_unit ** 3
        magnetic_unit = np.sqrt(4 * np.pi * mass_unit / (time_unit ** 2 * length_unit))
        pressure_unit = density_unit * (length_unit / time_unit) ** 2

        # TODO:
        # Generalize the temperature field to account for ionization
        # For now assume an atomic ideal gas with cosmic abundances (x_H = 0.76)
        mean_molecular_weight_factor = _X ** -1

        setdefaultattr(self, "density_unit", self.quan(density_unit, "g/cm**3"))
        setdefaultattr(self, "magnetic_unit", self.quan(magnetic_unit, "gauss"))
        setdefaultattr(self, "pressure_unit", self.quan(pressure_unit, "dyne/cm**2"))
        setdefaultattr(self, "time_unit", self.quan(time_unit, "s"))
        setdefaultattr(self, "mass_unit", self.quan(mass_unit, "g"))
        setdefaultattr(
            self, "velocity_unit", self.quan(length_unit, "cm") / self.time_unit
        )
        temperature_unit = (
            self.velocity_unit ** 2 * mp * mean_molecular_weight_factor / kb
        )
        setdefaultattr(self, "temperature_unit", temperature_unit.in_units("K"))

        # Only the length unit get scales by a factor of boxlen
        setdefaultattr(self, "length_unit", self.quan(length_unit * boxlen, "cm"))
Esempio n. 27
0
    def _parse_parameter_file(self):
        """
        Parses the parameter file and establishes the various
        dictionaries.
        """

        f = open(self.parameter_filename, "r")
        # get dimension from first block name
        b0, fn0 = f.readline().strip().split()
        level0, left0, right0 = get_block_info(b0, min_dim=0)
        root_blocks = get_root_blocks(b0)
        f.close()
        self.dimensionality = left0.size
        self.periodicity = \
          ensure_tuple(np.ones(self.dimensionality, dtype=bool))

        lcfn = self.parameter_filename[:-len(self._suffix)] + ".libconfig"
        if os.path.exists(lcfn):
            with io.open(lcfn, "r") as lf:
                self.parameters = libconf.load(lf)
            cosmo = nested_dict_get(
                self.parameters, ("Physics", "cosmology"))
            if cosmo is not None:
                self.cosmological_simulation = 1
                co_pars = ["hubble_constant_now", "omega_matter_now",
                           "omega_lambda_now", "comoving_box_size",
                           "initial_redshift"]
                co_dict = \
                  dict((attr, nested_dict_get(self.parameters,
                    ("Physics", "cosmology", attr))) for attr in co_pars)
                for attr in ["hubble_constant",
                             "omega_matter",
                             "omega_lambda"]:
                    setattr(self, attr, co_dict["%s_now" % attr])

                # Current redshift is not stored, so it's not possible
                # to set all cosmological units yet.
                # Get the time units and use that to figure out redshift.
                k = cosmology_get_units(
                    self.hubble_constant, self.omega_matter,
                    co_dict["comoving_box_size"],
                    co_dict["initial_redshift"], 0)
                setdefaultattr(
                    self, 'time_unit', self.quan(k['utim'], 's'))
                co = Cosmology(hubble_constant=self.hubble_constant,
                               omega_matter=self.omega_matter,
                               omega_lambda=self.omega_lambda)
            else:
                self.cosmological_simulation = 0
        else:
            self.cosmological_simulation = 0


        fh = h5py.File(os.path.join(self.directory, fn0), "r")
        self.domain_left_edge  = fh.attrs["lower"]
        self.domain_right_edge = fh.attrs["upper"]

        # all blocks are the same size
        ablock = fh[list(fh.keys())[0]]
        self.current_time = ablock.attrs["time"][0]
        gsi = ablock.attrs["enzo_GridStartIndex"]
        gei = ablock.attrs["enzo_GridEndIndex"]
        self.ghost_zones = gsi[0]
        self.root_block_dimensions = root_blocks
        self.active_grid_dimensions = gei - gsi + 1
        self.grid_dimensions = ablock.attrs["enzo_GridDimension"]
        self.domain_dimensions = root_blocks * self.active_grid_dimensions
        fh.close()

        if self.cosmological_simulation:
            self.current_redshift = \
              co.z_from_t(self.current_time * self.time_unit)

        self.periodicity += (False, ) * (3 - self.dimensionality)
        self.gamma = nested_dict_get(self.parameters, ("Field", "gamma"))

        self.unique_identifier = \
          str(int(os.stat(self.parameter_filename)[stat.ST_CTIME]))
Esempio n. 28
0
    def _set_code_unit_attributes(self):
        if self.cosmological_simulation:
            k = self.cosmology_get_units()
            # Now some CGS values
            box_size = self.parameters.get("CosmologyComovingBoxSize", None)
            if box_size is None:
                box_size = self.parameters["Physics"]["Cosmology"]\
                    ["CosmologyComovingBoxSize"]
            setdefaultattr(self, 'length_unit', self.quan(box_size, "Mpccm/h"))
            setdefaultattr(
                self, 'mass_unit',
                self.quan(k['urho'], 'g/cm**3') *
                (self.length_unit.in_cgs())**3)
            setdefaultattr(self, 'time_unit', self.quan(k['utim'], 's'))
            setdefaultattr(self, 'velocity_unit', self.quan(k['uvel'], 'cm/s'))
        else:
            if "LengthUnits" in self.parameters:
                length_unit = self.parameters["LengthUnits"]
                mass_unit = self.parameters["DensityUnits"] * length_unit**3
                time_unit = self.parameters["TimeUnits"]
            elif "SimulationControl" in self.parameters:
                units = self.parameters["SimulationControl"]["Units"]
                length_unit = units["Length"]
                mass_unit = units["Density"] * length_unit**3
                time_unit = units["Time"]
            else:
                mylog.warning("Setting 1.0 in code units to be 1.0 cm")
                mylog.warning("Setting 1.0 in code units to be 1.0 s")
                length_unit = mass_unit = time_unit = 1.0

            setdefaultattr(self, 'length_unit', self.quan(length_unit, "cm"))
            setdefaultattr(self, 'mass_unit', self.quan(mass_unit, "g"))
            setdefaultattr(self, 'time_unit', self.quan(time_unit, "s"))
            setdefaultattr(self, 'velocity_unit',
                           self.length_unit / self.time_unit)

        magnetic_unit = np.sqrt(4 * np.pi * self.mass_unit /
                                (self.time_unit**2 * self.length_unit))
        magnetic_unit = np.float64(magnetic_unit.in_cgs())
        setdefaultattr(self, 'magnetic_unit',
                       self.quan(magnetic_unit, "gauss"))
Esempio n. 29
0
 def _set_code_unit_attributes(self):
     setdefaultattr(self, 'length_unit', self.quan(1.0, 'kpccm/h'))
     setdefaultattr(self, 'mass_unit', self.quan(1.0, 'Msun/h'))
     setdefaultattr(self, 'time_unit', self.quan(1.0, 's'))
     setdefaultattr(self, 'velocity_unit', self.quan(1.0, 'km/s'))
Esempio n. 30
0
    def _set_code_unit_attributes(self):

        if 'unitsystem' in self.parameters:
            if self['unitsystem'].lower() == "cgs":
                b_factor = 1.0
            elif self['unitsystem'].lower() == "si":
                b_factor = np.sqrt(4 * np.pi / 1e7)
            elif self['unitsystem'].lower() == "none":
                b_factor = np.sqrt(4 * np.pi)
            else:
                raise RuntimeError("Runtime parameter unitsystem with "
                                   "value %s is unrecognized" %
                                   self['unitsystem'])
        else:
            b_factor = 1.
        if self.cosmological_simulation == 1:
            length_factor = 1.0 / (1.0 + self.current_redshift)
            temperature_factor = 1.0 / (1.0 + self.current_redshift)**2
        else:
            length_factor = 1.0
            temperature_factor = 1.0

        setdefaultattr(self, 'magnetic_unit', self.quan(b_factor, "gauss"))
        setdefaultattr(self, 'length_unit', self.quan(length_factor, "cm"))
        setdefaultattr(self, 'mass_unit', self.quan(1.0, "g"))
        setdefaultattr(self, 'time_unit', self.quan(1.0, "s"))
        setdefaultattr(self, 'velocity_unit', self.quan(1.0, "cm/s"))
        setdefaultattr(self, 'temperature_unit',
                       self.quan(temperature_factor, "K"))