Ejemplo n.º 1
0
def test_names_keyword_with_bad_name():
    grid = RasterModelGrid((4, 5), spacing=(2., 2.))
    grid.add_field('node', 'air__temperature', np.arange(20.))

    with cdtemp() as _:
        assert_raises(ValueError, write_esri_ascii, 'test.asc', grid,
                      names='not_a_name')
Ejemplo n.º 2
0
def test_degenerate_drainage():
    """
    This "hourglass" configuration should be one of the hardest to correctly
    re-route.
    """
    mg = RasterModelGrid(9, 5)
    z_init = mg.node_x.copy()*0.0001 + 1.
    lake_pits = np.array([7, 11, 12, 13, 17, 27, 31, 32, 33, 37])
    z_init[lake_pits] = -1.
    z_init[22] = 0.  # the common spill pt for both lakes
    z_init[21] = 0.1  # an adverse bump in the spillway
    z_init[20] = -0.2  # the spillway
    z = mg.add_field('node', 'topographic__elevation', z_init)

    fr = FlowRouter(mg)
    lf = DepressionFinderAndRouter(mg)
    fr.route_flow()
    lf.map_depressions()

    correct_A = np.array([ 0.,   0.,   0.,   0.,   0.,
                           0.,   1.,   3.,   1.,   0.,
                           0.,   5.,   1.,   2.,   0.,
                           0.,   1.,  10.,   1.,   0.,
                          21.,  21.,   1.,   1.,   0.,
                           0.,   1.,   9.,   1.,   0.,
                           0.,   3.,   1.,   2.,   0.,
                           0.,   1.,   1.,   1.,   0.,
                           0.,   0.,   0.,   0.,   0.])
    
    thelake = np.concatenate((lake_pits, [22])).sort()

    assert_array_almost_equal(mg.at_node['drainage_area'], correct_A)
Ejemplo n.º 3
0
def read_netcdf(nc_file, reshape=False, just_grid=False):
    """
    Reads the NetCDF file *nc_file*, and writes it to the fields of a new
    RasterModelGrid, which it then returns.
    Check the names of the fields in the returned grid with
    grid.at_nodes.keys().
    """
    try:
        root = nc.netcdf_file(nc_file, 'r', version=2)
    except TypeError:
        root = nc4.Dataset(nc_file, 'r', format='NETCDF4')

    shape = _read_netcdf_grid_shape(root)
    spacing = _read_netcdf_grid_spacing(root)

    assert(len(shape) == 2)
    assert(len(spacing) == 2)
    if spacing[0] != spacing[1]:
        raise NotRasterGridError()

    grid = RasterModelGrid(num_rows=shape[0], num_cols=shape[1], dx=spacing[0])

    if not just_grid:
        fields = _read_netcdf_structured_data(root)
        for (name, values) in fields.items():
            grid.add_field('node', name, values)

    root.close()

    return grid
Ejemplo n.º 4
0
def setup_dans_grid4():
    """
    Create a 10x10 test grid with two well defined holes in it, into an
    inclined surface. This time, one of the holes is a stupid shape, which
    will require the component to arrange flow back "uphill".
    """
    global hf, fr, mg
    global z, depr_outlet_target
    global lake, lake1, lake2, outlet, outlet_array

    lake1 = np.array([34, 35, 36, 44, 45, 46, 54, 55, 56, 65, 74])
    lake2 = np.array([78, 87, 88])
    guard_nodes = np.array([23, 33, 53, 63, 73, 83])
    lake = np.concatenate((lake1, lake2))
    outlet = 35  # shouldn't be needed
    outlet_array = np.array([outlet])

    mg = RasterModelGrid(10, 10, 1.)

    z = np.ones(100, dtype=float)
    # add slope
    z += mg.node_x
    z[guard_nodes] += 0.001  # forces the flow out of a particular node
    z[lake] = 0.

    depr_outlet_target = np.empty(100, dtype=float)
    depr_outlet_target.fill(XX)
    depr_outlet_target = XX  # not well defined in this simplest case...?

    mg.add_field('node', 'topographic__elevation', z, units='-')

    fr = FlowRouter(mg)
Ejemplo n.º 5
0
def test_netcdf_write():
    """Test generic write_netcdf."""
    if not WITH_NETCDF4:
        raise SkipTest('netCDF4 package not installed')

    field = RasterModelGrid(4, 3)
    field.add_field('node', 'topographic__elevation', np.arange(12.))

    with cdtemp() as _:
        write_netcdf('test.nc', field, format='NETCDF4')
        root = nc.Dataset('test.nc', 'r', format='NETCDF4')

        assert_equal(set(root.dimensions), set(['ni', 'nj', 'nt']))
        assert_equal(len(root.dimensions['ni']), 3)
        assert_equal(len(root.dimensions['nj']), 4)
        assert_true(len(root.dimensions['nt']), 1)
        assert_true(root.dimensions['nt'].isunlimited())

        assert_equal(set(root.variables),
                     set(['x', 'y', 'topographic__elevation']))

        assert_array_equal(root.variables['x'][:].flat,
                           np.array([0., 1., 2., 0., 1., 2., 0., 1., 2.,
                                     0., 1., 2., ]))
        assert_array_equal(root.variables['y'][:].flat,
                           np.array([0., 0., 0., 1., 1., 1., 2., 2., 2.,
                                     3., 3., 3., ]))
        assert_array_equal(root.variables['topographic__elevation'][:].flat,
                           field.at_node['topographic__elevation'])

        root.close()
Ejemplo n.º 6
0
def test_run_one_step():
    from landlab import RasterModelGrid
    import numpy as np
    from landlab.components.overland_flow import KinwaveOverlandFlowModel

    grid = RasterModelGrid((10, 10), spacing=0.5)
    grid.add_zeros('node', 'topographic__elevation', dtype=float)
    grid.add_zeros('node', 'topographic__gradient')

    topo_arr = np.ones(100).reshape(10, 10)
    i=0
    while i <= 9:
        topo_arr[:, i]  = 5 + (0.002*i)
        i+=1
    topo_arr = topo_arr.flatten()
    grid['node']['topographic__elevation'] = topo_arr
    KinWaveOF = KinwaveOverlandFlowModel(grid, precip_rate=100.,
        precip_duration=1.0, roughness=0.02)

    KinWaveOF.run_one_step(60)

    # I'll admit this is very non-robust. Solution roughly based on plot #9
    # from Heng et. al, (2009): "Modeling overland flow and soil eroion on
    # non uniform hillslopes: A finite volume scheme." They do not provide the
    # numerical solution but the plots match...
    max_h_mm = max(grid['node']['surface_water__depth']) * 1000.
    np.testing.assert_almost_equal(max_h_mm, 1.66666666667)
def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--n-loads', type=int, default=16,
                        help='Number of loads to apply')
    parser.add_argument('--shape', type=int, default=200,
                        help='Number rows and columns')
    parser.add_argument('--spacing', type=int, default=5e3,
                        help='Spading between rows and columns (m)')
    parser.add_argument('--n-procs', type=int, default=1,
                        help='Number of processors to use')
    parser.add_argument('--plot', action='store_true', default=False,
                        help='Plot an image of the total deflection')

    args = parser.parse_args()

    shape = (args.shape, args.shape)
    spacing = (args.spacing, args.spacing)

    load_locs = get_random_load_locations(shape, args.n_loads)
    load_sizes = get_random_load_magnitudes(args.n_loads)

    grid = RasterModelGrid(shape[0], shape[1], spacing[0])

    flex = FlexureComponent(grid, method='flexure')

    put_loads_on_grid(grid, load_locs, load_sizes)

    flex.update(n_procs=args.n_procs)

    grid.imshow('node', 'lithosphere__elevation', symmetric_cbar=False,
                cmap='spectral', show=True) 
Ejemplo n.º 8
0
def test_id_as_array_with_one_interior():
    rmg = RasterModelGrid(5, 5)
    assert_array_equal(
        rmg.node_has_boundary_neighbor(np.arange(25)),
        np.array(
            [
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                False,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
            ]
        ),
    )
Ejemplo n.º 9
0
def test_D_infinity_flat_closed_upper():
    mg = RasterModelGrid((5, 4), xy_spacing=(1, 1))
    z = mg.add_zeros("node", "topographic__elevation")
    z[mg.core_nodes] -= 1
    mg.set_closed_boundaries_at_grid_edges(
        bottom_is_closed=True,
        left_is_closed=True,
        right_is_closed=True,
        top_is_closed=True,
    )

    fd = FlowDirectorDINF(mg)
    fd.run_one_step()

    node_ids = np.arange(mg.number_of_nodes)
    true_recievers = -1 * np.ones(fd.receivers.shape)
    true_recievers[:, 0] = node_ids

    true_proportions = np.zeros(fd.proportions.shape)
    true_proportions[:, 0] = 1

    assert_array_equal(fd.receivers, true_recievers)
    assert_array_equal(
        np.round(fd.proportions, decimals=6), np.round(true_proportions, decimals=6)
    )
