Exemplo n.º 1
0
    def _parse_parameter_file(self):
        super(MaestroDataset, self)._parse_parameter_file()
        jobinfo_filename = os.path.join(self.output_dir, "job_info")
        line = ""
        with open(jobinfo_filename, "r") as f:
            while not line.startswith(" [*] indicates overridden default"):
                # get the code git hashes
                if "git hash" in line:
                    # line format: codename git hash:  the-hash
                    fields = line.split(":")
                    self.parameters[fields[0]] = fields[1].strip()
                line = next(f)
            # get the runtime parameters
            for line in f:
                p, v = (_.strip() for _ in line[4:].split("=", 1))
                if len(v) == 0:
                    self.parameters[p] = ""
                else:
                    self.parameters[p] = _guess_pcast(v)
            # hydro method is set by the base class -- override it here
            self.parameters["HydroMethod"] = "Maestro"

        # set the periodicity based on the integer BC runtime parameters
        periodicity = [True, True, True]
        if not self.parameters['bcx_lo'] == -1:
            periodicity[0] = False

        if not self.parameters['bcy_lo'] == -1:
            periodicity[1] = False

        if not self.parameters['bcz_lo'] == -1:
            periodicity[2] = False

        self.periodicity = ensure_tuple(periodicity)
Exemplo n.º 2
0
    def _parse_parameter_file(self):

        xmin, xmax = self._handle.attrs["RootGridX1"][:2]
        ymin, ymax = self._handle.attrs["RootGridX2"][:2]
        zmin, zmax = self._handle.attrs["RootGridX3"][:2]

        self.domain_left_edge = np.array([xmin, ymin, zmin], dtype="float64")
        self.domain_right_edge = np.array([xmax, ymax, zmax], dtype="float64")

        self.geometry = geom_map[self._handle.attrs["Coordinates"].decode(
            "utf-8")]
        self.domain_width = self.domain_right_edge - self.domain_left_edge
        self.domain_dimensions = self._handle.attrs["RootGridSize"]

        self._field_map = {}
        k = 0
        for dname, num_var in zip(self._handle.attrs["DatasetNames"],
                                  self._handle.attrs["NumVariables"]):
            for j in range(num_var):
                fname = self._handle.attrs["VariableNames"][k].decode(
                    "ascii", "ignore")
                self._field_map[fname] = (dname.decode("ascii", "ignore"), j)
                k += 1

        self.refine_by = 2
        dimensionality = 3
        if self.domain_dimensions[2] == 1:
            dimensionality = 2
        if self.domain_dimensions[1] == 1:
            dimensionality = 1
        self.dimensionality = dimensionality
        self.current_time = self._handle.attrs["Time"]
        self.unique_identifier = self.parameter_filename.__hash__()
        self.cosmological_simulation = False
        self.num_ghost_zones = 0
        self.field_ordering = "fortran"
        self.boundary_conditions = [1] * 6
        if "periodicity" in self.specified_parameters:
            self.periodicity = ensure_tuple(
                self.specified_parameters["periodicity"])
        else:
            self.periodicity = (True, True, True)
        if "gamma" in self.specified_parameters:
            self.gamma = float(self.specified_parameters["gamma"])
        else:
            self.gamma = 5.0 / 3.0

        self.current_redshift = (self.omega_lambda) = (
            self.omega_matter
        ) = self.hubble_constant = self.cosmological_simulation = 0.0
        self.parameters[
            "Time"] = self.current_time  # Hardcode time conversion for now.
        self.parameters[
            "HydroMethod"] = 0  # Hardcode for now until field staggering is supported.
        if "gamma" in self.specified_parameters:
            self.parameters["Gamma"] = self.specified_parameters["gamma"]
        else:
            self.parameters["Gamma"] = 5.0 / 3.0
        self.mu = self.specified_parameters.get("mu", default_mu)
