예제 #1
0
def test_sed_dep():
    input_file = os.path.join(_THIS_DIR, "sed_dep_params.txt")
    inputs = ModelParameterDictionary(input_file, auto_type=True)
    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("total_time")
    dt = inputs.read_float("dt")

    nt = int(runtime // dt)
    uplift_per_step = uplift_rate * dt

    mg = RasterModelGrid((nrows, ncols), xy_spacing=(dx, dx))

    mg.add_zeros("topographic__elevation", at="node")
    z = np.loadtxt(os.path.join(_THIS_DIR, "seddepinit.txt"))
    mg["node"]["topographic__elevation"] = z

    mg.set_closed_boundaries_at_grid_edges(True, False, True, False)

    fr = FlowAccumulator(mg, flow_director="D8")
    sde = SedDepEroder(mg, **inputs)

    for i in range(nt):
        mg.at_node["topographic__elevation"][mg.core_nodes] += uplift_per_step
        mg = fr.run_one_step()
        mg, _ = sde.erode(dt)

    z_tg = np.loadtxt(os.path.join(_THIS_DIR, "seddepz_tg.txt"))

    assert_array_almost_equal(
        mg.at_node["topographic__elevation"][mg.core_nodes], z_tg[mg.core_nodes]
    )
예제 #2
0
def test_sed_dep():
    input_file = os.path.join(_THIS_DIR, "sed_dep_params.txt")
    inputs = ModelParameterDictionary(input_file, auto_type=True)
    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("total_time")
    dt = inputs.read_float("dt")

    nt = int(runtime // dt)
    uplift_per_step = uplift_rate * dt

    mg = RasterModelGrid((nrows, ncols), xy_spacing=(dx, dx))

    mg.add_zeros("topographic__elevation", at="node")
    z = np.loadtxt(os.path.join(_THIS_DIR, "seddepinit.txt"))
    mg["node"]["topographic__elevation"] = z

    mg.set_closed_boundaries_at_grid_edges(True, False, True, False)

    fr = FlowAccumulator(mg, flow_director="D8")
    sde = SedDepEroder(mg, **inputs)

    for i in range(nt):
        mg.at_node["topographic__elevation"][mg.core_nodes] += uplift_per_step
        mg = fr.run_one_step()
        mg, _ = sde.erode(dt)

    z_tg = np.loadtxt(os.path.join(_THIS_DIR, "seddepz_tg.txt"))

    assert_array_almost_equal(
        mg.at_node["topographic__elevation"][mg.core_nodes],
        z_tg[mg.core_nodes])
예제 #3
0
def test_sed_dep_new():
    """
    This tests only the power_law version of the SDE.
    It uses a landscape run to 5000 100y iterations, then having experienced
    a 20-fold uplift acceleration for a further 30000 y. It tests the outcome
    of the next 1000 y of erosion.
    """
    mg = RasterModelGrid((25, 50), 200.)
    for edge in (mg.nodes_at_left_edge, mg.nodes_at_top_edge,
                 mg.nodes_at_right_edge):
        mg.status_at_node[edge] = CLOSED_BOUNDARY

    z = mg.add_zeros('node', 'topographic__elevation')

    fr = FlowAccumulator(mg, flow_director='D8')
    sde = SedDepEroder(mg, K_sp=1.e-4, sed_dependency_type='almost_parabolic',
                       Qc='power_law', K_t=1.e-4)

    initconds = os.path.join(os.path.dirname(__file__),
                             'perturbedcondst300.txt')
    finalconds = os.path.join(os.path.dirname(__file__),
                              'tenmorestepsfrom300.txt')
    z[:] = np.loadtxt(initconds)

    dt = 100.
    up = 0.05

    for i in range(10):
        fr.run_one_step()
        sde.run_one_step(dt)
        z[mg.core_nodes] += 20.*up

    assert_array_almost_equal(z, np.loadtxt(finalconds))
예제 #4
0
def test_sed_dep_new():
    """
    This tests only the power_law version of the SDE.
    It uses a landscape run to 5000 100y iterations, then having experienced
    a 20-fold uplift acceleration for a further 30000 y. It tests the outcome
    of the next 1000 y of erosion.
    """
    mg = RasterModelGrid((25, 50), xy_spacing=200.)
    for edge in (mg.nodes_at_left_edge, mg.nodes_at_top_edge, mg.nodes_at_right_edge):
        mg.status_at_node[edge] = CLOSED_BOUNDARY

    z = mg.add_zeros("node", "topographic__elevation")

    fr = FlowAccumulator(mg, flow_director="D8")
    sde = SedDepEroder(
        mg,
        K_sp=1.e-4,
        sed_dependency_type="almost_parabolic",
        Qc="power_law",
        K_t=1.e-4,
    )

    initconds = os.path.join(os.path.dirname(__file__), "perturbedcondst300.txt")
    finalconds = os.path.join(os.path.dirname(__file__), "tenmorestepsfrom300.txt")
    z[:] = np.loadtxt(initconds)

    dt = 100.
    up = 0.05

    for i in range(10):
        fr.run_one_step()
        sde.run_one_step(dt)
        z[mg.core_nodes] += 20. * up

    assert_array_almost_equal(z, np.loadtxt(finalconds))
예제 #5
0
def test_route_to_multiple_error_raised_run_SedDepEroder():
    mg = RasterModelGrid((10, 10))
    z = mg.add_zeros('node', 'topographic__elevation')
    z += mg.x_of_node + mg.y_of_node
    sp = SedDepEroder(mg)

    fa = FlowAccumulator(mg, flow_director='MFD')
    fa.run_one_step()

    with pytest.raises(NotImplementedError):
        sp.run_one_step(10)
def test_route_to_multiple_error_raised_run_SedDepEroder():
    mg = RasterModelGrid((10, 10))
    z = mg.add_zeros("node", "topographic__elevation")
    z += mg.x_of_node + mg.y_of_node
    sp = SedDepEroder(mg)

    fa = FlowAccumulator(mg, flow_director="MFD")
    fa.run_one_step()

    with pytest.raises(NotImplementedError):
        sp.run_one_step(10)
예제 #7
0
def test_route_to_multiple_error_raised_init_SedDepEroder():
    mg = RasterModelGrid((10, 10))
    z = mg.add_zeros("node", "topographic__elevation")
    z += mg.x_of_node + mg.y_of_node
    fa = FlowAccumulator(mg, flow_director="MFD")
    fa.run_one_step()

    with pytest.raises(NotImplementedError):
        SedDepEroder(mg)
예제 #8
0
def test_sed_dep():
    uplift_rate = 0.0001
    runtime = 20000.0
    dt = 5000.0

    nt = int(runtime // dt)
    uplift_per_step = uplift_rate * dt

    mg = RasterModelGrid((50, 50), xy_spacing=1000.0)

    mg.add_zeros("topographic__elevation", at="node")
    z = np.loadtxt(os.path.join(_THIS_DIR, "seddepinit.txt"))
    mg["node"]["topographic__elevation"] = z

    mg.set_closed_boundaries_at_grid_edges(True, False, True, False)

    fr = FlowAccumulator(mg, flow_director="D8")
    sde = SedDepEroder(
        mg,
        K_sp=1.0e-6,
        b_sp=0.5,
        c_sp=1.0,
        Qc="MPM",
        k_Q=2.5e-7,
        k_w=2.5,
        mannings_n=0.05,
        Dchar=0.05,
        threshold_Shields=0.05,
        sed_dependency_type="almost_parabolic",
        set_threshold_from_Dchar=True,
        g=9.81,
    )

    for i in range(nt):
        mg.at_node["topographic__elevation"][mg.core_nodes] += uplift_per_step
        mg = fr.run_one_step()
        mg, _ = sde.run_one_step(dt)

    z_tg = np.loadtxt(os.path.join(_THIS_DIR, "seddepz_tg.txt"))

    assert_array_almost_equal(
        mg.at_node["topographic__elevation"][mg.core_nodes], z_tg[mg.core_nodes]
    )
예제 #9
0
def test_sed_dep():
    input_file = os.path.join(_THIS_DIR, 'sed_dep_params.txt')
    inputs = ModelParameterDictionary(input_file, auto_type=True)
    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')
    uplift_rate = inputs.read_float('uplift_rate')

    runtime = inputs.read_float('total_time')
    dt = inputs.read_float('dt')

    nt = int(runtime // dt)
    uplift_per_step = uplift_rate * dt

    mg = RasterModelGrid((nrows, ncols), (dx, dx))

    mg.add_zeros('topographic__elevation', at='node')
    z = np.loadtxt(os.path.join(_THIS_DIR, 'seddepinit.txt'))
    mg['node']['topographic__elevation'] = z

    mg.set_closed_boundaries_at_grid_edges(True, False, True, False)

    fr = FlowAccumulator(mg, flow_director='D8')
    sde = SedDepEroder(mg, **inputs)

    for i in range(nt):
        mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step
        mg = fr.run_one_step()
        mg, _ = sde.erode(dt)

    z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'seddepz_tg.txt'))

    assert_array_almost_equal(
        mg.at_node['topographic__elevation'][mg.core_nodes],
        z_tg[mg.core_nodes])
예제 #10
0
def test_sed_dep():
    input_file = os.path.join(_THIS_DIR, 'sed_dep_params.txt')
    inputs = ModelParameterDictionary(input_file, auto_type=True)
    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')
    uplift_rate = inputs.read_float('uplift_rate')

    runtime = inputs.read_float('total_time')
    dt = inputs.read_float('dt')

    nt = int(runtime // dt)
    uplift_per_step = uplift_rate * dt

    mg = RasterModelGrid((nrows, ncols), (dx, dx))

    mg.add_zeros('topographic__elevation', at='node')
    z = np.loadtxt(os.path.join(_THIS_DIR, 'seddepinit.txt'))
    mg['node']['topographic__elevation'] = z

    mg.set_closed_boundaries_at_grid_edges(True, False, True, False)

    fr = FlowAccumulator(mg, flow_director='D8')
    sde = SedDepEroder(mg, **inputs)

    for i in range(nt):
        mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step
        mg = fr.run_one_step()
        mg, _ = sde.erode(dt)

    z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'seddepz_tg.txt'))

    assert_array_almost_equal(mg.at_node['topographic__elevation'][
        mg.core_nodes], z_tg[mg.core_nodes])
예제 #11
0
nt = int(runtime // dt)
uplift_per_step = uplift_rate * dt
print('uplift per step: ', uplift_per_step)

#check we have a plaubible grid
#mg = RasterModelGrid(nrows,ncols,dx)
assert mg.number_of_nodes == nrows * ncols
assert mg.dx == dx

# Display a message
print('Running ...')

# instantiate the components:
fr = FlowAccumulator(mg, flow_director='D8')
sde = SedDepEroder(mg, input_file)
# don't allow overwriting of these, just in case
try:
    x_profiles
except NameError:
    x_profiles = []
    z_profiles = []
    S_profiles = []
    A_profiles = []

# plot init conds
if make_output_plots:
    mg = fr.route_flow(grid=mg)
    pylab.figure('long_profile_anim')
    ylim([0, y_max])
    prf.analyze_channel_network_and_plot(mg)
예제 #12
0
nt = int(runtime//dt)
uplift_per_step = uplift_rate * dt
print('uplift per step: ', uplift_per_step)

#check we have a plaubible grid
#mg = RasterModelGrid(nrows,ncols,dx)
assert mg.number_of_nodes == nrows*ncols
assert mg.node_spacing == dx

# Display a message
print('Running ...')

# instantiate the components:
fr = FlowAccumulator(mg, flow_director='D8')
sde = SedDepEroder(mg, input_file)
# don't allow overwriting of these, just in case
try:
    x_profiles
except NameError:
    x_profiles = []
    z_profiles = []
    S_profiles = []
    A_profiles = []

# plot init conds
if make_output_plots:
    mg = fr.route_flow(grid=mg)
    pylab.figure('long_profile_anim')
    ylim([0, y_max])
    prf.analyze_channel_network_and_plot(mg)
예제 #13
0
from matplotlib.pyplot import plot, show, ylim
from landlab import RasterModelGrid
from landlab.components import SedDepEroder
import numpy as np
import seaborn as sns

# for fig 1
mycolors = sns.color_palette("cubehelix", 5)
lines = ["-", "--", "-.", ":"]

mg = RasterModelGrid((50, 50), 200.)
z = mg.add_zeros('node', 'topographic__elevation')
sdegen = SedDepEroder(mg)
# clear the output fields to permit binding of other components
for field in sdegen.output_var_names[1:]:
    mg.at_node.pop(field)
sdepara = SedDepEroder(mg, sed_dependency_type='almost_parabolic')
for field in sdegen.output_var_names[1:]:
    mg.at_node.pop(field)
sdelindec = SedDepEroder(mg, sed_dependency_type='linear_decline')
for field in sdegen.output_var_names[1:]:
    mg.at_node.pop(field)
sdeconst = SedDepEroder(mg, sed_dependency_type='None')

sns.set_context('paper')
for ln, col, sde in zip(lines, mycolors[:4],
                        (sdegen, sdepara, sdelindec, sdeconst)):
    with sns.axes_style('whitegrid', {'grid.linestyle': '--'}):
        sde.show_sed_flux_function(color=col, linestyle=ln)
ylim(0, 1.02)
show()
예제 #14
0
from landlab.components import FlowAccumulator, SedDepEroder
from landlab import RasterModelGrid
import landlab
import numpy as np
from pylab import show, figure
from landlab.io import read_esri_ascii


(mg, z) = read_esri_ascii("bacia_piratini_90m.asc", name="topographic__elevation")

fda = FlowAccumulator(mg, 'topographic__elevation')
sde1 = SedDepEroder(mg, Qc="MPM")

fda.run_one_step()
sde1.run_one_step(dt=30) #dt em anos

print(sde1.characteristic_grainsize)
예제 #15
0
def extend_perturbed_runs(total_iters_to_reach=0):
    """Load all perturbed runs in current folder, and extend them.

    Function should be called from within an experiment folder
    (extend all perturbations for all starting uplift rates), an
    'uplift_rate_XXXX' folder (extend all perturbations for this rate) or an
    'accel_XXX' folder (extend this accel only).

    Does NOT create a new expt or run ID, just extends the old ones. Adds a
    text file annotating what has happened.
    """
    # look for the params to use. Also tells us where we are in the hierarchy
    level = 0  # 0: top, 1: uplift, 2: accel:
    cwd = os.getcwd()
    while True:
        try:
            paramdict = np.load('expt_ID_paramdict.npy').item()
        except IOError:
            os.chdir('..')
            level += 1
        else:
            break
    # now back to where we started in the dir str:
    os.chdir(cwd)
    if level == 2:  # in accel_ folder
        # get the accel that this is:
        accel_factors = [
            get_float_of_folder_name(),
        ]
        # get the U of the host folder:
        uplift_rates = [
            get_float_of_folder_name(directory=(cwd + '/..')),
        ]
        wd_stub = os.path.abspath(os.getcwd() + '/../..')
    elif level == 1:  # in uplift_ folder
        accel_fnames = [
            filename for filename in os.listdir('.')
            if filename.startswith('accel_')
        ]
        accel_factors = [
            get_float_of_folder_name(directory=(cwd + '/' + filename))
            for filename in accel_fnames
        ]
        uplift_rates = [
            get_float_of_folder_name(),
        ]
        wd_stub = os.path.abspath(os.getcwd() + '/..')
    elif level == 0:  # in top folder
        uplift_fnames = [
            filename for filename in os.listdir('.')
            if filename.startswith('uplift_rate_')
        ]
        uplift_rates = [
            get_float_of_folder_name(directory=(cwd + '/' + filename))
            for filename in uplift_fnames
        ]
        accel_factors = paramdict['accel_factors']
        wd_stub = os.path.abspath(os.getcwd())

    for uplift_rate in uplift_rates:
        for accel_factor in accel_factors:
            wd = (wd_stub + '/uplift_rate_' + str(uplift_rate) + '/accel_' +
                  str(accel_factor))
            # get the saved filenames that already exist in this folder:
            runnames = [
                filename for filename in os.listdir(wd)
                if filename.startswith('topographic__elevation')
            ]
            seddepthnames = [
                filename for filename in os.listdir(wd)
                if filename.startswith('channel_sediment__depth')
            ]
            # as elsewhere, the final entry is the last run, so --
            # establish the loop number of that run:
            run_ID = runnames[-1][-14:-4]  # is a str
            _format = 0
            while True:
                char = runnames[-1][-16 - _format]
                try:
                    num = int(char)
                except ValueError:  # was a str
                    break
                else:
                    _format += 1
            finaliter = int(runnames[-1][(-15 - _format):-15])
            finalsediter = int(seddepthnames[-1][(-15 - _format):-15])
            assert finaliter == finalsediter  # ...just in case

            # test we need to actually do more runs:
            if total_iters_to_reach < finaliter + paramdict['out_interval']:
                continue

            # check we aren't going to have a "zero problem"; correct if we do
            max_zeros = len(str(total_iters_to_reach))
            if max_zeros + 1 > _format:  # less won't be possible from continue
                extra_zeros = max_zeros + 1 - _format
                for allfile in os.listdir(wd):
                    if allfile[-14:-4] == run_ID:
                        os.rename(
                            wd + '/' + allfile,
                            (wd + '/' + allfile[:(-15 - _format)] +
                             '0' * extra_zeros + allfile[(-15 - _format):]))
                runnames = [
                    filename for filename in os.listdir(wd)
                    if filename.startswith('topographic__elevation')
                ]
                seddepthnames = [
                    filename for filename in os.listdir(wd)
                    if filename.startswith('channel_sediment__depth')
                ]
            if max_zeros + 1 < _format:
                max_zeros = _format - 1  # in case of any bonus 0s from old run

            # build the structures:
            mg = RasterModelGrid(paramdict['shape'], paramdict['dx'])
            for edge in (mg.nodes_at_left_edge, mg.nodes_at_top_edge,
                         mg.nodes_at_right_edge):
                mg.status_at_node[edge] = CLOSED_BOUNDARY

            z = mg.add_zeros('node', 'topographic__elevation')
            seddepth = mg.add_zeros('node', 'channel_sediment__depth')
            fr = FlowRouter(mg)
            eroder = SedDepEroder(mg, **paramdict)
            ld = LinearDiffuser(mg, **paramdict)

            # load the last available elev data:
            z[:] = np.loadtxt(wd + '/' + runnames[-1])
            seddepth[:] = np.loadtxt(wd + '/' + seddepthnames[-1])

            # save a note
            try:
                appendfile = open(wd + '/appended_run_readme.txt', 'a')
            except IOError:
                appendfile = open(wd + '/appended_run_readme.txt', 'w')
            appendfile.write('This run was appended at timestamp ' +
                             str(int(time.time())) + '.\n')
            appendfile.write('New loops were added from iteration ' +
                             str(finaliter) + ' and terminated at iteration ' +
                             str(total_iters_to_reach) + '.\n\n')
            appendfile.close()

            # get runnin'
            print('Extending uplift ' + str(uplift_rate) + ' accel ' +
                  str(accel_factor) + ' from iter number ' + str(finaliter))
            dt = paramdict['dt']
            for i in xrange(finaliter + 1, total_iters_to_reach):
                fr.route_flow()
                eroder.run_one_step(dt)
                ld.run_one_step(dt)
                z[mg.core_nodes] += accel_factor * uplift_rate * dt
                print(i)
                if i % out_interval == 0:
                    zeros_to_add = max_zeros - len(str(i)) + 1
                    # note an OoM buffer! Just to be safe
                    if zeros_to_add < 0:
                        # ...just in case, though should never happen
                        print('Problem allocating zeros on savefiles')
                    ilabel = '0' * zeros_to_add + str(i)
                    identifier = ilabel + '_' + str(run_ID)
                    for field in out_fields:
                        np.savetxt(
                            wd + '/' + field + '_' + identifier + '.txt',
                            mg.at_node[field])
예제 #16
0
    'channel_sediment__relative_flux',
    'channel_sediment__volumetric_discharge', 'channel_sediment__depth'
]

# build the structures:
mg = RasterModelGrid(raster_params['shape'], raster_params['dx'])
for edge in (mg.nodes_at_left_edge, mg.nodes_at_top_edge,
             mg.nodes_at_right_edge):
    mg.status_at_node[edge] = CLOSED_BOUNDARY

z = mg.add_field('node', 'topographic__elevation',
                 np.loadtxt(raster_params['initcond']))
sed = mg.add_zeros('node', 'channel_sediment__depth', dtype=float)

fr = FlowRouter(mg)
eroder = SedDepEroder(mg, **inputs_sde)
ld = LinearDiffuser(mg, **inputs_ld)


def build_master_dict(expt_ID):
    total_dict = inputs_sde.copy()
    total_dict.update(inputs_ld)
    total_dict.update(raster_params)
    total_dict['expt_ID'] = expt_ID
    total_dict['dt'] = dt
    total_dict['max_loops'] = max_loops
    total_dict['multiplierforstab'] = multiplierforstab
    total_dict['out_interval'] = out_interval
    total_dict['uplift_rates'] = uplift_rates
    total_dict['bevel_amounts'] = bevel_amounts
    total_dict['elev_fraction_to_bevel'] = elev_fraction_to_bevel