Ejemplo n.º 1
0
def test_with_time(tmpdir):
    field = RasterModelGrid(4, 3)
    field.add_field("node", "topographic__elevation",
                    np.ones(12, dtype=np.int64))

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc",
                            field,
                            append=False,
                            format="NETCDF4",
                            time=0.)

        root = nc.Dataset("test.nc", "r", format="NETCDF4")

        for name in ["topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(root.variables[name][:],
                               [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]])
            assert root.variables[name][:].dtype == "int64"
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 1

        assert "t" in root.variables
        assert_array_equal(root.variables["t"][:], [0.])

        root.close()
Ejemplo n.º 2
0
def test_names_keyword(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("topographic__elevation", np.arange(12.0), at="node")
    field.add_field("uplift_rate", 2.0 * np.arange(12.0), at="node")

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc",
                            field,
                            format="NETCDF3_64BIT",
                            names="uplift_rate")

        root = nc.Dataset("test.nc", "r", format="NETCDF3_64BIT")

        assert "topographic__elevation" not in root.variables
        assert "uplift_rate" in root.variables

        assert_array_equal(
            root.variables["uplift_rate"],
            [[
                [0.0, 2.0, 4.0],
                [6.0, 8.0, 10.0],
                [12.0, 14.0, 16.0],
                [18.0, 20.0, 22.0],
            ]],
        )
        assert "nt" in root.dimensions
        assert len(root.dimensions["nt"]) == 1

        root.close()
Ejemplo n.º 3
0
def test_append_without_time_netcdf3(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("topographic__elevation", np.ones(12), at="node")

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc",
                            field,
                            append=False,
                            format="NETCDF3_64BIT")
        field.at_node["topographic__elevation"] *= 2
        write_raster_netcdf("test.nc",
                            field,
                            append=True,
                            format="NETCDF3_64BIT")

        root = nc.Dataset("test.nc", "r", format="NETCDF3_64BIT")

        for name in ["topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(root.variables[name][:],
                               [[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]])
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 1

        assert "t" not in root.variables

        root.close()
Ejemplo n.º 4
0
    def write_output(self):
        """Write output to file as a netCDF.

        Filenames will have the value of ``"output_filename"`` from the
        input file or parameter dictionary as the first part of the file
        name and the model run iteration as the second part of the
        filename.
        """
        self.calculate_cumulative_change()
        filename = self._out_file_name + str(self.iteration).zfill(4) + ".nc"
        self._output_files.append(filename)
        try:
            write_raster_netcdf(filename,
                                self.grid,
                                names=self.output_fields,
                                format="NETCDF4")
        except NotImplementedError:
            graph = Graph.from_dict({
                "y_of_node": self.grid.y_of_node,
                "x_of_node": self.grid.x_of_node,
                "nodes_at_link": self.grid.nodes_at_link,
            })

            for field_name in self.output_fields:

                graph._ds.__setitem__(field_name,
                                      ("node", self.grid.at_node[field_name]))

            graph.to_netcdf(path=filename, mode="w", format="NETCDF4")

        self.run_output_writers()