Exemplo n.º 3
0
 def _setup1d(self):
     # self._index_class = BoxlibHierarchy1D
     # self._fieldinfo_fallback = Orion1DFieldInfo
     self.domain_left_edge = \
         np.concatenate([self.domain_left_edge, [0.0, 0.0]])
     self.domain_right_edge = \
         np.concatenate([self.domain_right_edge, [1.0, 1.0]])
     tmp = self.domain_dimensions.tolist()
     tmp.extend((1, 1))
     self.domain_dimensions = np.array(tmp)
     tmp = list(self.periodicity)
     tmp[1] = False
     tmp[2] = False
     self.periodicity = ensure_tuple(tmp)
Exemplo n.º 4
0
 def _setup2d(self):
     self.domain_left_edge = \
         np.concatenate([self.domain_left_edge, [0.0]])
     self.domain_right_edge = \
         np.concatenate([self.domain_right_edge, [1.0]])
     if self.geometry == "cylindrical":
         dre = self.domain_right_edge
         dre[2] = 2.0 * np.pi
         self.domain_right_edge = dre
     tmp = self.domain_dimensions.tolist()
     tmp.append(1)
     self.domain_dimensions = np.array(tmp)
     tmp = list(self.periodicity)
     tmp[2] = False
     self.periodicity = ensure_tuple(tmp)
Exemplo n.º 5
0
 def _parse_parameter_file(self):
     self._handle = h5py.File(self.parameter_filename, mode="r")
     if "data_software" in self._handle["gridded_data_format"].attrs:
         self.data_software = self._handle["gridded_data_format"].attrs[
             "data_software"]
     else:
         self.data_software = "unknown"
     sp = self._handle["/simulation_parameters"].attrs
     if self.geometry is None:
         geometry = just_one(sp.get("geometry", 0))
         try:
             self.geometry = GEOMETRY_TRANS[geometry]
         except KeyError:
             raise YTGDFUnknownGeometry(geometry)
     self.parameters.update(sp)
     self.domain_left_edge = sp["domain_left_edge"][:]
     self.domain_right_edge = sp["domain_right_edge"][:]
     self.domain_dimensions = sp["domain_dimensions"][:]
     refine_by = sp["refine_by"]
     if refine_by is None:
         refine_by = 2
     self.refine_by = refine_by
     self.dimensionality = sp["dimensionality"]
     self.current_time = sp["current_time"]
     self.unique_identifier = sp["unique_identifier"]
     self.cosmological_simulation = sp["cosmological_simulation"]
     if sp["num_ghost_zones"] != 0:
         raise RuntimeError
     self.num_ghost_zones = sp["num_ghost_zones"]
     self.field_ordering = sp["field_ordering"]
     self.boundary_conditions = sp["boundary_conditions"][:]
     p = [bnd == 0 for bnd in self.boundary_conditions[::2]]
     self.periodicity = ensure_tuple(p)
     if self.cosmological_simulation:
         self.current_redshift = sp["current_redshift"]
         self.omega_lambda = sp["omega_lambda"]
         self.omega_matter = sp["omega_matter"]
         self.hubble_constant = sp["hubble_constant"]
     else:
         self.current_redshift = (self.omega_lambda) = (
             self.omega_matter
         ) = self.hubble_constant = self.cosmological_simulation = 0.0
     self.parameters["Time"] = 1.0  # Hardcode time conversion for now.
     # Hardcode for now until field staggering is supported.
     self.parameters["HydroMethod"] = 0
     self._handle.close()
     del self._handle