def test_calculate_landslide_probability_lognormal_method():
    """Testing the main method 'calculate_landslide_probability()' with
    'lognormal' method. 
    """
    grid_2 = RasterModelGrid((5, 4), spacing=(0.2, 0.2))
    gridnum = grid_2.number_of_nodes
    np.random.seed(seed=6)
    grid_2.at_node['topographic__slope'] = np.random.rand(gridnum)
    scatter_dat = np.random.randint(1, 10, gridnum)
    grid_2.at_node['topographic__specific_contributing_area']= (
             np.sort(np.random.randint(30, 900, gridnum)))
    grid_2.at_node['soil__transmissivity']= (
             np.sort(np.random.randint(5, 20, gridnum), -1))
    grid_2.at_node['soil__mode_total_cohesion']= (
             np.sort(np.random.randint(30, 900, gridnum)))
    grid_2.at_node['soil__minimum_total_cohesion']= (
             grid_2.at_node['soil__mode_total_cohesion'] - scatter_dat)
    grid_2.at_node['soil__maximum_total_cohesion']= (
             grid_2.at_node['soil__mode_total_cohesion'] + scatter_dat)
    grid_2.at_node['soil__internal_friction_angle']= (
             np.sort(np.random.randint(26, 37, gridnum)))
    grid_2.at_node['soil__thickness']= (
             np.sort(np.random.randint(1, 10, gridnum)))
    grid_2.at_node['soil__density']= (2000. * np.ones(gridnum))

    ls_prob_lognormal = LandslideProbability(grid_2, number_of_iterations=10,
        groundwater__recharge_distribution='lognormal',
        groundwater__recharge_mean=5.,
        groundwater__recharge_standard_deviation=0.25,
        seed=6)
    ls_prob_lognormal.calculate_landslide_probability()
    np.testing.assert_almost_equal(
        grid_2.at_node['landslide__probability_of_failure'][5], 0.8)
    np.testing.assert_almost_equal(
        grid_2.at_node['landslide__probability_of_failure'][9], 0.4)
Ejemplo n.º 11
0
def test_id_as_array():
    rmg = RasterModelGrid((4, 5))
    assert_array_equal(
        rmg.node_has_boundary_neighbor(np.arange(20)),
        np.array(
            [
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
                True,
            ]
        ),
    )
def test_infinite_taylor_error():
    mg = RasterModelGrid((5, 5))
    z = mg.add_zeros("node", "topographic__elevation")
    z += mg.node_x.copy() ** 4
    Cdiff = TaylorNonLinearDiffuser(mg, nterms=400)
    with pytest.raises(RuntimeError):
        Cdiff.soilflux(10)
Ejemplo n.º 13
0
def test_run_one_step():
    grid = RasterModelGrid((10, 10), xy_spacing=25)
    grid.add_ones("node", "soil_water_infiltration__depth", dtype=float)
    grid.add_ones("node", "surface_water__depth")
    hydraulic_conductivity = 2.5 * (10 ** -6)
    grid["node"]["surface_water__depth"] *= 5.0
    grid["node"]["soil_water_infiltration__depth"] *= 10 ** -5
    SI = SoilInfiltrationGreenAmpt(
        grid,
        hydraulic_conductivity=hydraulic_conductivity,
        soil_bulk_density=1700.,
        rock_density=2650.,
        initial_soil_moisture_content=0.2,
        soil_type="silt loam",
        volume_fraction_coarse_fragments=0.6,
        coarse_sed_flag=False,
        surface_water_minimum_depth=1.e-7,
        soil_pore_size_distribution_index=None,
        soil_bubbling_pressure=None,
        wetting_front_capillary_pressure_head=None,
    )

    SI.run_one_step(dt=5)
    np.testing.assert_almost_equal(
        grid["node"]["surface_water__depth"][0], 3.97677483519, decimal=6
    )
Ejemplo n.º 14
0
def test_netcdf_write():
    field = RasterModelGrid(4, 3)
    #field.new_field_location('node', 12.)
    values = np.arange(12.)
    field.add_field('node', 'planet_surface__elevation', values)

    write_netcdf('test.nc', field)

    import netCDF4 as nc

    root = nc.Dataset('test.nc', 'r', format='NETCDF4')
    assert_equal(set(root.dimensions), set(['ni', 'nj', 'nt']))
    assert_equal(len(root.dimensions['ni']), 3)
    assert_equal(len(root.dimensions['nj']), 4)
    assert_true(len(root.dimensions['nt']), 1)
    assert_true(root.dimensions['nt'].isunlimited())

    assert_equal(set(root.variables),
                 set(['x', 'y', 'planet_surface__elevation']))

    assert_list_equal(list(root.variables['x'][:].flat),
                      [0., 1., 2.,
                       0., 1., 2.,
                       0., 1., 2.,
                       0., 1., 2., ])
    assert_list_equal(list(root.variables['y'][:].flat),
                      [0., 0., 0.,
                       1., 1., 1.,
                       2., 2., 2.,
                       3., 3., 3., ])
    assert_list_equal(
        list(root.variables['planet_surface__elevation'][:].flat),
        range(12))
    root.close()
def test_raise_stability_error():
    mg = RasterModelGrid((5, 5))
    z = mg.add_zeros("node", "topographic__elevation")
    z += mg.node_x.copy() ** 2
    Cdiff = TaylorNonLinearDiffuser(mg)
    with pytest.raises(RuntimeError):
        Cdiff.soilflux(10, if_unstable="raise")
Ejemplo n.º 16
0
def test_run_with_2_fn_args():
    mg = RasterModelGrid((3, 5), xy_spacing=(2, 1))
    mg.set_closed_boundaries_at_grid_edges(True, True, False, True)
    mg.add_field("topographic__elevation", mg.node_x + mg.node_y, at="node")

    def mylossfunction(qw, nodeID):
        return 0.5 * qw

    fa = LossyFlowAccumulator(
        mg,
        "topographic__elevation",
        flow_director=FlowDirectorSteepest,
        routing="D4",
        loss_function=mylossfunction,
    )
    fa.run_one_step()

    assert np.allclose(
        mg.at_node["drainage_area"].reshape(mg.shape),
        np.array([[0., 0., 0., 0., 0.], [6., 6., 4., 2., 0.], [0., 0., 0., 0., 0.]]),
    )
    assert np.allclose(
        mg.at_node["surface_water__discharge"].reshape(mg.shape),
        np.array(
            [
                [0.00, 0.00, 0.00, 0.00, 0.00],
                [1.75, 3.50, 3.00, 2.00, 0.00],
                [0.00, 0.00, 0.00, 0.00, 0.00],
            ]
        ),
    )
Ejemplo n.º 17
0
 def _test():
     rmg = RasterModelGrid(4, 5)
     number_of_elements = rmg.number_of_elements(element)
     rtn_values = rmg.add_ones(element, 'name')
     assert_is(rtn_values, rmg.field_values(element, 'name'))
     assert_array_equal(
         rtn_values, np.ones(number_of_elements, dtype=np.float))
def test_out_array():
    """Test using the out keyword."""
    rmg = RasterModelGrid((4, 5), xy_spacing=(2, 5))
    values_at_nodes = np.arange(20)

    output_array = np.empty(rmg.number_of_links)
    rtn_array = rmg.calc_grad_at_link(values_at_nodes, out=output_array)
    assert_array_equal(
        rtn_array[rmg.active_links],
        np.array(
            [
                1.0,
                1.0,
                1.0,
                0.5,
                0.5,
                0.5,
                0.5,
                1.0,
                1.0,
                1.0,
                0.5,
                0.5,
                0.5,
                0.5,
                1.0,
                1.0,
                1.0,
            ]
        ),
    )
    assert rtn_array is output_array
def test_unit_spacing():
    """Test with a grid with unit spacing."""
    rmg = RasterModelGrid((4, 5))
    values_at_nodes = np.arange(20)
    grads = rmg.calc_grad_at_link(values_at_nodes)[rmg.active_links]

    assert_array_equal(
        grads,
        np.array(
            [
                5.0,
                5.0,
                5.0,
                1.0,
                1.0,
                1.0,
                1.0,
                5.0,
                5.0,
                5.0,
                1.0,
                1.0,
                1.0,
                1.0,
                5.0,
                5.0,
                5.0,
            ]
        ),
    )

    diffs = rmg.calc_diff_at_link(values_at_nodes)[rmg.active_links]
    assert_array_equal(grads, diffs)