Ejemplo n.º 5
0
def test_without_time_netcdf3(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("node", "topographic__elevation", 2.0 * np.arange(12.0))
    field.add_field("node", "uplift_rate", 2.0 * np.arange(12.0))

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc", field, format="NETCDF3_64BIT")

        root = nc.Dataset("test.nc", "r", format="NETCDF3_64BIT")

        for name in ["uplift_rate", "topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(
                root.variables[name][:],
                [[
                    [0.0, 2.0, 4.0],
                    [6.0, 8.0, 10.0],
                    [12.0, 14.0, 16.0],
                    [18.0, 20.0, 22.0],
                ]],
            )
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 1

        assert "t" not in root.variables

        root.close()
Ejemplo n.º 6
0
def test_append_with_time(tmpdir):
    field = RasterModelGrid(4, 3)
    field.add_field("node", "topographic__elevation", np.ones(12, dtype=np.int64))

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc", field, append=False, format="NETCDF4", time=0)
        field.at_node["topographic__elevation"] *= 2
        write_raster_netcdf("test.nc", field, append=True, format="NETCDF4", time=1.)

        root = nc.Dataset("test.nc", "r", format="NETCDF4")

        for name in ["topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(
                root.variables[name][:],
                [
                    [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
                    [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
                ],
            )
            assert root.variables[name][:].dtype == "int64"
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 2

        assert "t" in root.variables
        assert_array_equal(root.variables["t"][:], [0., 1.])

        root.close()
Ejemplo n.º 7
0
def test_with_time_netcdf3(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("node", "topographic__elevation", 2.0 * np.arange(12.0))
    field.add_field("node", "uplift_rate", 2.0 * np.arange(12.0))

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc", field, format="NETCDF3_64BIT", time=10.0)

        root = nc.Dataset("test.nc", "r", format="NETCDF3_64BIT")

        for name in ["uplift_rate", "topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(
                root.variables[name][:],
                [
                    [
                        [0.0, 2.0, 4.0],
                        [6.0, 8.0, 10.0],
                        [12.0, 14.0, 16.0],
                        [18.0, 20.0, 22.0],
                    ]
                ],
            )
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 1

        assert "t" in root.variables
        assert_array_equal(root.variables["t"][:], [10.0])

        root.close()
Ejemplo n.º 8
0
    def run_one_step(self, dt=None, output=None, names=None):
        """Run each component for one time step."""
        dt = dt or self.clock.step

        self.advance_components(dt)
        self.clock.advance(step=dt)

        if output:
            write_raster_netcdf(output, self.grid, append=True, names=names)
Ejemplo n.º 9
0
    def run(self, output=None, names=None):
        """Run the model until complete."""
        if output:
            write_raster_netcdf(output, self.grid, append=False, names=names)

        try:
            while 1:
                self.run_one_step(output=output, names=names)
        except StopIteration:
            pass
Ejemplo n.º 10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('file', nargs='?', help='plume config file')
    parser.add_argument('--output', help='output file')
    parser.add_argument('--verbose', action='store_true',
                        help='be verbose')
    parser.add_argument('--plot', choices=('c', 'cs', 'dz'), default=None,
                        help='value to plot')
    parser.add_argument('--set', action='append', default=[],
                        help='set plume parameters')

    args = parser.parse_args()

    params = DEFAULT_PARAMS
    if args.file:
        params_from_file = load_params(args.file)
        for group in params.keys():
            params[group].update(params_from_file.get(group, {}))

    params_from_cl = load_params_from_strings(args.set)
    for group in params.keys():
        params[group].update(params_from_cl.get(group, {}))

    if args.verbose:
        print(yaml.dump(params, default_flow_style=False))

    params['river']['angle'] = np.deg2rad(params['river']['angle'])

    grid = RasterModelGrid(params['grid']['shape'],
                           spacing=params['grid']['spacing'],
                           origin=params['grid']['origin'])
    plume = Plume(grid,
                  river_width=params['river']['width'],
                  river_depth=params['river']['depth'],
                  river_velocity=params['river']['velocity'],
                  river_angle=params['river']['angle'],
                  river_loc=params['river']['location'],
                  ocean_velocity=params['ocean']['along_shore_velocity'],
                  )

    plume.grid.at_grid['sediment__removal_rate'] = params['sediment']['removal_rate']
    plume.grid.at_grid['sediment__bulk_density'] = params['sediment']['bulk_density']
    deposit = plume.calc_deposit_thickness(params['sediment']['removal_rate'])
    if args.plot:
        imshow_grid(plume.grid, plume.grid.at_node[LONG_NAME[args.plot]],
                    at='node', show=True)

    if args.output:
        write_raster_netcdf(args.output, plume.grid)
Ejemplo n.º 11
0
    def run_one_step(self):
        """ Write output to file as a netCDF.  """
        filename_prefix = self.filename_prefix
        filename = f"{filename_prefix}.nc"
        filepath = os.path.join(self.output_dir, filename)

        grid = self.model.grid
        if isinstance(grid, RasterModelGrid):
            write_raster_netcdf(filepath,
                                grid,
                                names=self.output_fields,
                                format="NETCDF4")
        else:
            to_netcdf(grid, filepath, format="NETCDF4")

        self.register_output_filepath(filepath)
    def write_output(self, params, field_names=None):
        """Write output to file (currently netCDF)."""

        # Exclude fields with int64 (incompatible with netCDF3)
        if field_names is None:
            field_names = []
            for field in self.grid.at_node:
                if type(self.grid.at_node[field][0]) is not np.int64:
                    field_names.append(field)

        self.calculate_cumulative_change()
        filename = self.params['output_filename'] + str(self.iteration).zfill(4) \
                    + '.nc'
        write_raster_netcdf(filename,
                            self.grid,
                            names=field_names,
                            format='NETCDF4')
Ejemplo n.º 13
0
def test_without_time(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("node", "topographic__elevation", np.ones(12, dtype=np.int64))

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc", field, append=False, format="NETCDF4")

        root = nc.Dataset("test.nc", "r", format="NETCDF4")

        for name in ["topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(
                root.variables[name][:], [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]]
            )
            assert root.variables[name][:].dtype == "int64"
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 1

        assert "t" not in root.variables

        root.close()
Ejemplo n.º 14
0
def test_append_without_time_netcdf3(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("topographic__elevation", np.ones(12), at="node")

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc", field, append=False, format="NETCDF3_64BIT")
        field.at_node["topographic__elevation"] *= 2
        write_raster_netcdf("test.nc", field, append=True, format="NETCDF3_64BIT")

        root = nc.Dataset("test.nc", "r", format="NETCDF3_64BIT")

        for name in ["topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(
                root.variables[name][:], [[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]]
            )
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 1

        assert "t" not in root.variables

        root.close()
Ejemplo n.º 15
0
def test_append_with_time(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("topographic__elevation",
                    np.ones(12, dtype=np.int64),
                    at="node")

    with tmpdir.as_cwd():
        write_raster_netcdf("test.nc",
                            field,
                            append=False,
                            format="NETCDF4",
                            time=0)
        field.at_node["topographic__elevation"] *= 2
        write_raster_netcdf("test.nc",
                            field,
                            append=True,
                            format="NETCDF4",
                            time=1.0)

        root = nc.Dataset("test.nc", "r", format="NETCDF4")

        for name in ["topographic__elevation"]:
            assert name in root.variables
            assert_array_equal(
                root.variables[name],
                [
                    [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
                    [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
                ],
            )
            assert root.variables[name].dtype == "int64"
            assert "nt" in root.dimensions
            assert len(root.dimensions["nt"]) == 2

        assert "t" in root.variables
        assert_array_equal(root.variables["t"], [0.0, 1.0])

        root.close()
Ejemplo n.º 16
0
def test_names_keyword(tmpdir):
    field = RasterModelGrid((4, 3))
    field.add_field("node", "topographic__elevation", np.arange(12.))
    field.add_field("node", "uplift_rate", 2. * np.arange(12.))

    with tmpdir.as_cwd():
        write_raster_netcdf(
            "test.nc", field, format="NETCDF3_64BIT", names="uplift_rate"
        )

        root = nc.Dataset("test.nc", "r", format="NETCDF3_64BIT")

        assert "topographic__elevation" not in root.variables
        assert "uplift_rate" in root.variables

        assert_array_equal(
            root.variables["uplift_rate"][:],
            [[[0., 2., 4.], [6., 8., 10.], [12., 14., 16.], [18., 20., 22.]]],
        )
        assert "nt" in root.dimensions
        assert len(root.dimensions["nt"]) == 1

        root.close()