Exemplo n.º 6
0
def nested_dict_get(pdict, keys, default=None):
    """
    Retrieve a value from a nested dict using a tuple of keys.

    If a is a dict, and a['b'] = {'c': 'd'},
    then nested_dict_get(a, ('b', 'c')) returns 'd'.
    """

    keys = ensure_tuple(keys)
    val = pdict
    for key in keys:
        if val is None:
            break
        val = val.get(key)
    if val is None:
        val = default
    return val
 def _parse_parameter_file(self):
     self._handle = h5py.File(self.parameter_filename, "r")
     if 'data_software' in self._handle['gridded_data_format'].attrs:
         self.data_software = \
             self._handle['gridded_data_format'].attrs['data_software']
     else:
         self.data_software = "unknown"
     sp = self._handle["/simulation_parameters"].attrs
     if self.geometry is None:
         geometry = just_one(sp.get("geometry", 0))
         try:
             self.geometry = GEOMETRY_TRANS[geometry]
         except KeyError:
             raise YTGDFUnknownGeometry(geometry)
     self.parameters.update(sp)
     self.domain_left_edge = sp["domain_left_edge"][:]
     self.domain_right_edge = sp["domain_right_edge"][:]
     self.domain_dimensions = sp["domain_dimensions"][:]
     refine_by = sp["refine_by"]
     if refine_by is None:
         refine_by = 2
     self.refine_by = refine_by
     self.dimensionality = sp["dimensionality"]
     self.current_time = sp["current_time"]
     self.unique_identifier = sp["unique_identifier"]
     self.cosmological_simulation = sp["cosmological_simulation"]
     if sp["num_ghost_zones"] != 0:
         raise RuntimeError
     self.num_ghost_zones = sp["num_ghost_zones"]
     self.field_ordering = sp["field_ordering"]
     self.boundary_conditions = sp["boundary_conditions"][:]
     p = [bnd == 0 for bnd in self.boundary_conditions[::2]]
     self.periodicity = ensure_tuple(p)
     if self.cosmological_simulation:
         self.current_redshift = sp["current_redshift"]
         self.omega_lambda = sp["omega_lambda"]
         self.omega_matter = sp["omega_matter"]
         self.hubble_constant = sp["hubble_constant"]
     else:
         self.current_redshift = self.omega_lambda = self.omega_matter = \
             self.hubble_constant = self.cosmological_simulation = 0.0
     self.parameters['Time'] = 1.0  # Hardcode time conversion for now.
     # Hardcode for now until field staggering is supported.
     self.parameters["HydroMethod"] = 0
     self._handle.close()
     del self._handle
Exemplo n.º 8
0
    def _parse_cparams(self):
        if self.cparam_filename is None:
            return
        for line in (line.split("#")[0].strip()
                     for line in open(self.cparam_filename)):
            if "=" not in line: continue
            if len(line) == 0: continue
            param, vals = [s.strip() for s in line.split("=")]
            if param == "amr.n_cell":
                vals = self.domain_dimensions = np.array(vals.split(),
                                                         dtype='int32')

                # For 1D and 2D simulations in BoxLib usually only the relevant dimensions
                # have a specified number of zones, but yt requires domain_dimensions to
                # have three elements, with 1 in the additional slots if we're not in 3D,
                # so append them as necessary.

                if (len(vals) == 1):
                    vals = self.domain_dimensions = np.array([vals[0], 1, 1])
                elif (len(vals) == 2):
                    vals = self.domain_dimensions = np.array(
                        [vals[0], vals[1], 1])
            elif param == "amr.ref_ratio":
                vals = self.refine_by = int(vals[0])
            elif param == "Prob.lo_bc":
                vals = self.periodicity = ensure_tuple(
                    [i == 0 for i in vals.split()])
            elif param == "castro.use_comoving":
                vals = self.cosmological_simulation = int(vals)
            else:
                vals = _guess_pcast(vals)
            self.parameters[param] = vals

        if getattr(self, "cosmological_simulation", 0) == 1:
            self.omega_lambda = self.parameters["comoving_OmL"]
            self.omega_matter = self.parameters["comoving_OmM"]
            self.hubble_constant = self.parameters["comoving_h"]
            a_file = open(os.path.join(self.output_dir, 'comoving_a'))
            line = a_file.readline().strip()
            a_file.close()
            self.current_redshift = 1 / float(line) - 1
        else:
            self.current_redshift = self.omega_lambda = self.omega_matter = \
                self.hubble_constant = self.cosmological_simulation = 0.0