Ejemplo n.º 20
0
def test_dx_equals_zero():
    """Test a vertical fault trace."""
    grid = RasterModelGrid((6, 6), xy_spacing=10)

    grid.add_zeros("node", "topographic__elevation")

    param_dict = {
        "faulted_surface": "topographic__elevation",
        "fault_dip_angle": 90.0,
        "fault_throw_rate_through_time": {"time": [0, 9, 10], "rate": [0, 0, 0.05]},
        "fault_trace": {"y1": 0, "x1": 30, "y2": 30, "x2": 30},
        "include_boundaries": True,
    }

    nf = NormalFault(grid, **param_dict)

    out = np.array(
        [
            [True, True, True, False, False, False],
            [True, True, True, False, False, False],
            [True, True, True, False, False, False],
            [True, True, True, False, False, False],
            [True, True, True, False, False, False],
            [True, True, True, False, False, False],
        ],
        dtype=bool,
    )

    assert_array_equal(nf.faulted_nodes.reshape(grid.shape), out)
Ejemplo n.º 21
0
def test_save_esri_ascii(tmpdir):
    grid = RasterModelGrid(4, 5, 2.)
    grid.add_field('node', 'air__temperature', np.arange(20.))

    with tmpdir.as_cwd():
        grid.save('test.asc', format='esri-ascii')
        assert os.path.isfile('test.asc')
Ejemplo n.º 22
0
def test_error_for_to_many_with_depression():
    """Check that an error is thrown when to_many methods started DF."""

    mg0 = RasterModelGrid((10, 10), spacing=(1, 1))
    z0 = mg0.add_field(
        "topographic__elevation", mg0.node_x ** 2 + mg0.node_y ** 2, at="node"
    )

    mg1 = RasterModelGrid((10, 10), spacing=(1, 1))
    z1 = mg1.add_field(
        "topographic__elevation", mg1.node_x ** 2 + mg1.node_y ** 2, at="node"
    )

    with pytest.raises(NotImplementedError):
        FlowAccumulator(
            mg0, flow_director="MFD", depression_finder="DepressionFinderAndRouter"
        )
    with pytest.raises(NotImplementedError):
        FlowAccumulator(
            mg0, flow_director="DINF", depression_finder="DepressionFinderAndRouter"
        )

    fa0 = FlowAccumulator(mg0, flow_director="MFD")
    fa0.run_one_step()
    with pytest.raises(NotImplementedError):
        DepressionFinderAndRouter(mg0)

    fa1 = FlowAccumulator(mg1, flow_director="DINF")
    fa1.run_one_step()
    with pytest.raises(NotImplementedError):
        DepressionFinderAndRouter(mg1)
Ejemplo n.º 23
0
def test_no_reroute():
    mg = RasterModelGrid((5, 5), xy_spacing=2.)
    z = mg.add_zeros("node", "topographic__elevation", dtype=float)
    z[1] = -1.
    z[6] = -2.
    z[19] = -2.
    z[18] = -1.
    z[17] = -3.
    fd = FlowDirectorSteepest(mg)
    fa = FlowAccumulator(mg)
    lmb = LakeMapperBarnes(
        mg,
        method="Steepest",
        fill_flat=True,
        redirect_flow_steepest_descent=True,
        track_lakes=True,
    )

    lake_dict = {1: deque([6]), 18: deque([17])}
    fd.run_one_step()  # fill the director fields
    fa.run_one_step()  # get a drainage_area
    orig_surf = lmb._track_original_surface()
    lmb._redirect_flowdirs(orig_surf, lake_dict)

    assert mg.at_node["flow__receiver_node"][6] == 1
    assert mg.at_node["flow__receiver_node"][17] == 18
    assert mg.at_node["flow__receiver_node"][18] == 19
Ejemplo n.º 24
0
def test_sheetflow():
    flux = np.array(
        [0.00000000,  0.00000000,  0.00000000,  0.00000000,  0.00000000,
         0.00000000,  0.00000000,  0.00000000,  0.00000000,  0.00000000,
         0.00000000,  0.50000000,  1.35677118,  2.18064899,  2.98289061,
         3.77167837,  4.55070068,  5.32231777,  6.08818915,  6.34956448,
         0.00000000,  0.50000000,  1.64322882,  2.77444053,  3.90022802,
         5.01817926,  6.12943159,  7.23518857,  8.33656075,  8.93446352,
         0.00000000,  0.50000000,  1.50000000,  2.54491048,  3.60279934,
         4.66824237,  5.73835212,  6.81180077,  7.88776947,  8.46568929,
         0.00000000,  0.50000000,  1.50000000,  2.50000000,  3.51408202,
         4.54190001,  5.58151561,  6.63069288,  7.68748063,  8.25028271,
         0.00000000,  0.50000000,  1.50000000,  2.50000000,  3.51408202,
         4.54190001,  5.58151561,  6.63069288,  7.68748063,  8.25028271,
         0.00000000,  0.50000000,  1.50000000,  2.54491048,  3.60279934,
         4.66824237,  5.73835212,  6.81180077,  7.88776947,  8.46568929,
         0.00000000,  0.50000000,  1.64322882,  2.77444053,  3.90022802,
         5.01817926,  6.12943159,  7.23518857,  8.33656075,  8.93446352,
         0.00000000,  0.50000000,  1.35677118,  2.18064899,  2.98289061,
         3.77167837,  4.55070068,  5.32231777,  6.08818915,  6.34956448,
         0.00000000,  0.00000000,  0.00000000,  0.00000000,  0.00000000,
         0.00000000,  0.00000000,  0.00000000,  0.00000000,  0.00000000]
    )

    mg = RasterModelGrid((NROWS, NCOLS), (DX, DX))
    z = (3000. - mg.node_x) * 0.5
    mg.at_node['topographic__elevation'] = z

    mg.set_closed_boundaries_at_grid_edges(False, True, True, True)
    mg.at_node['water__volume_flux_in'] = np.ones_like(z, dtype=float)

    pfr = PotentialityFlowRouter(mg, INPUTS)
    pfr.route_flow(route_on_diagonals=True)

    assert_array_almost_equal(mg.at_node['water__volume_flux_magnitude'], flux)
Ejemplo n.º 25
0
def test_MFD_S_slope_w_diag():
    mg = RasterModelGrid((10, 10))
    mg.add_field("topographic__elevation", mg.node_y, at="node")
    fa = FlowAccumulator(mg, flow_director="FlowDirectorMFD", diagonals=True)
    fa.run_one_step()

    # this one should part to south west, part to south, and part to southeast
    sw_diags = mg.diagonal_adjacent_nodes_at_node[:, 2]
    se_diags = mg.diagonal_adjacent_nodes_at_node[:, 3]
    s_links = mg.adjacent_nodes_at_node[:, 3]
    node_ids = np.arange(mg.number_of_nodes)
    true_recievers = -1 * np.ones(fa.flow_director.receivers.shape)
    true_recievers[mg.core_nodes, 3] = s_links[mg.core_nodes]
    true_recievers[mg.core_nodes, 6] = sw_diags[mg.core_nodes]
    true_recievers[mg.core_nodes, 7] = se_diags[mg.core_nodes]
    true_recievers[mg.boundary_nodes, 0] = node_ids[mg.boundary_nodes]

    true_proportions = np.zeros(fa.flow_director.proportions.shape)
    true_proportions[mg.boundary_nodes, 0] = 1

    total_sum_of_slopes = 1. + 2. * (1. / 2. ** 0.5)

    true_proportions[mg.core_nodes, 3] = 1.0 / total_sum_of_slopes
    true_proportions[mg.core_nodes, 6] = (1. / 2. ** 0.5) / total_sum_of_slopes
    true_proportions[mg.core_nodes, 7] = (1. / 2. ** 0.5) / total_sum_of_slopes

    assert_array_equal(true_recievers, fa.flow_director.receivers)
    assert_array_almost_equal(true_proportions, fa.flow_director.proportions)
