Exemplo n.º 1
0
        #imshow_grid(rmg,'topographic__elevation',show_elements=False)
        #plt.xlim((rmg.shape[1]*rmg.dx/3,rmg.shape[1]*rmg.dx*2/3))
        #plt.show()
        #plt.clf
        print('Current time = ' + str(current_time))  # show current time
        for of in out_fields:
            ds[of][plotCounter, :, :] = rmg['node'][of].reshape(rmg.shape)
        plotCounter += 1
    current_time += dt  # update time tracker

    i += 1  # update iteration variable

print(plotCounter)
print('For loop complete')

write_esri_ascii('test.asc', rmg)

# imshow_grid(rmg,'topographic__elevation',show_elements=False)
# # tweek edges of domain so that they match the buffer kdc
# plt.xlim((e1,e2))
# plt.show()
# plt.clf

################################################################################
## plot the output into a gif
# hvds_topo = hv.Dataset(ds.topographic__elevation)
# get_ipython().run_line_magic('opts', "Image style(interpolation='bilinear', cmap='viridis') plot[colorbar=True]")
# get_ipython().run_line_magic('output', 'size=700')
# topo = hvds_topo.to(hv.Image, ['x', 'y'])
# # topo
#
Exemplo n.º 2
0
################################################################################
## plot the output into a gif
hvds_topo = hv.Dataset(ds.topographic__elevation)
try:
    get_ipython().run_line_magic('opts', "Image style(interpolation='bilinear', cmap='viridis') plot[colorbar=True]")
    get_ipython().run_line_magic('output', 'size=700')
except:
    print("Cannot plot gif because user is not using ipython")
topo = hvds_topo.to(hv.Image, ['x', 'y'])
# topo
#%%
#hv.output(dpi=100, size=150)
#hv.save(topo, 'topo.gif', fps=30)
#
#if SAVE_OUTPUT > 0:
#    d = datetime.datetime.today()
#    newPath = "./model_output_" + d.strftime("%Y_%B_%d_%H_%M")
#    os.mkfir(newPath)
#    hv.save(topo, newPath + '/topo.gif', fps=30)

if SAVE_OUTPUT == 2:
    currFile = os.path.basename(__file__)
    copyfile(currFile, newPath + "/" + currFile + "_archive")
    files = write_esri_ascii(newPath + '/output_grids.asc', rmg)



# save what is like a DEM:

def run_model(mdl_input=None):
    if mdl_input == None:
        mdl_input = default_landscape_parameters()

    # for ease, seperate the input into its main comonents
    domain = mdl_input['model_domain']
    landscape = mdl_input['landscape']
    tectonics = mdl_input['tectonics']
    fault_opt = mdl_input['fault_opt']
    duration = mdl_input['duration']
    save_opt = mdl_input['save_opt']

    # set the pointspacing
    dxy = domain['ymax'] / domain['Nxy']

    # set the location of the fault
    if fault_opt['fault_pos'] == 'midway':
        fault_pos = domain['ymax'] / 2

    # time bookeeping
    current_time = 0  # time tracking variable [kyr]
    i = 0  # iteration tracker [integer]
    plot_num = 2  # number of iterations to run before each new plot
    #calculate_BR= False     # calculate the metric BR used in the main paper
    num_frames = ((duration['total_time'] - duration['shear_start']) /
                  duration['dt_during_shear']) / plot_num + 1

    # informative output file: e.g. arctan_exp_5m_fault
    if save_opt['save_format'] == 'Default':
        d = datetime.datetime.today()
        fn = '{slip}{localization:.2e}_{damage}{intensity:.2e}_fault'.format(
            slip=fault_opt['slip_profile'],
            localization=fault_opt['localization'],
            damage=fault_opt['damage_prof'],
            intensity=landscape['km'])

        save_opt['save_format'] = {
            'file_name': fn,
            'dirname': fn + d.strftime('%d-%m-%Y')
        }

    print('Starting model run: ' + save_opt['save_format']['file_name'])

    ###########################################################################
    ###########################################################################
    ## Define domain (e.g. number of columns and rows)
    ncols = int(domain['xmax'] * (1. + 2. * domain['loopBuff']) /
                dxy)  # number of columns, tripled for looped boundaries kdc
    nrows = int(domain['ymax'] / dxy)  # number of rows
    e1 = ncols * dxy * domain['loopBuff'] / (2. * domain['loopBuff'] + 1.
                                             )  # edge1
    e2 = ncols * dxy - e1  # edge2

    ## Build the landlab grid #
    rmg = RasterModelGrid((nrows, ncols),
                          dxy)  # build a landlab grid of nrows x ncols

    #set boundary conditions to have top closed and all others open
    rmg.set_closed_boundaries_at_grid_edges(tectonics['boundaries'][0],
                                            tectonics['boundaries'][1],
                                            tectonics['boundaries'][2],
                                            tectonics['boundaries'][3])

    # Add an elevation field + slope and noise to get the flow router started
    rmg.add_zeros('node', 'topographic__elevation')
    rmg['node']['topographic__elevation'] += (rmg.node_y * 0.1 +
                                              np.random.rand(nrows * ncols))

    ################################################################################
    ## Fourth, the fun part, set up the off-fault deformation profile #############
    ################################################################################

    # define how a fault will work
    class fault:
        def __init__(self, rmg, fault_pos=None, fault_width=None):
            self.rmg = rmg
            self.nrows = rmg.shape[0]
            self.ncols = rmg.shape[1]
            self.fault_pos = fault_pos
            self.fault_width = fault_width

        def slip_profile(self, fault_prof, width=None):
            '''
            Define a slip profile relative to the dimensions of the model.
            '''

            yLocation = np.arange(nrows) * self.rmg.dx

            if width == None:
                width = self.fault_width

            if fault_prof == 'arctan':
                profile = 0.5 + 1 / np.pi * np.arctan(
                    (yLocation - self.fault_pos) * np.pi /
                    width)  # deal with magic number
            elif fault_prof == 'heaviside':
                profile = np.heaviside(yLocation - self.fault_pos, 1)
            elif fault_prof == 'exp':
                profile = np.exp(-yLocation / (fault_opt['v_star'] / dxy))
            else:
                raise ('fault_opt must be one of: arctan, heavyside, exp')

            v_profile = profile * fault_opt['vmax']
            accum_disp = profile * self.rmg.dx

            return v_profile, accum_disp

        def lithology(self,
                      damage_opt=None,
                      width=None,
                      ko=None,
                      km=None,
                      Do=None,
                      Dm=None):

            if width == None:
                width = self.fault_width  # set to the instantiated width

            if damage_opt == None:
                damage_func = lambda x: np.zeros(x.size)
                km = 0
                Dm = 0

            # 2D profiles
            if damage_opt == 'boxcar':
                damage_func = lambda x: np.heaviside(x-fault_pos-width,1) - \
                                        np.heaviside(x-fault_pos+width,1)

            if damage_opt == 'heaviside_up':
                damage_func = lambda x: np.abs(
                    np.heaviside(x - fault_pos, 1) - 1)

            if damage_opt == 'heaviside_down':
                damage_func = lambda x: np.heaviside(x - fault_pos, 1)

            if damage_opt == 'exp':
                damage_func = lambda x: (
                    width / (abs(x - fault_pos) + width)
                )  # NEED TO DEFINE BUFF -> similar to c value in aftershocks

            def mk_dict(rmg, damage_func, ao, am):
                lith_ary = ao + (am - ao) * damage_func(rmg.node_y)
                damage_dict = dict(zip(rmg.node_y, lith_ary))
                return damage_dict

            attrs = {
                'K_sp': mk_dict(self.rmg, damage_func, ko, km),
                'D': mk_dict(self.rmg, damage_func, Do, Dm)
            }

            lith = Lithology(
                self.rmg,
                self.rmg.ones().ravel().reshape(1, len(
                    self.rmg.node_y)),  # note that this is a dummy thickness
                self.rmg.node_y.reshape(1, len(self.rmg.node_y)),
                attrs,
                rock_id=self.rmg.node_y)

            self.rmg['node']['topographic__elevation'] += 1.
            lith.run_one_step()
            #imshow_grid(self.rmg, 'K_sp', cmap='viridis', vmin=ko, vmax=km)
            return lith

    # define the position of the fault
    this_fault = fault(rmg, fault_pos, fault_opt['width'])
    this_fault.lithology(damage_opt=fault_opt['damage_prof'],
                         ko=landscape['ko'],
                         km=landscape['km'],
                         Do=landscape['Do'],
                         Dm=landscape['Dm'])
    v_profile, accum_disp = this_fault.slip_profile(
        fault_opt['slip_profile'],
        fault_opt['localization'] * fault_opt['width'])
    # This is an array for counting how many pixels need to be moved
    nshift = np.zeros(nrows)
    n_buff = 0  # optional extra buffer zone incase you only want to move a subset.

    ################################################################################
    ## Next, we instantiate landlab components that will evolve the landscape #####
    ################################################################################

    fr = FlowAccumulator(
        rmg, 'topographic__elevation',
        flow_director='FlowDirectorD8')  # standard D8 flow routing algorithm
    sp = FastscapeEroder(rmg,
                         K_sp='K_sp',
                         m_sp=landscape['m'],
                         n_sp=landscape['n'],
                         threshold_sp=0)  # river eroder
    lin_diffuse = LinearDiffuser(rmg, linear_diffusivity='D')  #linear diffuser
    fill = DepressionFinderAndRouter(rmg)  #lake filling algorithm

    ################################################################################
    ## Next, we instantiate an object to store the model output #####
    ################################################################################
    nts = int(num_frames)
    if not save_opt['save_out'] == False:
        # define the base coordinates of the grid
        ds = xr.Dataset(
            coords={
                'x': (
                    ('x'),  # tuple of dimensions
                    rmg.x_of_node.reshape(rmg.shape)[
                        0, :],  # 1-d array of coordinate data
                    {
                        'units': 'meters'
                    }),  # dictionary with data attributes
                'y': (('y'), rmg.y_of_node.reshape(rmg.shape)[:, 1], {
                    'units': 'meters'
                }),
                'time': (('time'), duration['dt'] * np.arange(nts) / 1e6, {
                    'units': 'millions of years since model start',
                    'standard_name': 'time'
                })
            })

        # introduce the fields according the the fields specified in "save_opt"
        for of in save_opt['out_fields']:
            ds[of] = (('time', 'y', 'x'),
                      np.empty((nts, rmg.shape[0], rmg.shape[1])), {
                          'units': 'meters'
                      })

    plotCounter = 0

    ################################################################################
    # Now that all parameters and landlab components are set, run the loop #######
    ################################################################################

    dt = duration['dt']  # define the timestep
    mean_elev = []
    time_array = []

    with tqdm(total=duration['total_time'], position=0, leave=True) as pbar:
        while (current_time <= duration['total_time']):
            pbar.n = np.round(current_time)
            pbar.refresh()

            ## Looped boundary conditions ##

            # Because the landlab flow router isn't currently set up to use looped
            # boundary conditions, I simulated them here by duplicating the landscape
            # to the left and right such that the flow accumulator would 'see' the
            # the appropriate amount of upstream drainage area.

            rmg['node']['topographic__elevation'][(rmg.node_x < e1)] = (
                rmg['node']['topographic__elevation'][(rmg.node_x >= (e2 - e1))
                                                      & (rmg.node_x < e2)])

            rmg['node']['topographic__elevation'][(rmg.node_x >= e2)] = (
                rmg['node']['topographic__elevation'][(rmg.node_x >= e1) &
                                                      (rmg.node_x < (2 * e1))])

            ## Tectonic off-fault deformation ##

            # To simulate off fault lateral displacement/deformation, we apply a
            # lateral velocity profile. This is done by taking the landlab elevations
            # and shifting their coordinates.
            if (current_time > duration['shear_start']):

                dt = duration[
                    'dt_during_shear']  # First set a lower timestep to keep it stable

                # Take the landlab grid elevations and reshape into a box nrows x ncols
                elev = rmg['node']['topographic__elevation']
                elev_box = np.reshape(elev, [nrows, ncols])

                # Calculate the offset that has accumulated over a timestep
                accum_disp += v_profile * dt

                # now scan up the landscape row by row looking for offset
                for r in range(nrows):

                    # check if the accumulated offset for a row is larger than a pixel
                    if accum_disp[r] >= dxy:

                        # if so, count the number of in the row pixels to be moved
                        nshift[r] = int(np.floor(accum_disp[r] / dxy))

                        # copy which pixels will be moved off the grid by displacement
                        temp = elev_box[r, n_buff:int(nshift[r]) + n_buff]

                        # move the row over by the number of pixels of accumulated offset
                        elev_box[r, n_buff:(
                            (ncols - n_buff) -
                            int(nshift[r]))] = elev_box[r,
                                                        int(nshift[r]) +
                                                        n_buff:ncols - n_buff]

                        # replace the values on the right side by the ones from the left
                        elev_box[r, ((ncols) - int(nshift[r])):ncols] = temp

                        # last, subtract the offset pixels from the accumulated displacement
                        accum_disp[r] -= dxy

                #This section is if you select a middle section to be moved independently
                elev_box[:, (ncols -
                             n_buff):ncols] = elev_box[:, n_buff:(2 * n_buff)]
                elev_box[:, 0:n_buff] = elev_box[:, ncols - 2 * n_buff:ncols -
                                                 n_buff]

                # Finally, reshape the elevation box into an array and feed to landlab
                elev_new = np.reshape(elev_box, nrows * ncols)
                rmg['node']['topographic__elevation'] = elev_new

            # record the evolution of the mean elevation
            mean_elev.append(np.mean(rmg['node']['topographic__elevation']))
            time_array.append(current_time)

            ## Landscape Evolution ##

            # Now that we have performed the tectonic deformation, lets apply our
            # landscape evolution and watch the landscape change as a result.

            # Uplift the landscape
            rmg['node']['topographic__elevation'][
                rmg.core_nodes] += tectonics['uplift_rate'] * dt

            # set the lower boundary as fixed elevation
            #rmg['node']['topographic__elevation'][rmg.node_y==0] = 0
            #rmg['node']['topographic__elevation'][rmg.node_y==max(rmg.node_y)] = 0

            # Diffuse the landscape simulating hillslope sediment transport
            lin_diffuse.run_one_step(dt)

            # Accumulate and route flow, fill any lakes, and erode under the rivers
            fr.run_one_step()  # route flow
            DepressionFinderAndRouter.map_depressions(fill)  # fill lakes
            sp.run_one_step(dt)  # fastscape stream power eroder

            ## Plotting ##
            # plot output at each [plot_num] iteration once we start lateral advection
            if i % plot_num == 0 and current_time > duration['shear_start']:

                if not save_opt['save_out'] == False:
                    for of in save_opt['out_fields']:
                        ds[of][plotCounter, :, :] = rmg['node'][of].reshape(
                            rmg.shape)
                plotCounter += 1
            current_time += dt  # update time tracker
            i += 1  # update iteration variable
    print('number of frames:', plotCounter)
    print('For loop complete')

    ##########################################################################
    ### We do some bookkeeping with the result ###############################
    ##########################################################################
    #    plt.figure()
    #    imshow_grid(rmg,'topographic__elevation',show_elements=False)
    #    # tweek edges of domain so that they match the buffer kdc
    #    plt.xlim((e1,e2))
    #    plt.show()
    #    plt.clf

    ##########################################################################
    ## plot the evolution of the mean elevation of the model:
    if tectonics['track_uplift'] == True:
        plt.figure()
        plt.plot(time_array, mean_elev, label='Mean elevation')
        plt.axvline(duration['shear_start'],
                    color='r',
                    label='Start lateral advection')
        plt.xlabel('Iteration number')
        plt.ylabel('Mean elevation')
        plt.legend()
        plt.show()

    # small function to save a specific field as a gif
    ## plot the output into a gif
    get_ipython().run_line_magic(
        'opts',
        "Image style(interpolation='bilinear', cmap='viridis') plot[colorbar=True]"
    )
    get_ipython().run_line_magic('output', 'size=100')

    fn = save_opt['save_format']['file_name']
    dn = save_opt['save_format']['dirname']
    if save_opt['save_out'] == True:
        os.mkdir(dn)

        for of in save_opt['out_fields']:
            hvds_topo = hv.Dataset(ds[of])
            topo = hvds_topo.to(hv.Image, ['x', 'y'])
            topo.opts(colorbar=True, fig_size=200, xlim=(e1, e2))
            hv.save(topo, os.path.join(dn, fn + of + '.gif'))
        with open(os.path.join(dn, fn + '.pkl'), 'wb') as f:
            pickle.dump([rmg, ds], f)
        # and to load the session again:
        # dill.load_session(filename)
    if save_opt['save_ascii'] == True:
        write_esri_ascii(os.path.join(
            dn, save_opt['save_format']['file_name'] + '.asc'),
                         rmg,
                         names='topographic__elevation')

    if save_opt['save_out'] == 'temp':
        hv.save(topo, 'temp_output.gif')

    if save_opt['append_to_log'] == True:

        def NestedDictValues(d):
            for v in d.values():
                if isinstance(v, dict):
                    yield from NestedDictValues(v)
                else:
                    yield v

        with open('Model_log.csv', mode='a') as fd:
            writer = csv.writer(fd)
            writer.writerow(NestedDictValues(mdl_input))
    return rmg