Exemplo n.º 9
0
 def _parse_parameter_file(self):
     enzo = self._obtain_enzo()
     self.basename = "cycle%08i" % (
         enzo.yt_parameter_file["NumberOfPythonCalls"])
     self.parameters["CurrentTimeIdentifier"] = time.time()
     self.parameters.update(enzo.yt_parameter_file)
     self.conversion_factors.update(enzo.conversion_factors)
     for i in self.parameters:
         if isinstance(self.parameters[i], tuple):
             self.parameters[i] = np.array(self.parameters[i])
         if i.endswith("Units") and not i.startswith("Temperature"):
             dataType = i[:-5]
             self.conversion_factors[dataType] = self.parameters[i]
     self.domain_left_edge = self.parameters["DomainLeftEdge"].copy()
     self.domain_right_edge = self.parameters["DomainRightEdge"].copy()
     for i in self.conversion_factors:
         if isinstance(self.conversion_factors[i], tuple):
             self.conversion_factors[i] = np.array(
                 self.conversion_factors[i])
     for p, v in self._parameter_override.items():
         self.parameters[p] = v
     for p, v in self._conversion_override.items():
         self.conversion_factors[p] = v
     self.refine_by = self.parameters["RefineBy"]
     self.periodicity = ensure_tuple(
         self.parameters["LeftFaceBoundaryCondition"] == 3)
     self.dimensionality = self.parameters["TopGridRank"]
     self.domain_dimensions = self.parameters["TopGridDimensions"]
     self.current_time = self.parameters["InitialTime"]
     if "CurrentTimeIdentifier" in self.parameters:
         self.unique_identifier = self.parameters["CurrentTimeIdentifier"]
     if self.parameters["ComovingCoordinates"]:
         self.cosmological_simulation = 1
         self.current_redshift = self.parameters["CosmologyCurrentRedshift"]
         self.omega_lambda = self.parameters["CosmologyOmegaLambdaNow"]
         self.omega_matter = self.parameters["CosmologyOmegaMatterNow"]
         self.hubble_constant = self.parameters[
             "CosmologyHubbleConstantNow"]
     else:
         self.current_redshift = (self.omega_lambda) = (
             self.omega_matter
         ) = self.hubble_constant = self.cosmological_simulation = 0.0
Exemplo n.º 10
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))

        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()

        self.periodicity += (False, ) * (3 - self.dimensionality)

        # WIP hard-coded for now
        self.refine_by = 2
        self.cosmological_simulation = 0
        self.gamma = 5. / 3.
        self.particle_types = ()
        self.particle_types_raw = self.particle_types
        self.unique_identifier = \
          str(int(os.stat(self.parameter_filename)[stat.ST_CTIME]))
Exemplo n.º 11
0
    def _parse_parameter_file(self):
        super(CastroDataset, self)._parse_parameter_file()
        jobinfo_filename = os.path.join(self.output_dir, "job_info")
        line = ""
        with open(jobinfo_filename, "r") as f:
            while not line.startswith(" Inputs File Parameters"):
                # boundary condition info starts with -x:, etc.
                bcs = ["-x:", "+x:", "-y:", "+y:", "-z:", "+z:"]
                if any(b in line for b in bcs):
                    p, v = line.strip().split(":")
                    self.parameters[p] = v.strip()
                if "git hash" in line:
                    # line format: codename git hash:  the-hash
                    fields = line.split(":")
                    self.parameters[fields[0]] = fields[1].strip()
                line = next(f)

            # runtime parameters that we overrode follow "Inputs File
            # Parameters"
            # skip the "====..." line
            line = next(f)
            for line in f:
                p, v = line.strip().split("=")
                self.parameters[p] = v.strip()

        # hydro method is set by the base class -- override it here
        self.parameters["HydroMethod"] = "Castro"

        # set the periodicity based on the runtime parameters
        periodicity = [True, True, True]
        if not self.parameters['-x'] == "interior": periodicity[0] = False
        if self.dimensionality >= 2:
            if not self.parameters['-y'] == "interior": periodicity[1] = False
        if self.dimensionality == 3:
            if not self.parameters['-z'] == "interior": periodicity[2] = False

        self.periodicity = ensure_tuple(periodicity)