Ejemplo n.º 26
0
def setup_dans_grid2():
    """
    Create a 10x10 test grid with a well defined hole in it, from a flat
    surface.
    """
    global hf, mg
    global z, depr_outlet_target
    global lake, outlet, lake_code, outlet_array

    lake = np.array([44, 45, 46, 54, 55, 56, 64, 65, 66])
    outlet = 35  # shouldn't be needed
    lake_code = 44
    outlet_array = np.array([outlet])

    mg = RasterModelGrid(10, 10, 1.)

    z = np.ones(100, dtype=float)
    z[lake] = 0.

    depr_outlet_target = np.empty(100, dtype=float)
    depr_outlet_target.fill(XX)
    depr_outlet_target = XX  # not well defined in this simplest case...?

    mg.add_field('node', 'topographic__elevation', z, units='-')

    hf = SinkFiller(mg)
Ejemplo n.º 27
0
def setup_dans_grid3():
    """
    Create a 10x10 test grid with two well defined holes in it, into an
    inclined surface.
    """
    global hf, fr, mg
    global z, depr_outlet_target
    global lake, lake1, lake2, outlet, outlet_array, rcvr

    lake1 = np.array([34, 35, 36, 44, 45, 46, 54, 55, 56])
    lake2 = np.array([77, 78, 87, 88])
    guard_nodes = np.array([23, 33, 53, 63])
    lake = np.concatenate((lake1, lake2))
    outlet = 35  # shouldn't be needed
    outlet_array = np.array([outlet])

    mg = RasterModelGrid(10, 10, 1.)

    z = np.ones(100, dtype=float)
    # add slope
    z += mg.node_x
    z[guard_nodes] += 0.001
    z[lake] = 0.

    depr_outlet_target = np.empty(100, dtype=float)
    depr_outlet_target.fill(XX)
    depr_outlet_target = XX  # not well defined in this simplest case...?

    mg.add_field('node', 'topographic__elevation', z, units='-')

    fr = FlowRouter(mg)
Ejemplo n.º 28
0
def test_closed_up_grid():
    mg = RasterModelGrid((5, 5))
    for edge in ("left", "right", "top", "bottom"):
        mg.status_at_node[mg.nodes_at_edge(edge)] = CLOSED_BOUNDARY
    mg.add_zeros("node", "topographic__elevation", dtype=float)
    with pytest.raises(ValueError):
        LakeMapperBarnes(mg)
Ejemplo n.º 29
0
def setup_dans_grid1():
    """
    Create a 7x7 test grid with a well defined hole in it.
    """
    global hf, mg
    global z, r_new, r_old, A_new, A_old, s_new, depr_outlet_target
    global lake, outlet, lake_code, outlet_array

    mg = RasterModelGrid(7, 7, 1.)

    z = np.array([0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,
                  0.0,  2.0,  2.0,  2.0,  2.0,  2.0,  0.0,
                  0.0,  2.0,  1.6,  1.5,  1.6,  2.0,  0.0,
                  0.0,  2.0,  1.7,  1.6,  1.7,  2.0,  0.0,
                  0.0,  2.0,  1.8,  2.0,  2.0,  2.0,  0.0,
                  0.0,  1.0,  0.6,  1.0,  1.0,  1.0,  0.0,
                  0.0,  0.0, -0.5,  0.0,  0.0,  0.0,  0.0]).flatten()

    depr_outlet_target = np.array([XX, XX, XX, XX, XX, XX, XX,
                                   XX, XX, XX, XX, XX, XX, XX,
                                   XX, XX, 30, 30, 30, XX, XX,
                                   XX, XX, 30, 30, 30, XX, XX,
                                   XX, XX, XX, XX, XX, XX, XX,
                                   XX, XX, XX, XX, XX, XX, XX,
                                   XX, XX, XX, XX, XX, XX, XX]).flatten()

    lake = np.array([16, 17, 18, 23, 24, 25])
    outlet = 30
    lake_code = 17
    outlet_array = np.array([outlet])

    mg.add_field('node', 'topographic__elevation', z, units='-')

    hf = SinkFiller(mg)
Ejemplo n.º 30
0
def test_nodes_around_point():
    rmg = RasterModelGrid((4, 5), spacing=1.)
    surrounding_ids = rmg.nodes_around_point(2.1, 1.1)
    assert_array_equal(surrounding_ids, np.array([7, 12, 13, 8]))

    surrounding_ids = rmg.nodes_around_point(2.1, .9)
    assert_array_equal(surrounding_ids, np.array([2, 7, 8, 3]))
Ejemplo n.º 31
0
def test_youngs_attribute():
    grid = RasterModelGrid((20, 20), xy_spacing=10e3)
    for val in (10e3, 1e3):
        assert Flexure(grid, youngs=val).youngs == pytest.approx(val)
Ejemplo n.º 32
0
def test_sp_old():

    uplift = 0.001
    dt = 1.0
    time_to_run = 10.0
    mg = RasterModelGrid((10, 5))
    mg.set_closed_boundaries_at_grid_edges(False, False, True, True)

    mg.add_zeros("topographic__elevation", at="node")
    z = mg.zeros(at="node")
    numpy.random.seed(0)
    mg["node"]["topographic__elevation"] = z + numpy.random.rand(len(z)) / 1000.0

    fr = FlowAccumulator(mg, flow_director="D8")
    sp = StreamPowerEroder(mg, K_sp=0.1, m_sp=0.5, n_sp=1.0, threshold_sp=0.0)
    elapsed_time = 0.0
    while elapsed_time < time_to_run:
        if elapsed_time + dt > time_to_run:
            dt = time_to_run - elapsed_time
        fr.run_one_step()
        sp.run_one_step(dt)
        mg.at_node["topographic__elevation"][mg.core_nodes] += uplift * dt
        elapsed_time += dt

    z_trg = numpy.array(
        [
            5.48813504e-04,
            7.15189366e-04,
            6.02763376e-04,
            5.44883183e-04,
            4.23654799e-04,
            6.45894113e-04,
            1.01830760e-02,
            9.58036770e-03,
            6.55865452e-03,
            3.83441519e-04,
            7.91725038e-04,
            1.00142749e-02,
            8.80798884e-03,
            5.78387585e-03,
            7.10360582e-05,
            8.71292997e-05,
            9.81911417e-03,
            9.52243406e-03,
            7.55093226e-03,
            8.70012148e-04,
            9.78618342e-04,
            1.00629755e-02,
            8.49253798e-03,
            5.33216680e-03,
            1.18274426e-04,
            6.39921021e-04,
            9.88956320e-03,
            9.47119567e-03,
            6.43790696e-03,
            4.14661940e-04,
            2.64555612e-04,
            1.00450743e-02,
            8.37262908e-03,
            5.21540904e-03,
            1.87898004e-05,
            6.17635497e-04,
            9.21286940e-03,
            9.34022513e-03,
            7.51114450e-03,
            6.81820299e-04,
            3.59507901e-04,
            6.19166921e-03,
            7.10456176e-03,
            6.62585507e-03,
            6.66766715e-04,
            6.70637870e-04,
            2.10382561e-04,
            1.28926298e-04,
            3.15428351e-04,
            3.63710771e-04,
        ]
    )

    assert_array_almost_equal(mg.at_node["topographic__elevation"], z_trg)
Ejemplo n.º 33
0
def read_netcdf(nc_file, just_grid=False):
    """Create a :class:`~.RasterModelGrid` from a netcdf file.

    Create a new :class:`~.RasterModelGrid` from the netcdf file, *nc_file*.
    If the netcdf file also contains data, add that data to the grid's fields.
    To create a new grid without any associated data from the netcdf file,
    set the *just_grid* keyword to ``True``.

    Parameters
    ----------
    nc_file : str
        Name of a netcdf file.
    just_grid : boolean, optional
        Create a new grid but don't add value data.

    Returns
    -------
    :class:`~.RasterModelGrid`
        A newly-created :class:`~.RasterModelGrid`.

    Examples
    --------
    Import :func:`read_netcdf` and the path to an example netcdf file included
    with landlab.

    >>> from landlab.io.netcdf import read_netcdf
    >>> from landlab.io.netcdf import NETCDF4_EXAMPLE_FILE

    Create a new grid from the netcdf file. The example grid is a uniform
    rectilinear grid with 4 rows and 3 columns of nodes with unit spacing.
    The data file also contains data defined at the nodes for the grid for
    a variable called, *surface__elevation*.

    >>> grid = read_netcdf(NETCDF4_EXAMPLE_FILE)
    >>> grid.shape == (4, 3)
    True
    >>> grid.dy, grid.dx
    (1.0, 1.0)
    >>> [str(k) for k in grid.at_node.keys()]
    ['surface__elevation']
    >>> grid.at_node['surface__elevation']
    array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
            11.])

    :func:`read_netcdf` will try to determine the format of the netcdf file.
    For example, the same call will also work for *netcdf3*-formatted files.

    >>> from landlab.io.netcdf import NETCDF3_64BIT_EXAMPLE_FILE
    >>> grid = read_netcdf(NETCDF3_64BIT_EXAMPLE_FILE)
    >>> grid.shape == (4, 3)
    True
    >>> grid.dy, grid.dx
    (1.0, 1.0)
    """
    from landlab import RasterModelGrid

    try:
        root = nc.netcdf_file(nc_file, 'r', version=2)
    except TypeError:
        root = nc4.Dataset(nc_file, 'r', format='NETCDF4')

    try:
        node_coords = _read_netcdf_structured_grid(root)
    except ValueError:
        if ((len(root.variables['x'].dimensions) == 1)
                and (len(root.variables['y'].dimensions) == 1)):

            node_coords = _read_netcdf_raster_structured_grid(root)
        else:
            assert ValueError('x and y dimensions must both either be 2D '
                              '(nj, ni) or 1D (ni,) and (nj).')

    assert len(node_coords) == 2

    spacing = _get_raster_spacing(node_coords)

    shape = node_coords[0].shape

    grid = RasterModelGrid(shape, spacing=spacing)

    if not just_grid:
        fields = _read_netcdf_structured_data(root)
        for (name, values) in fields.items():
            grid.add_field('node', name, values)

    root.close()

    return grid