Exemplo n.º 4
0
def run_model(input_file=None,
              savepath=None,
              initial_topo_file=None,
              initial_seed_file=None):
    from landlab.components.flow_routing.route_flow_dn_JL import FlowRouter
    from landlab.components.stream_power.fastscape_stream_power_JL import FastscapeEroder
    #from landlab.components.stream_power.stream_power import StreamPowerEroder
    from landlab.components.sink_fill.pit_fill_pf import PitFiller
    from landlab.components.diffusion.diffusion import LinearDiffuser
    from landlab import ModelParameterDictionary
    #from landlab.plot import channel_profile as prf
    from landlab.plot.imshow import imshow_node_grid
    from landlab.io.esri_ascii import write_esri_ascii
    from landlab.io.esri_ascii import read_esri_ascii
    from landlab import RasterModelGrid

    #from analysis_method import analyze_drainage_percentage
    #from analysis_method import analyze_drainage_percentage_each_grid
    #from analysis_method import analyze_mean_erosion
    #from analysis_method import elev_diff_btwn_moraine_upland
    #from analysis_method import label_catchment
    #from analysis_method import cross_section
    #from analysis_method import analyze_node_below_threshold
    #from analysis_method import identify_drained_area
    #from analysis_method import save_result
    from analysis_method import shiftColorMap

    import copy
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    import os
    import time
    import sys
    import shutil

    sys.setrecursionlimit(5000)

    #===============================================================================
    #get the needed properties to build the grid:
    if input_file is None:
        input_file = './coupled_params_sp.txt'
    inputs = ModelParameterDictionary(input_file)
    nrows = inputs.read_int('nrows')
    ncols = inputs.read_int('ncols')
    dx = inputs.read_float('dx')
    initial_slope = inputs.read_float('initial_slope')
    rightmost_elevation = initial_slope * ncols * dx
    #rightmost_elevation = inputs.read_float('rightmost_elevation')
    uplift_rate = inputs.read_float('uplift_rate')
    incision_rate = inputs.read_float('incision_rate')
    runtime = inputs.read_float('total_time')
    dt = inputs.read_float('dt')
    nt = int(runtime // dt)
    k_sp = inputs.read_float('K_sp')
    m_sp = inputs.read_float('m_sp')
    uplift_per_step = uplift_rate * dt
    incision_per_step = incision_rate * dt
    moraine_height = inputs.read_float('moraine_height')
    moraine_width = inputs.read_float('moraine_width')
    #valley_width = inputs.read_float('valley_width')
    valley_depth = inputs.read_float('valley_depth')
    num_outs = inputs.read_int('number_of_outputs')
    output_interval = int(nt // num_outs)
    diff = inputs.read_float('linear_diffusivity')
    #threshold_stream_power = inputs.read_float('threshold_stream_power')
    threshold_AS = inputs.read_float('threshold_AS')
    #threshold_erosion = dt*threshold_stream_power
    gw_coeff = inputs.read_float('gw_coeff')
    all_dry = inputs.read_bool('all_dry')
    fill_sink_with_water = inputs.read_bool('fill_sink_with_water')
    #===============================================================================

    #===============================================================================
    if initial_topo_file is None:
        #instantiate the grid object
        mg = RasterModelGrid(nrows, ncols, dx)

        ##create the elevation field in the grid:
        #create the field
        #specifically, this field has a triangular ramp
        #moraine at the north edge of the domain.
        mg.add_zeros('node', 'topographic__elevation', units='m')
        z = mg.at_node['topographic__elevation']
        moraine_start_y = np.max(mg.node_y) - moraine_width
        moraine_ys = np.where(mg.node_y > moraine_start_y)
        z[moraine_ys] += (mg.node_y[moraine_ys] - np.min(
            mg.node_y[moraine_ys])) * (moraine_height / moraine_width)

        #set valley
        #valley_start_x = np.min(mg.node_x)+valley_width
        #valley_ys = np.where((mg.node_x<valley_start_x)&(mg.node_y<moraine_start_y-valley_width))
        #z[valley_ys] -= (np.max(mg.node_x[valley_ys])-mg.node_x[valley_ys])*(valley_depth/valley_width)

        #set ramp (towards valley)
        upland = np.where(mg.node_y < moraine_start_y)
        z[upland] -= (np.max(mg.node_x[upland]) -
                      mg.node_x[upland]) * (rightmost_elevation / (ncols * dx))
        z += rightmost_elevation

        #set ramp (away from moraine)
        #upland = np.where(mg.node_y<moraine_start_y)
        #z[upland] -= (moraine_start_y-mg.node_y[upland])*initial_slope

        #put these values plus roughness into that field
        if initial_seed_file is None:
            z += np.random.rand(len(z)) / 1
        else:
            (seedgrid,
             seed) = read_esri_ascii(initial_seed_file,
                                     name='topographic__elevation_seed')
            z += seed
        mg.at_node['topographic__elevation'] = z

        #set river valley
        river_valley, = np.where(
            np.logical_and(
                mg.node_x == 0,
                np.logical_or(mg.status_at_node == 1, mg.status_at_node == 2)))
        mg.at_node['topographic__elevation'][river_valley] = -valley_depth
    else:
        (mg, z) = read_esri_ascii(initial_topo_file,
                                  name='topographic__elevation')

    #set river valley
    river_valley, = np.where(
        np.logical_and(
            mg.node_x == 0,
            np.logical_or(mg.status_at_node == 1, mg.status_at_node == 2)))
    mg.at_node['topographic__elevation'][river_valley] = -valley_depth

    #set up grid's boundary conditions (right, top, left, bottom) is inactive
    mg.set_closed_boundaries_at_grid_edges(True, True, False, True)

    #set up boundary along moraine
    #moraine_start_y = np.max(mg.node_y)-moraine_width
    #bdy_moraine_ids = np.where((mg.node_y > moraine_start_y) & (mg.node_x == 0))
    #mg.status_at_node[bdy_moraine_ids]=4
    #mg._update_links_nodes_cells_to_new_BCs()
    #===============================================================================

    #===============================================================================
    #instantiate the components:
    fr = FlowRouter(mg)
    pf = PitFiller(mg)
    sp = FastscapeEroder(mg, input_file, threshold_sp=threshold_AS * k_sp)
    #sp = StreamPowerEroder(mg, input_file, threshold_sp=threshold_erosion, use_Q=True)
    #diffuse = PerronNLDiffuse(mg, input_file)
    #lin_diffuse = LinearDiffuser(mg, input_file, method='on_diagonals')
    lin_diffuse = LinearDiffuser(mg, input_file)
    #===============================================================================

    #===============================================================================
    #instantiate plot setting
    plt.close('all')
    output_time = output_interval
    plot_num = 0
    mycmap = shiftColorMap(matplotlib.cm.gist_earth, 'mycmap')

    #folder name
    if savepath is None:
        if all_dry:
            name_tag = 'All_dry'
        elif fill_sink_with_water:
            name_tag = 'Not_all_dry_no_sink'
        else:
            name_tag = 'Not_all_dry_sink'
        savepath = 'results/sensitivity_test_threshold_same_seed/'+name_tag+'_dt=' + str(dt) + '_total_time=' + str(runtime) + '_k_sp=' + str(k_sp) + \
                '_uplift_rate=' + str(uplift_rate) + '_incision_rate=' + str(incision_rate) + '_initial_slope=' + str(initial_slope) + \
                '_threshold=' + str(threshold_stream_power)
    if not os.path.isdir(savepath):
        os.makedirs(savepath)

    #copy params_file
    if not os.path.isfile(savepath + '/coupled_params_sp.txt'):
        shutil.copy(input_file, savepath + '/coupled_params_sp.txt')

    # Display a message
    print 'Running ...'
    print savepath

    #save initial topography
    write_esri_ascii(savepath + '/Topography_t=0.0.txt', mg,
                     'topographic__elevation')

    #time
    start_time = time.time()
    #===============================================================================

    #===============================================================================
    #perform the loops:
    for i in xrange(nt):
        #note the input arguments here are not totally standardized between modules
        ''' 
        # simulate changing climate
        if (((i+1)*dt // 5000.) % 2) == 0.:
            all_dry = False
        else:
            all_dry = True
        '''

        #sp = FastscapeEroder(mg, input_file, threshold_sp = threshold_stream_power)

        #update elevation
        mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step
        mg.at_node['topographic__elevation'][river_valley] -= incision_per_step

        #mg = lin_diffuse.diffuse(dt)

        #route and erode
        original_topo = mg.at_node['topographic__elevation'].copy()
        slope = mg.at_node['topographic__steepest_slope'].copy()
        filled_nodes = None
        if all_dry or fill_sink_with_water:
            mg = pf.pit_fill()
            filled_nodes, = np.where(
                (mg.at_node['topographic__elevation'] - original_topo) > 0)
        mg = fr.route_flow(routing_flat=all_dry)
        old_topo = mg.at_node['topographic__elevation'].copy()
        #mg, temp_z, temp_sp = sp.erode(mg, dt, Q_if_used='water__volume_flux')
        mg = sp.erode(mg, dt, flooded_nodes=filled_nodes)

        new_topo = mg.at_node['topographic__elevation'].copy()
        mg.at_node[
            'topographic__elevation'] = original_topo + new_topo - old_topo

        #diffuse
        #for j in range(10):
        #    mg = lin_diffuse.diffuse(dt/10)
        mg = lin_diffuse.diffuse(dt)

        if i + 1 == output_time:
            print 'Saving data...'

            plot_num += 1
            plt.figure(plot_num)
            im = imshow_node_grid(mg, 'topographic__elevation', plot_name='t = '+str(int((i+1)*dt))+' years', \
                grid_units = ['m','m'], cmap=mycmap, allow_colorbar=True, \
                vmin=0-valley_depth-incision_rate*runtime, vmax=5.+moraine_height+uplift_rate*runtime)
            plt.savefig(savepath + '/Topography_t=' + str(
                (i + 1) * dt) + '.jpg',
                        dpi=300)

            write_esri_ascii(
                savepath + '/Topography_t=' + str((i + 1) * dt) + '.txt', mg,
                'topographic__elevation')

            output_time += output_interval

        plt.close('all')

        print("--- %.2f minutes ---" %
              ((time.time() - start_time) / 60)), 'Completed loop', i + 1

    plt.close('all')

    print 'Finished simulating.'
    #===============================================================================

    #===============================================================================
    #analyze_drainage_percentage(savepath, True)
    #analyze_mean_erosion(savepath, True)
    #elev_diff_btwn_moraine_upland(savepath, True)
    #label_catchment(savepath)
    #cross_section(savepath)
    #===============================================================================

    print 'Done!'
    print '\n'
Exemplo n.º 5
0
                     threshold_sp=0.0)  #k eh erodibilidade, usar 0.0004
#FastscapeEroder(grid, K_sp=0.001, m_sp=0.5, n_sp=1.0, threshold_sp=0.0, discharge_field='drainage_area', erode_flooded_nodes=True)
ed = ErosionDeposition(
    mg,
    K=0.0004,  # Erodibility for substrate (units vary)valor anterior = 0.00001
    v_s=0.001,  # Effective settling velocity for chosen grain size metric [L/T].
    m_sp=
    0.5,  # Discharge exponent (units vary) usar valores do fast scape (valor anterior = 0.5)
    n_sp=1.0,  #Slope exponent (units vary) usar valores do fast scape
    sp_crit=0
)  #Critical stream power to erode substrate [E/(TL^2)] usar valores do fast scape
lin_diffuse = LinearDiffuser(mg, linear_diffusivity=0.01)

uplift_rate = 0.001
time_step = 1000
fr.run_one_step()
sp.run_one_step(time_step)
for i in range(101):
    print(i)
    fr.run_one_step()
    df.map_depressions()
    flooded = np.where(df.flood_status == 3)[0]  # ver pra que serve
    ed.run_one_step(time_step)
    mg.at_node['topographic__elevation'] += time_step * uplift_rate
    #no artigo ele usa em anos mas esta de acordo com todos os outros parametros em anos tbm
    #lin_diffuse.run_one_step(time_step)
    css.run_one_step()
    if i == 1 or i == 10 or i == 20 or i == 40 or i == 60 or i == 80 or i == 100:
        files = write_esri_ascii(
            "../testes_dispersao/" + test_name + "/" + str(i) + ".asc", mg)