Exemplo n.º 12
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]))
Exemplo n.º 13
0
    def _parse_parameter_file(self):
        self._handle = open(self.parameter_filename, "rb")
        # Read the start of a grid to get simulation parameters.
        grid = {}
        grid['read_field'] = None
        line = self._handle.readline()
        while grid['read_field'] is None:
            parse_line(line, grid)
            splitup = line.strip().split()
            if chk23('X_COORDINATES') in splitup:
                grid['left_edge'] = np.zeros(3)
                grid['dds'] = np.zeros(3)
                v = np.fromfile(self._handle, dtype='>f8', count=2)
                grid['left_edge'][0] = v[0] - 0.5 * (v[1] - v[0])
                grid['dds'][0] = v[1] - v[0]
            if chk23('Y_COORDINATES') in splitup:
                v = np.fromfile(self._handle, dtype='>f8', count=2)
                grid['left_edge'][1] = v[0] - 0.5 * (v[1] - v[0])
                grid['dds'][1] = v[1] - v[0]
            if chk23('Z_COORDINATES') in splitup:
                v = np.fromfile(self._handle, dtype='>f8', count=2)
                grid['left_edge'][2] = v[0] - 0.5 * (v[1] - v[0])
                grid['dds'][2] = v[1] - v[0]
            if check_break(line): break
            line = self._handle.readline()

        self.domain_left_edge = grid['left_edge']
        mylog.info(
            "Temporarily setting domain_right_edge = -domain_left_edge." +
            " This will be corrected automatically if it is not the case.")
        self.domain_right_edge = -self.domain_left_edge
        self.domain_width = self.domain_right_edge - self.domain_left_edge
        self.domain_dimensions = np.round(self.domain_width /
                                          grid['dds']).astype('int32')
        refine_by = None
        if refine_by is None: refine_by = 2
        self.refine_by = refine_by
        dimensionality = 3
        if grid['dimensions'][2] == 1:
            dimensionality = 2
        if grid['dimensions'][1] == 1:
            dimensionality = 1
        if dimensionality <= 2: self.domain_dimensions[2] = np.int32(1)
        if dimensionality == 1: self.domain_dimensions[1] = np.int32(1)
        if dimensionality != 3 and self.nprocs > 1:
            raise RuntimeError(
                "Virtual grids are only supported for 3D outputs!")
        self.dimensionality = dimensionality
        self.current_time = grid["time"]
        self.unique_identifier = self.parameter_filename.__hash__()
        self.cosmological_simulation = False
        self.num_ghost_zones = 0
        self.field_ordering = 'fortran'
        self.boundary_conditions = [1] * 6
        if 'periodicity' in self.specified_parameters:
            self.periodicity = ensure_tuple(
                self.specified_parameters['periodicity'])
        else:
            self.periodicity = (
                True,
                True,
                True,
            )
        if 'gamma' in self.specified_parameters:
            self.gamma = float(self.specified_parameters['gamma'])
        else:
            self.gamma = 5. / 3.
        dataset_dir = os.path.dirname(self.parameter_filename)
        dname = os.path.split(self.parameter_filename)[-1]
        if dataset_dir.endswith("id0"):
            dname = "id0/" + dname
            dataset_dir = dataset_dir[:-3]

        gridlistread = glob.glob(
            os.path.join(dataset_dir,
                         'id*/%s-id*%s' % (dname[4:-9], dname[-9:])))
        if 'id0' in dname:
            gridlistread += glob.glob(
                os.path.join(dataset_dir, 'id*/lev*/%s*-lev*%s' %
                             (dname[4:-9], dname[-9:])))
        else:
            gridlistread += glob.glob(
                os.path.join(dataset_dir,
                             'lev*/%s*-lev*%s' % (dname[:-9], dname[-9:])))
        ndots = dname.count(".")
        gridlistread = [
            fn for fn in gridlistread
            if os.path.basename(fn).count(".") == ndots
        ]
        self.nvtk = len(gridlistread) + 1

        self.current_redshift = self.omega_lambda = self.omega_matter = \
            self.hubble_constant = self.cosmological_simulation = 0.0
        self.parameters[
            'Time'] = self.current_time  # Hardcode time conversion for now.
        self.parameters[
            "HydroMethod"] = 0  # Hardcode for now until field staggering is supported.
        if "gamma" in self.specified_parameters:
            self.parameters["Gamma"] = self.specified_parameters["gamma"]
        else:
            self.parameters["Gamma"] = 5. / 3.
        self.geometry = self.specified_parameters.get("geometry", "cartesian")
        self._handle.close()