Ejemplo n.º 34
0
def veg():
    grid = RasterModelGrid((20, 20), xy_spacing=10e0)
    grid.add_zeros("vegetation__plant_functional_type", at="cell", dtype=int)
    grid.add_zeros("surface__evapotranspiration", at="cell", dtype=float)
    grid.add_zeros("vegetation__water_stress", at="cell", dtype=float)
    grid.add_zeros("surface__potential_evapotranspiration_rate",
                   at="cell",
                   dtype=float)
    grid.add_zeros("surface__potential_evapotranspiration_30day_mean",
                   at="cell",
                   dtype=float)

    return Vegetation(grid)
Ejemplo n.º 35
0
def test_grid_with_no_fields(tmpdir):
    grid = RasterModelGrid((4, 5), spacing=(2., 2.))
    with tmpdir.as_cwd():
        with pytest.raises(ValueError):
            write_esri_ascii('test.asc', grid)
Ejemplo n.º 36
0
def test_rho_mantle_attribute():
    grid = RasterModelGrid((20, 20), xy_spacing=10e3)
    for val in (10e3, 1e3):
        assert Flexure(grid, rho_mantle=val).rho_mantle == pytest.approx(val)
Ejemplo n.º 37
0
def test_gravity_attribute():
    grid = RasterModelGrid((20, 20), xy_spacing=10e3)
    for val in (10e3, 1e3):
        assert Flexure(grid, gravity=val).gravity == pytest.approx(val)
Ejemplo n.º 38
0
def test_method_names():
    grid = RasterModelGrid((20, 20), xy_spacing=10e3)
    assert Flexure(grid, method="airy").method == "airy"
    assert Flexure(grid, method="flexure").method == "flexure"
    with pytest.raises(ValueError):
        Flexure(grid, method="bad-name")
Ejemplo n.º 39
0
ncols = inputs.read_int('ncols')
dx = inputs.read_float('dx')
leftmost_elev = inputs.read_float('leftmost_elevation')
initial_slope = inputs.read_float('initial_slope')
uplift_rate = inputs.read_float('uplift_rate')
runtime = inputs.read_float('total_time')
dt = inputs.read_float('dt')
nt = int(
    runtime //
    dt)  #"//" means "divide and truncate" ("%" means "division remainder")
uplift_per_step = uplift_rate * dt

#Instantiate the grid object
#We know which parameters are needed for input by inspecting the function where it lives, in landlab.grid.raster
#We could also look at the documentation for landlab found online (http://the-landlab.readthedocs.org)
mg = RasterModelGrid(nrows, ncols, dx)
##create the elevation field in the grid:
#create the field
mg.create_node_array_zeros('topographic_elevation')
z = mg.create_node_array_zeros(
) + leftmost_elev  #in our case, slope is zero, so the leftmost_elev is the mean elev
#put these values plus roughness into that field
mg['node']['topographic_elevation'] = z + np.random.rand(len(z)) / 100000.

#set up its boundary conditions (bottom, left, top, right)
#The mechanisms for this are all automated within the grid object
mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True)

# Display a message
print 'Running ...'
Ejemplo n.º 40
0
def test_eet_attribute():
    grid = RasterModelGrid((20, 20), xy_spacing=10e3)
    for val in (10e3, 1e3):
        assert Flexure(grid, eet=val).eet == pytest.approx(val)
    with pytest.raises(ValueError):
        assert Flexure(grid, eet=-10e3)
Ejemplo n.º 41
0
def setup_unit_grid():
    from landlab import RasterModelGrid
    global _GRID, _VALUES_AT_NODES
    _GRID = RasterModelGrid(4, 5)
    _VALUES_AT_NODES = np.arange(20.)
Ejemplo n.º 42
0
import pylab
from pylab import show
from landlab import RasterModelGrid
from landlab import ModelParameterDictionary
from landlab.plot.imshow import imshow_node_grid

inputs = ModelParameterDictionary('./diffusion_params.txt')
nrows = inputs.read_int('nrows')
ncols = inputs.read_int('ncols')
dx = inputs.read_float('dx')
dt = inputs.read_float('dt')
time_to_run = inputs.read_float('run_time')
init_elev = inputs.read_float('init_elev')
uplift_rate = inputs.read_float('uplift_rate')

mg = RasterModelGrid(nrows, ncols, dx)

#create the fields in the grid
mg.create_node_array_zeros('topographic__elevation')
z = mg.create_node_array_zeros() + init_elev
mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000.

mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True)

#instantiate:
dfn = LinearDiffuser(mg, './diffusion_params.txt')

#perform the loop:
elapsed_time = 0.  #total time in simulation
while elapsed_time < time_to_run:
    print elapsed_time
Ejemplo n.º 43
0
Ks = df_params['ksat']  #hydraulic conductivity [m/s]
n = df_params['n']  #drainable porosity [-]
b = df_params['b']  #characteristic depth  [m]
p = df_params['p']  #average precipitation rate [m/s]
tr = df_params['tr']  #mean storm duration [s]
tb = df_params['tb']  #mean interstorm duration [s]
ds = df_params['ds']  #mean storm depth [m]
T_h = 50 * df_params['Th']  #total hydrological time [s]
K = df_params['K']
Ksp = K / p  #see governing equation. If the discharge field is (Q/sqrt(A)) then streampower coeff is K/p
E0 = df_params['E0']

#initialize grid
dx = grid.dx
mg = RasterModelGrid(grid.shape, xy_spacing=dx)
mg.set_status_at_node_on_edges(right=mg.BC_NODE_IS_CLOSED, top=mg.BC_NODE_IS_CLOSED, \
                              left=mg.BC_NODE_IS_FIXED_VALUE, bottom=mg.BC_NODE_IS_CLOSED)
z = mg.add_zeros('node', 'topographic__elevation')
z[:] = elev
zb = mg.add_zeros('node', 'aquifer_base__elevation')
zb[:] = base
zwt = mg.add_zeros('node', 'water_table__elevation')
zwt[:] = wt

f = open('../post_proc/%s/dt_qs_s_%d.csv' % (base_output_path, ID), 'w')


def write_SQ(grid, r, dt, file=f):
    cores = grid.core_nodes
    h = grid.at_node["aquifer__thickness"]
Ejemplo n.º 44
0
def setup_3x3_grid():
    from landlab import RasterModelGrid
    global rmg_3x3
    rmg_3x3 = RasterModelGrid(3, 3)
Ejemplo n.º 45
0
Tg = df_params['Tg'][ID]
ksf = df_params['ksf'][ID]

output = {}
output["output_interval"] = 1000
output["output_fields"] = [
        "at_node:topographic__elevation",
        "at_node:aquifer_base__elevation",
        "at_node:water_table__elevation",
        ]
output["base_output_path"] = './data/steady_sp_hi_'
output["run_id"] = ID #make this task_id if multiple runs