Exemplo n.º 14
0
    def _parse_enzo2_parameter_file(self, f):
        for line in (l.strip() for l in f):
            if len(line) < 2: continue
            param, vals = (i.strip() for i in line.split("=", 1))
            # First we try to decipher what type of value it is.
            vals = vals.split()
            # Special case approaching.
            if "(do" in vals: vals = vals[:1]
            if len(vals) == 0:
                pcast = str  # Assume NULL output
            else:
                v = vals[0]
                # Figure out if it's castable to floating point:
                try:
                    float(v)
                except ValueError:
                    pcast = str
                else:
                    if any("." in v or "e+" in v or "e-" in v for v in vals):
                        pcast = float
                    elif v == "inf":
                        pcast = str
                    else:
                        pcast = int
            # Now we figure out what to do with it.
            if len(vals) == 0:
                vals = ""
            elif len(vals) == 1:
                vals = pcast(vals[0])
            else:
                vals = np.array([pcast(i) for i in vals if i != "-99999"])
            if param.startswith("Append"):
                if param not in self.parameters:
                    self.parameters[param] = []
                self.parameters[param].append(vals)
            else:
                self.parameters[param] = vals
        self.refine_by = self.parameters["RefineBy"]
        self.periodicity = ensure_tuple(
            self.parameters["LeftFaceBoundaryCondition"] == 3)
        self.dimensionality = self.parameters["TopGridRank"]
        if "MetaDataDatasetUUID" in self.parameters:
            self.unique_identifier = self.parameters["MetaDataDatasetUUID"]
        elif "CurrentTimeIdentifier" in self.parameters:
            self.unique_identifier = self.parameters["CurrentTimeIdentifier"]
        else:
            self.unique_identifier = \
                str(int(os.stat(self.parameter_filename)[stat.ST_CTIME]))
        if self.dimensionality > 1:
            self.domain_dimensions = self.parameters["TopGridDimensions"]
            if len(self.domain_dimensions) < 3:
                tmp = self.domain_dimensions.tolist()
                tmp.append(1)
                self.domain_dimensions = np.array(tmp)
                self.periodicity += (False, )
            self.domain_left_edge = np.array(self.parameters["DomainLeftEdge"],
                                             "float64").copy()
            self.domain_right_edge = np.array(
                self.parameters["DomainRightEdge"], "float64").copy()
        else:
            self.domain_left_edge = np.array(self.parameters["DomainLeftEdge"],
                                             "float64")
            self.domain_right_edge = np.array(
                self.parameters["DomainRightEdge"], "float64")
            self.domain_dimensions = np.array(
                [self.parameters["TopGridDimensions"], 1, 1])
            self.periodicity += (False, False)

        self.gamma = self.parameters["Gamma"]
        if self.parameters["ComovingCoordinates"]:
            self.cosmological_simulation = 1
            self.current_redshift = self.parameters["CosmologyCurrentRedshift"]
            self.omega_lambda = self.parameters["CosmologyOmegaLambdaNow"]
            self.omega_matter = self.parameters["CosmologyOmegaMatterNow"]
            self.hubble_constant = self.parameters[
                "CosmologyHubbleConstantNow"]
        else:
            self.current_redshift = self.omega_lambda = self.omega_matter = \
                self.hubble_constant = self.cosmological_simulation = 0.0
        self.particle_types = []
        self.current_time = self.parameters["InitialTime"]
        if self.parameters["NumberOfParticles"] > 0 and \
            "AppendActiveParticleType" in self.parameters.keys():
            # If this is the case, then we know we should have a DarkMatter
            # particle type, and we don't need the "io" type.
            self.parameters["AppendActiveParticleType"].append("DarkMatter")
        else:
            # We do not have an "io" type for Enzo particles if the
            # ActiveParticle machinery is on, as we simply will ignore any of
            # the non-DarkMatter particles in that case.  However, for older
            # datasets, we call this particle type "io".
            self.particle_types = ["io"]
        for ptype in self.parameters.get("AppendActiveParticleType", []):
            self.particle_types.append(ptype)
        self.particle_types = tuple(self.particle_types)
        self.particle_types_raw = self.particle_types

        if self.dimensionality == 1:
            self._setup_1d()
        elif self.dimensionality == 2:
            self._setup_2d()