#initialize grid
np.random.seed(12345)
grid = RasterModelGrid((125, 125), xy_spacing=v0)
grid.set_status_at_node_on_edges(
        right=grid.BC_NODE_IS_CLOSED,
        top=grid.BC_NODE_IS_CLOSED,
        left=grid.BC_NODE_IS_FIXED_VALUE,
        bottom=grid.BC_NODE_IS_CLOSED,
)
elev = grid.add_zeros('node', 'topographic__elevation')
elev[:] = b + 0.1*hg*np.random.rand(len(elev))
base = grid.add_zeros('node', 'aquifer_base__elevation')
wt = grid.add_zeros('node', 'water_table__elevation')
wt[:] = elev.copy()

#initialize components
gdp = GroundwaterDupuitPercolator(grid,
        porosity=n,
import random

#get the needed properties to build the grid:
input_file = './drive_sp_params.txt'
inputs = ModelParameterDictionary(input_file)
nrows = inputs.read_int('nrows')
ncols = inputs.read_int('ncols')
dx = inputs.read_float('dx')
uplift_rate = inputs.read_float('uplift_rate')
runtime = inputs.read_float('run_time')
dt = inputs.read_float('dt')
nt = int(runtime // dt)
uplift_per_step = uplift_rate * dt

#instantiate the grid object
mg = RasterModelGrid(nrows, ncols, dx)

boundary_node_list = mg.boundary_nodes

#set up its boundary conditions (bottom, right, top, left is inactive)
mg.set_inactive_boundaries(True, True, True, True)
mg.set_closed_boundaries_at_grid_edges(False, False, False, False)
mg.status_at_node[20] = FIXED_VALUE_BOUNDARY

##create the elevation field in the grid:
#create the field
mg.add_zeros('topographic__elevation', at='node')
z = mg.zeros(at='node') + init_elev
#put these values plus roughness into that field
mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 100000.
Ejemplo n.º 47
0
def test_director_adding_methods_are_equivalent_D8():
    """Check that different methods to specifying the director are the same."""

    mg0 = RasterModelGrid((10, 10), spacing=(1, 1))
    z0 = mg0.add_field('topographic__elevation',
                       mg0.node_x**2 + mg0.node_y**2,
                       at='node')
    fa0 = FlowAccumulator(mg0, flow_director='D8')
    fa0.run_one_step()

    mg1 = RasterModelGrid((10, 10), spacing=(1, 1))
    z1 = mg1.add_field('topographic__elevation',
                       mg1.node_x**2 + mg1.node_y**2,
                       at='node')
    fa1 = FlowAccumulator(mg1, flow_director='FlowDirectorD8')
    fa1.run_one_step()

    mg2 = RasterModelGrid((10, 10), spacing=(1, 1))
    z2 = mg2.add_field('topographic__elevation',
                       mg2.node_x**2 + mg2.node_y**2,
                       at='node')
    fa2 = FlowAccumulator(mg2, flow_director=FlowDirectorD8)
    fa2.run_one_step()

    mg3 = RasterModelGrid((10, 10), spacing=(1, 1))
    z3 = mg3.add_field('topographic__elevation',
                       mg3.node_x**2 + mg3.node_y**2,
                       at='node')
    fd = FlowDirectorD8(mg3)
    fa3 = FlowAccumulator(mg3, flow_director=fd)
    fa3.run_one_step()

    for key in mg0.at_node.keys():
        assert_array_equal(mg0.at_node[key], mg1.at_node[key])

        assert_array_equal(mg1.at_node[key], mg2.at_node[key])

        assert_array_equal(mg2.at_node[key], mg3.at_node[key])
Ejemplo n.º 48
0
def test_misc():
    grid = RasterModelGrid((3, 3))

    # test bad dimension:
    with pytest.raises(ValueError):
        DataRecord(
            grid,
            time=[0.0],
            data_vars={"mean_elev": (["time"], [100.0]), "test": (["bad_dim"], [12])},
        )
    # should return ValueError('Data variable dimensions must be time and/or'
    #                              'item_id')
    # test bad time format:
    with pytest.raises(TypeError):
        DataRecord(grid=grid, time="bad_time")
    # should return TypeError: Time must be a list or an array of length 1

    # test bad datavars format:
    with pytest.raises(TypeError):
        DataRecord(grid, time=[0.0], data_vars=["not a dict"])
    # should return TypeError(('Data variables (data_vars) passed to'
    #                                 ' DataRecord must be a dictionary (see '
    #                                 'documentation for valid structure)'))

    # test bad items format:
    with pytest.raises(TypeError):
        DataRecord(
            grid,
            time=[0.0],
            items=["not a dict"],
            data_vars={"mean_elevation": (["time"], np.array([100]))},
            attrs={"time_units": "y"},
        )
    # Should return TypeError(('You must provide an ''items'' dictionary '
    #                                 '(see documentation for required format)'))
    #
    with pytest.raises(TypeError):
        """Test bad items keys"""
        DataRecord(
            grid,
            time=[0.0],
            items={
                "grid_element": np.array([["node"], ["link"]]),
                "bad_key": np.array([[1], [3]]),
            },
            data_vars={"mean_elevation": (["time"], np.array([100]))},
            attrs={"time_units": "y"},
        )
    # Should return TypeError(('You must provide an ''items'' dictionary '
    #                                  '(see documentation for required format)'))
    with pytest.raises(TypeError):
        """Test bad attrs"""
        DataRecord(
            grid,
            time=[0.0],
            items={
                "grid_element": np.array([["node"], ["link"]]),
                "element_id": np.array([[1], [3]]),
            },
            data_vars={"mean_elevation": (["time"], np.array([100]))},
            attrs=["not a dict"],
        )
    # Should return except AttributeError:
    #                 raise TypeError(('Attributes (attrs) passed to DataRecord'
    #                                 'must be a dictionary'))
    #
    # test bad loc and id:
    rmg = RasterModelGrid((3, 3))
    hmg = HexModelGrid((3, 2), spacing=1.0)
    radmg = RadialModelGrid(n_rings=1, nodes_in_first_ring=5, xy_of_center=(0.0, 0.0))
    vdmg = VoronoiDelaunayGrid(np.random.rand(25), np.random.rand(25))
    my_items_bad_loc = {
        "grid_element": np.array(["node", "bad_loc"]),
        "element_id": np.array([1, 3]),
    }
    my_items_bad_loc2 = {"grid_element": "bad_loc", "element_id": np.array([1, 3])}
    my_items_bad_loc3 = {
        "grid_element": np.array(["node", "node", "node"]),
        "element_id": np.array([1, 3]),
    }
    my_items_bad_id = {
        "grid_element": np.array(["node", "link"]),
        "element_id": np.array([1, 300]),
    }
    my_items_bad_id2 = {
        "grid_element": np.array(["node", "link"]),
        "element_id": np.array([1, -300]),
    }
    my_items_bad_id3 = {
        "grid_element": np.array(["node", "link"]),
        "element_id": np.array([1, 2.0]),
    }
    my_items_bad_id4 = {
        "grid_element": np.array(["node", "link"]),
        "element_id": np.array([1, 2, 3]),
    }
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_loc)
    with pytest.raises(ValueError):
        DataRecord(hmg, items=my_items_bad_loc)
    with pytest.raises(ValueError):
        DataRecord(radmg, items=my_items_bad_loc)
    with pytest.raises(ValueError):
        DataRecord(vdmg, items=my_items_bad_loc)
    # should return ValueError(('One or more of the grid elements provided is/are'
    #                             ' not permitted location for this grid type.'))
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_loc2)
    # should return ValueError: Location provided: bad_loc is not a permitted
    #  location for this grid type.
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_loc3)
    # should return ValueError(('grid_element passed to DataRecord must be '
    #  ' the same length as the number of items or 1.'))
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_id)
    with pytest.raises(ValueError):
        DataRecord(hmg, items=my_items_bad_id)
    with pytest.raises(ValueError):
        DataRecord(radmg, items=my_items_bad_id)
    with pytest.raises(ValueError):
        DataRecord(vdmg, items=my_items_bad_id)
    # should return ValueError(('An item residing at ' + at + ' has an '
    #  'element_id larger than the number of'+ at + 'on the grid.'))
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_id2)
    #  should return ValueError(('An item residing at ' + at + ' has '
    # 'an element id below zero. This is not permitted.'))
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_id3)
    # should return ValueError(('You have passed a non-integer element_id to '
    #                              'DataRecord, this is not permitted.'))
    with pytest.raises(ValueError):
        DataRecord(rmg, items=my_items_bad_id4)
Ejemplo n.º 49
0
def dans_grid3():
    """
    Create a 7x7 test grid with a well defined hole in it.
    """
    mg = RasterModelGrid(7, 7, 1.)

    z = np.array([
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        [0.0, 2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
        [0.0, 2.0, 1.6, 1.5, 1.6, 2.0, 0.0],
        [0.0, 2.0, 1.7, 1.6, 1.7, 2.0, 0.0],
        [0.0, 2.0, 1.8, 2.0, 2.0, 2.0, 0.0],
        [0.0, 1.0, 0.6, 1.0, 1.0, 1.0, 0.0],
        [0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0],
    ]).flatten()

    r_old = np.array([
        [0, 1, 2, 3, 4, 5, 6],
        [7, 1, 2, 3, 4, 5, 13],
        [14, 14, 17, 17, 17, 20, 20],
        [21, 21, 17, 17, 17, 27, 27],
        [28, 28, 37, 38, 39, 34, 34],
        [35, 44, 44, 44, 46, 41, 41],
        [42, 43, 44, 45, 46, 47, 48],
    ]).flatten()

    r_new = np.array([
        [0, 1, 2, 3, 4, 5, 6],
        [7, 1, 2, 3, 4, 5, 13],
        [14, 14, 23, 24, 24, 20, 20],
        [21, 21, 30, 30, 24, 27, 27],
        [28, 28, 37, 38, 39, 34, 34],
        [35, 44, 44, 44, 46, 41, 41],
        [42, 43, 44, 45, 46, 47, 48],
    ]).flatten()

    A_old = np.array([
        [0., 1., 1., 1., 1., 1., 0.],
        [0., 1., 1., 1., 1., 1., 0.],
        [1., 1., 1., 6., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1.],
        [0., 1., 2., 2., 2., 1., 1.],
        [0., 0., 5., 0., 2., 0., 0.],
    ]).flatten()

    A_new = np.array([
        [0., 1., 1., 1., 1., 1., 0.],
        [0., 1., 1., 1., 1., 1., 0.],
        [1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 2., 4., 1., 1., 1.],
        [1., 1., 7., 1., 1., 1., 1.],
        [0., 1., 8., 2., 2., 1., 1.],
        [0., 0., 11., 0., 2., 0., 0.],
    ]).flatten()

    s_new = np.array([
        [0, 1, 8, 2, 9, 3, 10],
        [4, 11, 5, 12, 6, 7, 13],
        [14, 15, 20, 19, 21, 22, 27],
        [26, 28, 29, 34, 33, 35, 41],
        [40, 42, 43, 44, 36, 37, 30],
        [23, 16, 24, 17, 18, 25, 38],
        [31, 45, 46, 39, 32, 47, 48],
    ]).flatten()

    links_old = np.array([
        [-1, -1, -1, -1, -1, -1, -1],
        [-1, 7, 8, 9, 10, 11, -1],
        [-1, 26, 28, -1, 29, 31, -1],
        [-1, 39, 113, 35, 114, 44, -1],
        [-1, 52, 60, 61, 62, 57, -1],
        [-1, 146, 73, 149, 75, 70, -1],
        [-1, -1, -1, -1, -1, -1, -1],
    ]).flatten()

    links_new = np.array([
        [-1, -1, -1, -1, -1, -1, -1],
        [-1, 7, 8, 9, 10, 11, -1],
        [-1, 26, 34, 35, 115, 31, -1],
        [-1, 39, 47, 125, 42, 44, -1],
        [-1, 52, 60, 61, 62, 57, -1],
        [-1, 146, 73, 149, 75, 70, -1],
        [-1, -1, -1, -1, -1, -1, -1],
    ]).flatten()

    depr_outlet_target = np.array([
        [XX, XX, XX, XX, XX, XX, XX],
        [XX, XX, XX, XX, XX, XX, XX],
        [XX, XX, 30, 30, 30, XX, XX],
        [XX, XX, 30, 30, 30, XX, XX],
        [XX, XX, XX, XX, XX, XX, XX],
        [XX, XX, XX, XX, XX, XX, XX],
        [XX, XX, XX, XX, XX, XX, XX],
    ]).flatten()

    mg.add_field("node", "topographic__elevation", z, units="-")

    fr = FlowAccumulator(mg, flow_director="D8")
    lf = DepressionFinderAndRouter(mg)

    class DansGrid(object):
        pass

    dans_grid = DansGrid()
    dans_grid.mg = mg
    dans_grid.fr = fr
    dans_grid.lf = lf
    dans_grid.z = z
    dans_grid.r_new = r_new
    dans_grid.r_old = r_old
    dans_grid.A_new = A_new
    dans_grid.A_old = A_old
    dans_grid.s_new = s_new
    dans_grid.depr_outlet_target = depr_outlet_target
    dans_grid.links_old = links_old
    dans_grid.links_new = links_new

    return dans_grid
Ejemplo n.º 50
0
num_cols = len(spacearray)

#Time Array
t_min = 0  #s
t_max = 18000  #s
dt = 0.3  #s
timearray = np.arange(t_min, t_max + dt, dt)
time_interval = [
    timearray[i:i + int((round(len(timearray) / 4)))]
    for i in range(0, len(timearray), int(round(len(timearray) / 4)))
]

#2D grid dimensions
x_ncells = num_cols
y_ncells = num_rows
mg = RasterModelGrid(x_ncells, y_ncells, dx)  #make 2D grid

#Create data fields
zb = mg.add_empty('node', 'land_surface_elevation')
h = mg.add_zeros('node', 'water_thickness')
zw = mg.add_empty('node', 'water_elevation')
w_slope = mg.add_zeros('link', 'water_slope')  #make all links have zero slope
q = mg.add_zeros('link', 'flux')

#Initialize elevation
zb[:] = zmax - valley_s * mg.node_x
zb += side_s * np.abs(mg.node_y - mg.dx * ((num_rows - 1) / 2.0))
zw[:] = zb + h

#Define constants
n = 0.045  #roughness of bed surface
Ejemplo n.º 51
0
def dans_grid1():
    """
    Create a 5x5 test grid.
    This is a sheet flow test.
    """
    mg = RasterModelGrid((5, 5), spacing=(10., 10.))

    this_dir = os.path.abspath(os.path.dirname(__file__))
    infile = os.path.join(this_dir, "test_fr_input.txt")

    z = mg.node_x.copy()

    A_target = (np.array([
        [0., 0., 0., 0., 0.],
        [3., 3., 2., 1., 0.],
        [3., 3., 2., 1., 0.],
        [3., 3., 2., 1., 0.],
        [0., 0., 0., 0., 0.],
    ]).flatten() * 100.)

    frcvr_target = np.array([
        [0, 1, 2, 3, 4],
        [5, 5, 6, 7, 9],
        [10, 10, 11, 12, 14],
        [15, 15, 16, 17, 19],
        [20, 21, 22, 23, 24],
    ]).flatten()

    upids_target = np.array([
        [0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
    ]).flatten()

    links2rcvr_target = np.full(25, XX)
    links2rcvr_target[mg.core_nodes] = np.array(
        [9, 10, 11, 18, 19, 20, 27, 28, 29])

    Q_target = A_target * 2.  # only once Q_in is used

    steepest_target = np.array([
        [0., 0., 0., 0., 0.],
        [0., 1., 1., 1., 0.],
        [0., 1., 1., 1., 0.],
        [0., 1., 1., 1., 0.],
        [0., 0., 0., 0., 0.],
    ]).flatten()

    mg.add_field("node", "topographic__elevation", z, units="-")

    class DansGrid(object):
        pass

    dans_grid = DansGrid()
    dans_grid.mg = mg
    dans_grid.z = z
    dans_grid.infile = infile
    dans_grid.A_target = A_target
    dans_grid.frcvr_target = frcvr_target
    dans_grid.upids_target = upids_target
    dans_grid.Q_target = Q_target
    dans_grid.steepest_target = steepest_target
    dans_grid.links2rcvr_target = links2rcvr_target

    return dans_grid
Ejemplo n.º 52
0
def internal_closed():
    """
    Create a 6x5 test grid, but with two internal nodes closed.
    This is a sheet flow test.
    """
    mg = RasterModelGrid((6, 5), spacing=(10., 10.))

    mg.set_closed_boundaries_at_grid_edges(True, True, False, True)
    mg.status_at_node[7] = CLOSED_BOUNDARY
    mg.status_at_node[16] = CLOSED_BOUNDARY

    z = mg.node_x.copy()

    Q_in = np.full(25, 2.)

    A_target = (np.array([
        [0., 0., 0., 0., 0.],
        [1., 1., 0., 1., 0.],
        [6., 6., 3., 1., 0.],
        [0., 0., 2., 1., 0.],
        [3., 3., 2., 1., 0.],
        [0., 0., 0., 0., 0.],
    ]).flatten() * 100.)

    frcvr_target = np.array([
        [0, 1, 2, 3, 4],
        [5, 5, 7, 12, 9],
        [10, 10, 11, 12, 14],
        [15, 16, 11, 17, 19],
        [20, 20, 21, 22, 24],
        [25, 26, 27, 28, 29],
    ]).flatten()

    links2rcvr_target = np.full(mg.number_of_nodes, XX)
    links2rcvr_target[mg.core_nodes] = np.array(
        [9, 62, 18, 19, 20, 67, 29, 36, 37, 38])

    steepest_target = np.array([
        [0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 1., 1., 1., 0.],
        [0., 0., 0., 1., 0.],
        [0., 1., 1., 1., 0.],
        [0., 0., 0., 0., 0.],
    ]).flatten()

    steepest_target[np.array([8, 17])] = 1. / np.sqrt(2.)

    mg.add_field("node", "topographic__elevation", z, units="-")

    class DansGrid(object):
        pass

    dans_grid = DansGrid()
    dans_grid.mg = mg
    dans_grid.z = z
    dans_grid.Q_in = Q_in
    dans_grid.A_target = A_target
    dans_grid.frcvr_target = frcvr_target
    dans_grid.steepest_target = steepest_target
    dans_grid.links2rcvr_target = links2rcvr_target

    return dans_grid
Ejemplo n.º 53
0
def test_add_field_at_node():
    """Add field at nodes."""
    grid = RasterModelGrid((4, 5))
    grid.add_field('z', np.arange(20), at='node')

    assert_array_equal(grid.at_node['z'], np.arange(20))
Ejemplo n.º 54
0
def dans_grid2():
    """
    Create a 5x5 test grid.
    This tests more complex routing, with diffs between D4 & D8.
    """
    mg = RasterModelGrid((5, 5), spacing=(10., 10.))

    this_dir = os.path.abspath(os.path.dirname(__file__))
    infile = os.path.join(this_dir, "test_fr_input.txt")

    z = np.array([
        [7., 7., 7., 7., 7.],
        [7., 5., 3.2, 6., 7.],
        [7., 2., 3., 5., 7.],
        [7., 1., 1.9, 4., 7.],
        [7., 0., 7., 7., 7.],
    ]).flatten()

    A_target_D8 = np.array([
        [0., 0., 0., 0., 0.],
        [0., 100., 200., 100., 0.],
        [0., 400., 100., 100., 0.],
        [0., 600., 300., 100., 0.],
        [0., 900., 0., 0., 0.],
    ]).flatten()

    A_target_D4 = np.array([
        [0., 0., 0., 0., 0.],
        [0., 100., 200., 100., 0.],
        [0., 200., 400., 100., 0.],
        [0., 900., 600., 100., 0.],
        [0., 900., 0., 0., 0.],
    ]).flatten()

    frcvr_target_D8 = np.array([
        [0, 1, 2, 3, 4],
        [5, 11, 11, 7, 9],
        [10, 16, 16, 17, 14],
        [15, 21, 21, 17, 19],
        [20, 21, 22, 23, 24],
    ]).flatten()

    frcvr_target_D4 = np.array([
        [0, 1, 2, 3, 4],
        [5, 11, 12, 7, 9],
        [10, 16, 17, 12, 14],
        [15, 21, 16, 17, 19],
        [20, 21, 22, 23, 24],
    ]).flatten()

    upids_target_D8 = np.array([
        [0, 1, 2, 3, 4],
        [5, 9, 10, 14, 15],
        [19, 20, 21, 16, 11],
        [6, 7, 8, 12, 17],
        [13, 18, 22, 23, 24],
    ]).flatten()

    upids_target_D4 = np.array([
        [0, 1, 2, 3, 4],
        [5, 9, 10, 14, 15],
        [19, 20, 21, 16, 11],
        [6, 17, 12, 7, 8],
        [13, 18, 22, 23, 24],
    ]).flatten()

    links2rcvr_target_D8 = np.full(25, XX)
    links2rcvr_target_D8[mg.core_nodes] = np.array(
        [14, 51, 11, 23, 59, 61, 32, 67, 29])

    links2rcvr_target_D4 = np.full(25, XX)
    links2rcvr_target_D4[mg.core_nodes] = np.array(
        [14, 15, 11, 23, 24, 20, 32, 28, 29])

    steepest_target_D8 = np.array([
        [0., 0., 0., 0., 0.],
        [0., 0.3, 0.08485281, 0.28, 0.],
        [0., 0.1, 0.14142136, 0.21920310, 0.],
        [0., 0.1, 0.13435029, 0.21, 0.],
        [0., 0., 0., 0., 0.],
    ]).flatten()

    steepest_target_D4 = np.array([
        [0., 0., 0., 0., 0.],
        [0., 0.3, 0.02, 0.28, 0.],
        [0., 0.1, 0.11, 0.2, 0.],
        [0., 0.1, 0.09, 0.21, 0.],
        [0., 0., 0., 0., 0.],
    ]).flatten()

    mg.add_field("node", "topographic__elevation", z, units="-")

    class DansGrid(object):
        pass

    dans_grid = DansGrid()
    dans_grid.mg = mg
    dans_grid.z = z
    dans_grid.infile = infile
    dans_grid.A_target_D8 = A_target_D8
    dans_grid.A_target_D4 = A_target_D4
    dans_grid.frcvr_target_D8 = frcvr_target_D8
    dans_grid.frcvr_target_D4 = frcvr_target_D4
    dans_grid.upids_target_D8 = upids_target_D8
    dans_grid.upids_target_D4 = upids_target_D4
    dans_grid.steepest_target_D8 = steepest_target_D8
    dans_grid.steepest_target_D4 = steepest_target_D4
    dans_grid.links2rcvr_target_D8 = links2rcvr_target_D8
    dans_grid.links2rcvr_target_D4 = links2rcvr_target_D4

    return dans_grid
Ejemplo n.º 55
0
def test_add_ones_zeros_empty_to_at_grid():
    """Test different add methods for keyword at='grid'"""
    grid = RasterModelGrid((4, 5))
    assert_raises(ValueError, grid.add_zeros, 'value', at='grid')
    assert_raises(ValueError, grid.add_empty, 'value', at='grid')
    assert_raises(ValueError, grid.add_ones, 'value', at='grid')
Ejemplo n.º 56
0
import numpy as np
import time
import pylab

#get the needed properties to build the grid:
input_file = './craters_params_init.txt'
inputs = ModelParameterDictionary(input_file)
nrows = inputs.read_int('nrows')
ncols = inputs.read_int('ncols')
dx = inputs.read_float('dx')
leftmost_elev = inputs.read_float('leftmost_elevation')
initial_slope = inputs.read_float('initial_slope')
nt = inputs.read_int('number_of_craters_per_loop')
loops = inputs.read_int('number_of_loops')

mg = RasterModelGrid(nrows, ncols, dx)
mg.set_looped_boundaries(True, True)

#create the fields in the grid
mg.create_node_array_zeros('topographic_elevation')
z = mg.create_node_array_zeros() + leftmost_elev
z += initial_slope * np.amax(mg.node_y) - initial_slope * mg.node_y
mg['node']['topographic_elevation'] = z  #+ np.random.rand(len(z))/10000.

# Display a message
print('Running ...')
start_time = time.time()

#instantiate the component:
craters_component = impactor(mg, input_file)
Ejemplo n.º 57
0
def test_add_field_at_grid():
    """Test add field at grid."""
    grid = RasterModelGrid((4, 5))
    grid.at_grid['value']=1
    assert_array_equal(1, grid.at_grid['value'].size)
Ejemplo n.º 58
0
def test_ones_zeros_empty_to_at_grid():
    """Test get array with field size methods for keyword at='grid'"""
    grid = RasterModelGrid((4, 5))
    assert_raises(ValueError, grid.zeros, at='grid')
    assert_raises(ValueError, grid.empty, at='grid')
    assert_raises(ValueError, grid.ones, at='grid')
Ejemplo n.º 59
0
def test_add_field_without_at():
    """Test raises error with wrong size array."""
    grid = RasterModelGrid((4, 5))
    assert_raises(ValueError, grid.add_field, 'z', np.arange(21))
Ejemplo n.º 60
0
def test_adding_field_at_grid_two_ways():
    """Test add field at grid two ways."""
    grid = RasterModelGrid((4, 5))
    grid.at_grid['value_1']=1
    grid.add_field('value_2', 1, at='grid')
    assert_array_equal(grid.at_grid['value_1'], grid.at_grid['value_2'])