def main(cls): parser = cls.argparser() args = parser.parse_args() params = load_model_params(param_file=args.file, defaults=cls.DEFAULT_PARAMS, dotted_params=args.set) if args.verbose: print(yaml.dump(params, default_flow_style=False)) model = cls(**params) if args.with_citations: from landlab.core.model_component import registry print(registry.format_citations()) if not args.dry_run: model.run(output=args.output, names=args.fields or None) if args.plot: imshow_grid(model.grid, model.grid.at_node[cls.LONG_NAME[args.plot]], at='node', show=True, cmap='Blues')
def plot_veg_type(grid, veg_type, yr, savename=''): cmap = mpl.colors.ListedColormap([(0, 0.6, 0.5), (0.8, 0.4, 0), (0, 0, 0), (1, 1, 1), (0.8, 0.4, 0), (0, 0, 0)]) bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) plt.figure(figsize=(10, 5)) imshow_grid(grid, veg_type, values_at='cell', cmap=cmap, grid_units=('m', 'm'), norm=norm, limits=[0, 5], allow_colorbar=False, color_for_closed='white') # if elev_provided: # clt = plt.contour(xx, yy, elev_grid, colors='b', # figsize=(10, 8), linewidths=3) # plt.clabel(clt, inline=1, fmt='%4.0f', fontsize=12) name = 'PFT at Year = ' + "%05d" % yr plt.title(name, weight='bold', fontsize=22) plt.xlabel('X (m)', weight='bold', fontsize=18) plt.ylabel('Y (m)', weight='bold', fontsize=18) plt.xticks(fontsize=14, weight='bold') plt.yticks(fontsize=14, weight='bold') savename = savename + ' vegtype_at_' + str(yr) + '_yrs' plt.tight_layout() plt.savefig(savename)
def replot(nc): print(nc) grid = read_netcdf(nc) z = grid.at_node['topographic__elevation'] fig_name = glob.glob(os.path.split(nc)[0] + os.sep + '*png')[0] inputs = glob.glob(os.path.split(nc)[0] + os.sep + 'inputs.txt')[0] with open(inputs, 'r') as f: params = yaml.load(f) outlet_id = params['outlet_id'] grid.set_watershed_boundary_condition_outlet_id(outlet_id, z, nodata_value=-9999) #fig_name imshow_grid(grid, 'topographic__elevation', vmin=1161, vmax=1802, cmap='viridis', output=fig_name) return True
def plot(sim, grid, veg_type, yrs, yr_step=10): pic = 0 years = range(0, yrs) cmap = mpl.colors.ListedColormap( ['green', 'red', 'black', 'white', 'red', 'black']) bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) print 'Plotting cellular field of Plant Functional Type' print 'Green - Grass; Red - Shrubs; Black - Trees; White - Bare' # Plot images to make gif. for year in range(0, yrs, yr_step): filename = 'year_' + "%05d" % year pic += 1 plt.figure(pic, figsize=(10, 8)) imshow_grid(grid, veg_type[year], values_at='cell', cmap=cmap, grid_units=('m', 'm'), norm=norm, limits=[0, 5], allow_colorbar=False) plt.title(filename, weight='bold', fontsize=22) plt.xlabel('X (m)', weight='bold', fontsize=18) plt.ylabel('Y (m)', weight='bold', fontsize=18) plt.xticks(fontsize=14, weight='bold') plt.yticks(fontsize=14, weight='bold') plt.savefig(sim + '_' + filename) grass_cov = np.empty(yrs) shrub_cov = np.empty(yrs) tree_cov = np.empty(yrs) grid_size = float(veg_type.shape[1]) for x in range(0, yrs): grass_cov[x] = ((veg_type[x][veg_type[x] == GRASS].size / grid_size) * 100) shrub_cov[x] = ( (veg_type[x][veg_type[x] == SHRUB].size / grid_size) * 100 + (veg_type[x][veg_type[x] == SHRUBSEEDLING].size / grid_size) * 100) tree_cov[x] = ( (veg_type[x][veg_type[x] == TREE].size / grid_size) * 100 + (veg_type[x][veg_type[x] == TREESEEDLING].size / grid_size) * 100) pic += 1 plt.figure(pic, figsize=(10, 8)) plt.plot(years, grass_cov, '-g', label='Grass', linewidth=4) plt.hold(True) plt.plot(years, shrub_cov, '-r', label='Shrub', linewidth=4) plt.hold(True) plt.plot(years, tree_cov, '-k', label='Tree', linewidth=4) plt.ylabel('% Area Covered by Plant Type', weight='bold', fontsize=18) plt.xlabel('Time in years', weight='bold', fontsize=18) plt.xticks(fontsize=12, weight='bold') plt.yticks(fontsize=12, weight='bold') plt.xlim((0, yrs)) plt.ylim(ymin=0, ymax=100) plt.legend(loc=1, prop={'size': 16, 'weight': 'bold'}) plt.savefig(sim + '_percent_cover')
def plott( self, RMG ): figure(1) imshow_grid(RMG,self._Z, values_at = 'node') savefig('figure1') figure(2) self._slope_[self._slope_ >= 1] = 1 imshow_active_cells(RMG, self._slope_, 'Slope', None, ('m','m')) savefig('figure2') figure(3) imshow_active_cells(RMG,self._Si, \ 'Cosine of Solar Angle of Incidence', None, ('m','m')) savefig('figure3') figure(4) imshow_active_cells(RMG,self._BETA, \ 'Aspect (clockwise from North)', 'radians', ('m','m')) savefig('figure4') figure(5) imshow_active_cells(RMG,self._Rs, \ 'Incoming Shortwave Radiation', 'W/m^2', ('m','m')) savefig('figure5')
def plot_channels_in_map_view(grid, profile_structure, field='topographic__elevation', **kwargs): """ Plot channel locations in map view on a frame. Parameters ---------- grid, model grid instance. field, name or nnode long array to plot with imshow_grid profile_IDs: profile_IDs datastructure **kwargs: additional parameters to pass to imshow_grid """ # make imshow_grid background imshow_grid(grid, field, **kwargs) # for each stream network for i in range(len(profile_structure)): network_nodes = profile_structure[i] # for each stream segment in the network for j in range(len(network_nodes)): # identify the nodes and distances upstream for this channel segment the_nodes = network_nodes[j] plt.plot(grid.x_of_node[the_nodes], grid.y_of_node[the_nodes])
def example_test2(): from landlab.io.netcdf import write_netcdf # INITIALIZE # User-defined parameters nr = 10 nc = 10 plot_interval = 0.1 next_plot = plot_interval run_duration = 1.0 # Create grid and set up boundaries mg = RasterModelGrid(nr, nc, 1.0) mg.set_inactive_boundaries(True, True, True, True) # Transition data here represent a body of fractured rock, with rock # represented by nodes with state 0, and saprolite (weathered rock) # represented by nodes with state 1. Node pairs (links) with 0-1 or 1-0 # can undergo a transition to 1-1, representing chemical weathering of the # rock. ns_dict = { 0 : 'air', 1 : 'immobile soil', 2 : 'mobile soil' } xn_list = setup_transition_list2() # The initial grid represents a domain with half immobile soil, half air node_state_grid = mg.add_zeros('node', 'node_frog') print (numpy.where(mg.node_y<nr/2),) (lower_half,) = numpy.where(mg.node_y<nr/2) node_state_grid[lower_half] = 1 # Create the CA model ca = LinkCellularAutomaton(mg, ns_dict, xn_list, node_state_grid) # Plot initial state plt.figure() imshow_grid(mg, ca.node_state) # RUN current_time = 0.0 time_slice = 0 filename = 'soil_ca1-'+str(time_slice).zfill(5)+'.nc' write_netcdf(filename, ca.grid) while current_time < run_duration: ca.run(current_time+plot_interval, ca.node_state) current_time += plot_interval print 'time:',current_time print 'ca time:',ca.current_time #plt.figure() #imshow_grid(mg, ca.node_state) #plt.show() time_slice += 1 filename = 'soil_ca1-'+str(time_slice).zfill(5)+'.nc' write_netcdf(filename, ca.grid)
def example_test2(): from landlab.io.netcdf import write_netcdf # INITIALIZE # User-defined parameters nr = 10 nc = 10 plot_interval = 0.1 next_plot = plot_interval run_duration = 1.0 # Create grid and set up boundaries mg = RasterModelGrid(nr, nc, 1.0) mg.set_inactive_boundaries(True, True, True, True) # Transition data here represent a body of fractured rock, with rock # represented by nodes with state 0, and saprolite (weathered rock) # represented by nodes with state 1. Node pairs (links) with 0-1 or 1-0 # can undergo a transition to 1-1, representing chemical weathering of the # rock. ns_dict = {0: 'air', 1: 'immobile soil', 2: 'mobile soil'} xn_list = setup_transition_list2() # The initial grid represents a domain with half immobile soil, half air node_state_grid = mg.add_zeros('node', 'node_frog') print(numpy.where(mg.node_y < nr / 2), ) (lower_half, ) = numpy.where(mg.node_y < nr / 2) node_state_grid[lower_half] = 1 # Create the CA model ca = LinkCellularAutomaton(mg, ns_dict, xn_list, node_state_grid) # Plot initial state plt.figure() imshow_grid(mg, ca.node_state) # RUN current_time = 0.0 time_slice = 0 filename = 'soil_ca1-' + str(time_slice).zfill(5) + '.nc' write_netcdf(filename, ca.grid) while current_time < run_duration: ca.run(current_time + plot_interval, ca.node_state) current_time += plot_interval print 'time:', current_time print 'ca time:', ca.current_time #plt.figure() #imshow_grid(mg, ca.node_state) #plt.show() time_slice += 1 filename = 'soil_ca1-' + str(time_slice).zfill(5) + '.nc' write_netcdf(filename, ca.grid)
def plot_marked_cells(cells, grid, values=None, marker='x', marker_color='k'): # if import_packages==True: # import matplotlib.pyplot as plt # from landlab.plot import imshow_grid # import numpy as np nodes = grid.node_at_cell[cells] if values == None: values = np.zeros(grid.number_of_nodes) plt.figure(figsize=(10, 8)) imshow_grid(grid, values=values, values_at='node', cmap='jet') plt.plot(grid.x_of_node[nodes], grid.y_of_node[nodes], marker + marker_color)
def plot_results(grid, VegType, yrs, yr_step=10): # # Plotting pic = 0 years = range(0, yrs) cmap = mpl.colors.ListedColormap( ['green', 'red', 'black', 'white', 'red', 'black']) bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) print('Plotting cellular field of Plant Functional Type') print('Green - Grass; Red - Shrubs; Black - Trees; White - Bare') # # Plot images to make gif. for year in range(0, yrs, yr_step): filename = 'Year = ' + "%05d" % year pic += 1 plt.figure(pic) imshow_grid(grid, VegType[year], values_at='cell', cmap=cmap, grid_units=('m', 'm'), norm=norm, limits=[0, 5], allow_colorbar=False) plt.title(filename) plt.savefig(filename) grass_cov = np.empty(yrs) shrub_cov = np.empty(yrs) tree_cov = np.empty(yrs) grid_size = float(VegType.shape[1]) for x in range(0, yrs): grass_cov[x] = (VegType[x][VegType[x] == GRASS].size / grid_size) * 100 shrub_cov[x] = ( (VegType[x][VegType[x] == SHRUB].size / grid_size) * 100 + (VegType[x][VegType[x] == SHRUBSEEDLING].size / grid_size) * 100) tree_cov[x] = ( (VegType[x][VegType[x] == TREE].size / grid_size) * 100 + (VegType[x][VegType[x] == TREESEEDLING].size / grid_size) * 100) pic += 1 plt.figure(pic) plt.plot(years, grass_cov, '-g', label='Grass') plt.hold(True) plt.plot(years, shrub_cov, '-r', label='Shrub') plt.hold(True) plt.plot(years, tree_cov, '-k', label='Tree') plt.xlim(xmin=0, xmax=years[-1]) plt.ylim( ymin=0, ymax=(max(np.max(grass_cov), np.max(shrub_cov), np.max(tree_cov)) + 10)) plt.ylabel(' % Coverage ') plt.xlabel('Time in years') plt.legend(loc=0) plt.savefig('PercentageCover_PFTs')
def replot(nc): nc_full = os.path.abspath(nc) print(nc_full) grid = read_netcdf(nc) # z = modeled modern z = grid.at_node['topographic__elevation'] fig_name = fig_out + os.path.sep + '.'.join(nc_full.split(os.path.sep)[6:9])+'.png' inputs = glob.glob(os.path.split(nc)[0] + os.sep + 'inputs.txt')[0] with open(inputs, 'r') as f: params = yaml.load(f) outlet_id = params['outlet_id'] initial_dem = params['DEM_filename'] grid.set_watershed_boundary_condition_outlet_id(outlet_id, z, nodata_value=-9999) # read modern and initial # iz = initial (igrid, iz) = read_esri_ascii(initial_dem, name='topographic__elevation', halo=1) igrid.set_watershed_boundary_condition_outlet_id(outlet_id, z, nodata_value=-9999) #topographic change from start elevation_change = z - iz ec_lim = np.max(np.abs(elevation_change[grid.core_nodes])) fs = (3, 2.4) fig, ax = plt.subplots(figsize=fs, dpi=300) imshow_grid(grid, z, vmin=1230, vmax=1940, cmap='viridis', plot_name='End of Model Run Topography [ft]') line_segments = LineCollection(segments, colors='k', linewidth=0.1) plt.axis('off') ax.add_collection(line_segments) plt.savefig(fig_name[:-4]+'.png') fig, ax = plt.subplots(figsize=fs, dpi=300) imshow_grid(grid, elevation_change, vmin=-160, vmax=160, cmap='RdBu', plot_name='Change Since Start [ft]') line_segments = LineCollection(segments, colors='k', linewidth=0.1) plt.axis('off') ax.add_collection(line_segments) plt.savefig(fig_name[:-4]+'.elevation_change_since_start.png') plt.close('all') return True
def plot(sim, grid, veg_type, yrs, yr_step=10): pic = 0 years = range(0, yrs) cmap = mpl.colors.ListedColormap( ['green', 'red', 'black', 'white', 'red', 'black']) bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) print 'Plotting cellular field of Plant Functional Type' print 'Green - Grass; Red - Shrubs; Black - Trees; White - Bare' # Plot images to make gif. for year in range(0, yrs, yr_step): filename = 'year_' + "%05d" % year pic += 1 plt.figure(pic, figsize=(10, 8)) imshow_grid(grid, veg_type[year], values_at='cell', cmap=cmap, grid_units=('m', 'm'), norm=norm, limits=[0, 5], allow_colorbar=False) plt.title(filename, weight='bold', fontsize=22) plt.xlabel('X (m)', weight='bold', fontsize=18) plt.ylabel('Y (m)', weight='bold', fontsize=18) plt.xticks(fontsize=14, weight='bold') plt.yticks(fontsize=14, weight='bold') plt.savefig(sim + '_' + filename) grass_cov = np.empty(yrs) shrub_cov = np.empty(yrs) tree_cov = np.empty(yrs) grid_size = float(veg_type.shape[1]) for x in range(0, yrs): grass_cov[x] = (veg_type[x][veg_type[x] == GRASS].size / grid_size) * 100 shrub_cov[x] = ((veg_type[x][veg_type[x] == SHRUB].size / grid_size) * 100 + (veg_type[x][veg_type[x] == SHRUBSEEDLING].size / grid_size) * 100) tree_cov[x] = ((veg_type[x][veg_type[x] == TREE].size / grid_size) * 100 + (veg_type[x][veg_type[x] == TREESEEDLING].size / grid_size) * 100) pic += 1 plt.figure(pic, figsize=(10, 8)) plt.plot(years, grass_cov, '-g', label='Grass', linewidth=4) plt.hold(True) plt.plot(years, shrub_cov, '-r', label='Shrub', linewidth=4) plt.hold(True) plt.plot(years, tree_cov, '-k', label='Tree', linewidth=4) plt.ylabel('% Area Covered by Plant Type', weight='bold', fontsize=18) plt.xlabel('Time in years', weight='bold', fontsize=18) plt.xticks(fontsize=12, weight='bold') plt.yticks(fontsize=12, weight='bold') plt.legend(loc=0, prop={'size': 16, 'weight': 'bold'}) plt.savefig(sim + '_percent_cover')
def main(): parser = argparse.ArgumentParser() parser.add_argument('file', nargs='?', help='plume config file') parser.add_argument('--output', help='output file') parser.add_argument('--verbose', action='store_true', help='be verbose') parser.add_argument('--plot', choices=('c', 'cs', 'dz'), default=None, help='value to plot') parser.add_argument('--set', action='append', default=[], help='set plume parameters') args = parser.parse_args() params = DEFAULT_PARAMS if args.file: params_from_file = load_params(args.file) for group in params.keys(): params[group].update(params_from_file.get(group, {})) params_from_cl = load_params_from_strings(args.set) for group in params.keys(): params[group].update(params_from_cl.get(group, {})) if args.verbose: print(yaml.dump(params, default_flow_style=False)) params['river']['angle'] = np.deg2rad(params['river']['angle']) grid = RasterModelGrid(params['grid']['shape'], spacing=params['grid']['spacing'], origin=params['grid']['origin']) plume = Plume(grid, river_width=params['river']['width'], river_depth=params['river']['depth'], river_velocity=params['river']['velocity'], river_angle=params['river']['angle'], river_loc=params['river']['location'], ocean_velocity=params['ocean']['along_shore_velocity'], ) plume.grid.at_grid['sediment__removal_rate'] = params['sediment']['removal_rate'] plume.grid.at_grid['sediment__bulk_density'] = params['sediment']['bulk_density'] deposit = plume.calc_deposit_thickness(params['sediment']['removal_rate']) if args.plot: imshow_grid(plume.grid, plume.grid.at_node[LONG_NAME[args.plot]], at='node', show=True) if args.output: write_raster_netcdf(args.output, plume.grid)
def plot_profiles_in_map_view(self, field="topographic__elevation", endpoints_only=False, color=None, **kwds): """Plot profile locations in map view. Parameters ---------- field : field name or nnode array Array of the at-node-field to plot as the 2D map values. Default value is the at-node field 'topographic__elevation'. endpoints_only : boolean Boolean where False (default) indicates every node along the profile is plotted, or True indicating only segment endpoints are plotted. color : RGBA tuple or color string Color to use in order to plot all profiles the same color. Default is None, and the colors assigned to each profile are used. **kwds : dictionary Keyword arguments to pass to imshow_grid. """ # make imshow_grid background imshow_grid(self._grid, field, **kwds) ax = plt.gca() # create segments the way that line collection likes them. segments = [] for idx, nodes in enumerate(self._nodes): if endpoints_only: select_nodes = [nodes[0], nodes[-1]] segments.append( list( zip( self._grid.x_of_node[select_nodes], self._grid.y_of_node[select_nodes], ))) else: segments.append( list( zip(self._grid.x_of_node[nodes], self._grid.y_of_node[nodes]))) line_segments = LineCollection(segments) colors = color or self._colors line_segments.set_color(colors) ax.add_collection(line_segments)
def Plot_( grid, VegType, yrs, yr_step=10 ): ## Plotting pic = 0 years = range(0,yrs) cmap = mpl.colors.ListedColormap( \ [ 'green', 'red', 'black', 'white', 'red', 'black' ] ) bounds = [-0.5,0.5,1.5,2.5,3.5,4.5,5.5] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) print 'Plotting cellular field of Plant Functional Type' print 'Green - Grass; Red - Shrubs; Black - Trees; White - Bare' ## Plot images to make gif. for year in range(0,yrs,yr_step): filename = 'Year = ' + "%05d" % year pic += 1 plt.figure(pic) imshow_grid(grid,VegType[year],values_at = 'cell', cmap=cmap, \ grid_units=('m', 'm'), norm=norm, limits = [0,5] ,\ allow_colorbar = False) plt.title(filename) plt.savefig(filename) grass_cov = np.empty(yrs) shrub_cov = np.empty(yrs) tree_cov = np.empty(yrs) grid_size = float(VegType.shape[1]) for x in range(0,yrs): grass_cov[x] = (VegType[x][VegType[x] == GRASS].size/grid_size) * 100 shrub_cov[x] = (VegType[x][VegType[x] == SHRUB].size/grid_size) * 100 + \ (VegType[x][VegType[x] == SHRUBSEEDLING].size/grid_size) * 100 tree_cov[x] = (VegType[x][VegType[x] == TREE].size/grid_size) * 100 + \ (VegType[x][VegType[x] == TREESEEDLING].size/grid_size) * 100 pic += 1 plt.figure(pic) plt.plot(years, grass_cov, '-g', label = 'Grass') plt.hold(True) plt.plot(years, shrub_cov, '-r', label = 'Shrub') plt.hold(True) plt.plot(years, tree_cov, '-k', label = 'Tree') plt.ylabel(' % Coverage ') plt.xlabel('Time in years' ) plt.legend(loc = 0) plt.savefig('PercentageCover_PFTs')
def main(cls): parser = cls.argparser() args = parser.parse_args() # params = cls.DEFAULT_PARAMS # if args.file: # params_from_file = load_params(args.file) # for group in params.keys(): # params[group].update(params_from_file.get(group, {})) # params_from_cl = load_params_from_strings(args.set) # for group in params.keys(): # params[group].update(params_from_cl.get(group, {})) params = load_model_params(param_file=args.file, defaults=cls.DEFAULT_PARAMS, dotted_params=args.set) if args.verbose: print(yaml.dump(params, default_flow_style=False)) model = cls(**params) if args.with_citations: from landlab.core.model_component import registry print(registry.format_citations()) if not args.dry_run: model.run(output=args.output) if args.plot: imshow_grid( model.grid, model.grid.at_node[cls.LONG_NAME[args.plot]], at="node", show=True, cmap="Blues", )
## Run model with a 100x100 grid (increasing to 200x200 will increase timing significantly). First step will be slower, because flow routing takes more time. n = 200 mg = RasterModelGrid((n, n), 100.0) z = mg.add_zeros('node', 'topographic__elevation') mg.set_closed_boundaries_at_grid_edges(right_is_closed=False, top_is_closed=False, \ left_is_closed=False, bottom_is_closed=False) #Create an uplifted block blockuplift_nodes = np.where((mg.node_y < 17500) & (mg.node_y > 2500) & (mg.node_x < 17500) & (mg.node_x > 2500)) z[blockuplift_nodes] += 100.0 z[blockuplift_nodes] += np.random.rand(len(blockuplift_nodes[0])) * 10 pl.figure() imshow_grid(mg, 'topographic__elevation', plot_name='Initial Topography of Uplifted block', allow_colorbar=True) ld = LinearDiffuser(mg, linear_diffusivity=0.01) fr = FlowAccumulator(mg, flow_director='D8') fse = FastscapeEroder(mg, K_sp=5e-5, m_sp=0.5, n_sp=1.) sf = SinkFiller(mg, routing='D8') ## instantiate helper components chif = ChiFinder(mg) steepnessf = SteepnessFinder(mg, reference_concavity=0.5) ## Set some variables rock_up_rate = 1e-3 #m/yr dt = 1000 # yr rock_up_len = dt * rock_up_rate # m
# calc grouped differences: gd = GroupedDifferences(topo_file, observed_topo_file_name, outlet_id=outlet_id, category_values=cat, weight_values=cat_wt) gd.calculate_metrics() cat_resids = gd.metric cat_diff[model] = cat_resids # for modeled and True, # elevation, slope, erosion, shaded, chi f, axarr = plt.subplots(3, 2, sharex=True, figsize=(8.5,11)) # elevation plt.sca(axarr[0,0]) plt.title('Observations') plt.text(0.2, 0.9, 'Elevation', color='w', ha='center', va='center', transform=axarr[0,0].transAxes) imshow_grid(grid, z, vmin=1230, vmax=1940, cmap='jet')#, color_for_closed='w') plt.sca(axarr[0,1]) plt.title(model) imshow_grid(mgrid, mz, vmin=1230, vmax=1940, cmap='jet')#, color_for_closed='w') # erosion plt.sca(axarr[1,0]) plt.text(0.2, 0.9, 'Erosion Depth', color='w', ha='center', va='center', transform=axarr[1,0].transAxes) imshow_grid(grid, iz-z, vmin=-120, vmax=120, cmap='RdBu_r') plt.sca(axarr[1,1]) imshow_grid(mgrid, iz-mz, vmin=-120, vmax=120, cmap='RdBu_r') # slope plt.sca(axarr[2,0])
#%% # observed_topography observed_topo_file_name = inputs['modern_dem_name'] (grid, z) = read_esri_ascii(observed_topo_file_name, name='topographic__elevation', halo=1) grid.set_watershed_boundary_condition_outlet_id(inputs['outlet_id'], z, nodata_value=-9999) fa = FlowAccumulator(grid, flow_director='D8', depression_finder='DepressionFinderAndRouter') fa.run_one_step() area = grid.dx**2 imshow_grid(grid, np.log10(fa.drainage_area / area + 1)) plt.show() #%% # initial condition topography initial_topo_file_name = inputs['DEM_filename'] (igrid, iz) = read_esri_ascii(initial_topo_file_name, name='topographic__elevation', halo=1) igrid.set_watershed_boundary_condition_outlet_id(inputs['outlet_id'], iz, nodata_value=-9999) ifa = FlowAccumulator(igrid, flow_director='D8', depression_finder='DepressionFinderAndRouter') ifa.run_one_step()
def main(): """ In this simple tutorial example, the main function does all the work: it sets the parameter values, creates and initializes a grid, sets up the state variables, runs the main loop, and cleans up. """ # INITIALIZE # User-defined parameter values dem_name = 'ExampleDEM/west_bijou_gully.asc' outlet_row = 6 outlet_column = 38 next_to_outlet_row = 7 next_to_outlet_column = 38 n = 0.06 # roughness coefficient (Manning's n) h_init = 0.001 # initial thin layer of water (m) g = 9.8 # gravitational acceleration (m/s2) alpha = 0.2 # time-step factor (ND; from Bates et al., 2010) run_time = 2400 # duration of run, seconds rainfall_mmhr = 100 # rainfall rate, in mm/hr rain_duration = 15 * 60 # rainfall duration, in seconds # Derived parameters rainfall_rate = (rainfall_mmhr / 1000.) / 3600. # rainfall in m/s ten_thirds = 10. / 3. # pre-calculate 10/3 for speed elapsed_time = 0.0 # total time in simulation report_interval = 5. # interval to report progress (seconds) next_report = time.time() + report_interval # next time to report progress DATA_FILE = os.path.join(os.path.dirname(__file__), dem_name) # Create and initialize a raster model grid by reading a DEM print('Reading data from "' + str(DATA_FILE) + '"') (mg, z) = read_esri_ascii(DATA_FILE) print('DEM has ' + str(mg.number_of_node_rows) + ' rows, ' + str(mg.number_of_node_columns) + ' columns, and cell size ' + str(mg.dx)) + ' m' # Modify the grid DEM to set all nodata nodes to inactive boundaries mg.set_nodata_nodes_to_closed(z, 0) # set nodata nodes to inactive bounds # Set the open boundary (outlet) cell. We want to remember the ID of the # outlet node and the ID of the interior node adjacent to it. We'll make # the outlet node an open boundary. outlet_node = mg.grid_coords_to_node_id(outlet_row, outlet_column) node_next_to_outlet = mg.grid_coords_to_node_id(next_to_outlet_row, next_to_outlet_column) mg.set_fixed_value_boundaries(outlet_node) # Set up state variables h = mg.add_zeros('node', 'Water_depth') + h_init # water depth (m) q = mg.create_active_link_array_zeros() # unit discharge (m2/s) # Get a list of the core nodes core_nodes = mg.core_nodes # To track discharge at the outlet through time, we create initially empty # lists for time and outlet discharge. q_outlet = [] t = [] q_outlet.append(0.) t.append(0.) outlet_link = mg.active_link_connecting_node_pair(outlet_node, node_next_to_outlet) # Display a message print('Running ...') start_time = time.time() # RUN # Main loop while elapsed_time < run_time: # Report progress if time.time() >= next_report: print('Time = ' + str(elapsed_time) + ' (' + str(100. * elapsed_time / run_time) + '%)') next_report += report_interval # Calculate time-step size for this iteration (Bates et al., eq 14) dtmax = alpha * mg.dx / np.sqrt(g * np.amax(h)) # Calculate the effective flow depth at active links. Bates et al. 2010 # recommend using the difference between the highest water-surface # and the highest bed elevation between each pair of cells. zmax = mg.max_of_link_end_node_values(z) w = h + z # water-surface height wmax = mg.max_of_link_end_node_values(w) hflow = wmax - zmax # Calculate water-surface slopes water_surface_slope = mg.calculate_gradients_at_active_links(w) # Calculate the unit discharges (Bates et al., eq 11) q = (q-g*hflow*dtmax*water_surface_slope)/ \ (1.+g*hflow*dtmax*n*n*abs(q)/(hflow**ten_thirds)) # Calculate water-flux divergence at nodes dqds = mg.calculate_flux_divergence_at_nodes(q) # Update rainfall rate if elapsed_time > rain_duration: rainfall_rate = 0. # Calculate rate of change of water depth dhdt = rainfall_rate - dqds # Second time-step limiter (experimental): make sure you don't allow # water-depth to go negative if np.amin(dhdt) < 0.: shallowing_locations = np.where(dhdt < 0.) time_to_drain = -h[shallowing_locations] / dhdt[ shallowing_locations] dtmax2 = alpha * np.amin(time_to_drain) dt = np.min([dtmax, dtmax2]) else: dt = dtmax # Update the water-depth field h[core_nodes] = h[core_nodes] + dhdt[core_nodes] * dt h[outlet_node] = h[node_next_to_outlet] # Update current time elapsed_time += dt # Remember discharge and time t.append(elapsed_time) q_outlet.append(abs(q[outlet_link])) # FINALIZE # Set the elevations of the nodata cells to the minimum active cell # elevation (convenient for plotting) z[np.where(z <= 0.)] = 9999 # temporarily change their elevs ... zmin = np.amin(z) # ... so we can find the minimum ... z[np.where(z == 9999)] = zmin # ... and assign them this value. # Get a 2D array version of the water depths and elevations # Clear previous plots pylab.figure(1) pylab.close() pylab.figure(2) pylab.close() # Plot discharge vs. time pylab.figure(1) pylab.plot(np.array(t), np.array(q_outlet) * mg.dx) pylab.xlabel('Time (s)') pylab.ylabel('Q (m3/s)') pylab.title('Outlet discharge') # Plot topography pylab.figure(2) pylab.subplot(121) imshow_grid(mg, z, allow_colorbar=False) pylab.xlabel(None) pylab.ylabel(None) im = pylab.set_cmap('RdBu') cb = pylab.colorbar(im) cb.set_label('Elevation (m)', fontsize=12) pylab.title('Topography') # Plot water depth pylab.subplot(122) imshow_grid(mg, h, allow_colorbar=False) im2 = pylab.set_cmap('RdBu') pylab.clim(0, 0.25) cb = pylab.colorbar(im2) cb.set_label('Water depth (m)', fontsize=12) pylab.title('Water depth') # ## Display the plots pylab.show() print('Done.') print('Total run time = ' + str(time.time() - start_time) + ' seconds.')
from matplotlib import pyplot as plt ## Make a grid that is 100 by 100 with dx=dy=100. m rmg1 = RasterModelGrid((100, 100), 100.) ## Add elevation field to the grid. z1 = rmg1.add_ones('node', 'topographic__elevation') ## Instantiate process components ld1 = LinearDiffuser(rmg1, linear_diffusivity=0.1) fr1 = FlowRouter(rmg1, method='D8') fse1 = FastscapeEroder(rmg1, K_sp=1e-5, m_sp=0.5, n_sp=1.) ## Set some variables rock_up_rate = 1e-3 #m/yr dt = 1000 # yr rock_up_len = dt * rock_up_rate # m ## Time loop where evolution happens for i in range(500): z1[rmg1.core_nodes] += rock_up_len #uplift only the core nodes ld1.run_one_step(dt) #linear diffusion happens. fr1.run_one_step() #flow routing happens, time step not needed fse1.run_one_step(dt) #fluvial incision happens ## optional print statement print('i', i) ## Plotting the topography plt.figure(1) imshow_grid(rmg1, 'topographic__elevation') #need to run for about 4000 time steps, or 4,000,000 years to reach SS
def test_cython_functions(): # %% test d8 flow dir with open boundaries mg = RasterModelGrid((4, 4), xy_spacing=(1, 1)) z = mg.add_zeros("topographic__elevation", at="node") z[5:7] = [1, 3] z[9:11] = [3, 4] from landlab.plot import imshow_grid imshow_grid(mg, "topographic__elevation") activeCells = np.array(mg.status_at_node != NodeStatus.CLOSED + 0, dtype=int) receivers = np.array(mg.status_at_node, dtype=int) distance_receiver = np.zeros((receivers.shape), dtype=float) cores = mg.core_nodes activeCores = cores[activeCells[cores] == 1] # Make boundaries to save time with conditionals in c loops receivers[np.nonzero(mg.status_at_node)] = -1 steepest_slope = np.zeros((receivers.shape), dtype=float) el_dep_free = z el_ori = mg.at_node["topographic__elevation"] dist = (np.array( [1, np.sqrt(2), 1, np.sqrt(2), 1, np.sqrt(2), 1, np.sqrt(2)]) * mg.dx) ngb = np.zeros((8, ), dtype=int) el_d = np.zeros((8, ), dtype=float) # Links adj_link = np.array(mg.d8s_at_node, dtype=int) recvr_link = np.zeros((receivers.shape), dtype=int) - 1 _D8_flowDir( receivers, distance_receiver, steepest_slope, np.array(el_dep_free), el_ori, dist, ngb, activeCores, activeCells, el_d, mg.number_of_node_columns, mg.dx, adj_link, recvr_link, ) # We know where the water will flow using the D8 steepest descent algo # Also consider that under equal slopes, the flow will follow Landlab's rotational ordering going first to cardial, then to diagonal cells known_rec = np.array( [-1, -1, -1, -1, -1, 4, 7, -1, -1, 13, 11, -1, -1, -1, -1, -1]) testing.assert_array_equal( known_rec, receivers, err_msg="Error with D8 flow routing calculations", verbose=True, ) # %% test flow acc with open boundaries node_cell_area = np.array(mg.cell_area_at_node) node_cell_area[mg.closed_boundary_nodes] = 0.0 dis = np.full(mg.number_of_nodes, node_cell_area) da = np.array(node_cell_area) sort = np.argsort(el_dep_free) stack_flip = np.flip(sort) # Filter out donors giving to receivers being -1 stack_flip = np.array(stack_flip[receivers[stack_flip] != -1], dtype=int) _D8_FlowAcc(da, dis, stack_flip, receivers) # We know how much water will accumualte given the calculated flow dir (see before) known_FA = np.array([ 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0 ]) testing.assert_array_equal( known_FA, da, err_msg="Error with D8_FlowAcc calculations", verbose=True, ) # %% test d8 flow dir with closed boundaries mg = RasterModelGrid((4, 4), xy_spacing=(1, 1)) z = mg.add_zeros("topographic__elevation", at="node") # Close all model boundary edges mg.set_closed_boundaries_at_grid_edges( bottom_is_closed=True, left_is_closed=True, right_is_closed=True, top_is_closed=True, ) # Set lower-left (southwest) corner as an open boundary mg.set_watershed_boundary_condition_outlet_id( 0, mg["node"]["topographic__elevation"], -9999.0) z[5:7] = [1, 3] z[9:11] = [3, 4] activeCells = np.array(mg.status_at_node != NodeStatus.CLOSED + 0, dtype=int) receivers = np.array(mg.status_at_node, dtype=int) distance_receiver = np.zeros((receivers.shape), dtype=float) cores = mg.core_nodes activeCores = cores[activeCells[cores] == 1] # Make boundaries to save time with conditionals in c loops receivers[np.nonzero(mg.status_at_node)] = -1 steepest_slope = np.zeros((receivers.shape), dtype=float) el_dep_free = z el_ori = mg.at_node["topographic__elevation"] dist = (np.array( [1, np.sqrt(2), 1, np.sqrt(2), 1, np.sqrt(2), 1, np.sqrt(2)]) * mg.dx) ngb = np.zeros((8, ), dtype=int) el_d = np.zeros((8, ), dtype=float) # Links adj_link = np.array(mg.d8s_at_node, dtype=int) recvr_link = np.zeros((receivers.shape), dtype=int) - 1 _D8_flowDir( receivers, distance_receiver, steepest_slope, np.array(el_dep_free), el_ori, dist, ngb, activeCores, activeCells, el_d, mg.number_of_node_columns, mg.dx, adj_link, recvr_link, ) # We know where the water will flow using the D8 steepest descent algo # Also consider that under equal slopes, the flow will follow Landlab's rotational ordering going first to cardial, then to diagonal cells known_rec = np.array( [-1, -1, -1, -1, -1, 0, 5, -1, -1, 5, 5, -1, -1, -1, -1, -1]) testing.assert_array_equal( known_rec, receivers, err_msg="Error with D8 flow routing calculations", verbose=True, ) # %% test flow acc with closed boundaries node_cell_area = np.array(mg.cell_area_at_node) node_cell_area[mg.closed_boundary_nodes] = 0.0 dis = np.full(mg.number_of_nodes, node_cell_area) da = np.array(node_cell_area) sort = np.argsort(el_dep_free) stack_flip = np.flip(sort) # Filter out donors giving to receivers being -1 stack_flip = np.array(stack_flip[receivers[stack_flip] != -1], dtype=int) _D8_FlowAcc(da, dis, stack_flip, receivers) # We know how much water will accumualte given the calculated flow dir (see before) known_FA = np.array([ 4.0, 0.0, 0.0, 0.0, 0.0, 4.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]) testing.assert_array_equal( known_FA, da, err_msg="Error with D8_FlowAcc calculations", verbose=True, )
##of.flow_at_one_node(rg, z, study_node) ##of.update_at_one_point(rg, rainfall_duration=900, model_duration=900,rainfall_intensity=0.0000193333) ##of.update_at_one_point(rg, rainfall_duration=480, model_duration=480,rainfall_intensity=0.0000183333) # Once run, we can plot the output ##of.plot_at_one_node() # Now the flow_across_grid() method will be discussed. The commands needed to # run this method are triple-commented ('###') for convenience. All flow_at_one_node() # methods calls *should* be commented out to run this driver quicker. # Again, this function reads in data using the ModelParameterDictionary and the default # input file. The only required arguments for this method are the RasterModelGrid instance # and the the initial elevations. # This is the standard call to the flow_across_grid() method of.flow_across_grid(rg,z) of.update_across_grid(rg, rainfall_duration=900, model_duration=900,rainfall_intensity=0.0000193333) of.update_across_grid(rg, rainfall_duration=480, model_duration=900,rainfall_intensity=0.0000183333) plt.figure('Total Erosion, m') imshow_grid(rg, of.total_dzdt, show=True) endtime = time.time() print(endtime - start_time, "seconds")
def main(): """ In this simple tutorial example, the main function does all the work: it sets the parameter values, creates and initializes a grid, sets up the state variables, runs the main loop, and cleans up. """ # INITIALIZE # User-defined parameter values dem_name = 'ExampleDEM/west_bijou_gully.asc' outlet_row = 6 outlet_column = 38 next_to_outlet_row = 7 next_to_outlet_column = 38 n = 0.06 # roughness coefficient (Manning's n) h_init = 0.001 # initial thin layer of water (m) g = 9.8 # gravitational acceleration (m/s2) alpha = 0.2 # time-step factor (ND; from Bates et al., 2010) run_time = 2400 # duration of run, seconds rainfall_mmhr = 100 # rainfall rate, in mm/hr rain_duration = 15*60 # rainfall duration, in seconds # Derived parameters rainfall_rate = (rainfall_mmhr/1000.)/3600. # rainfall in m/s ten_thirds = 10./3. # pre-calculate 10/3 for speed elapsed_time = 0.0 # total time in simulation report_interval = 5. # interval to report progress (seconds) next_report = time.time()+report_interval # next time to report progress DATA_FILE = os.path.join(os.path.dirname(__file__), dem_name) # Create and initialize a raster model grid by reading a DEM print('Reading data from "'+str(DATA_FILE)+'"') (mg, z) = read_esri_ascii(DATA_FILE) print('DEM has ' + str(mg.number_of_node_rows) + ' rows, ' + str(mg.number_of_node_columns) + ' columns, and cell size ' + str(mg.dx)) + ' m' # Modify the grid DEM to set all nodata nodes to inactive boundaries mg.set_nodata_nodes_to_closed(z, 0) # set nodata nodes to inactive bounds # Set the open boundary (outlet) cell. We want to remember the ID of the # outlet node and the ID of the interior node adjacent to it. We'll make # the outlet node an open boundary. outlet_node = mg.grid_coords_to_node_id(outlet_row, outlet_column) node_next_to_outlet = mg.grid_coords_to_node_id(next_to_outlet_row, next_to_outlet_column) mg.set_fixed_value_boundaries(outlet_node) # Set up state variables h = mg.add_zeros('node', 'Water_depth') + h_init # water depth (m) q = mg.create_active_link_array_zeros() # unit discharge (m2/s) # Get a list of the core nodes core_nodes = mg.core_nodes # To track discharge at the outlet through time, we create initially empty # lists for time and outlet discharge. q_outlet = [] t = [] q_outlet.append(0.) t.append(0.) outlet_link = mg.active_link_connecting_node_pair(outlet_node, node_next_to_outlet) # Display a message print( 'Running ...' ) start_time = time.time() # RUN # Main loop while elapsed_time < run_time: # Report progress if time.time()>=next_report: print('Time = '+str(elapsed_time)+' (' +str(100.*elapsed_time/run_time)+'%)') next_report += report_interval # Calculate time-step size for this iteration (Bates et al., eq 14) dtmax = alpha*mg.dx/np.sqrt(g*np.amax(h)) # Calculate the effective flow depth at active links. Bates et al. 2010 # recommend using the difference between the highest water-surface # and the highest bed elevation between each pair of cells. zmax = mg.max_of_link_end_node_values(z) w = h+z # water-surface height wmax = mg.max_of_link_end_node_values(w) hflow = wmax - zmax # Calculate water-surface slopes water_surface_slope = mg.calculate_gradients_at_active_links(w) # Calculate the unit discharges (Bates et al., eq 11) q = (q-g*hflow*dtmax*water_surface_slope)/ \ (1.+g*hflow*dtmax*n*n*abs(q)/(hflow**ten_thirds)) # Calculate water-flux divergence at nodes dqds = mg.calculate_flux_divergence_at_nodes(q) # Update rainfall rate if elapsed_time > rain_duration: rainfall_rate = 0. # Calculate rate of change of water depth dhdt = rainfall_rate-dqds # Second time-step limiter (experimental): make sure you don't allow # water-depth to go negative if np.amin(dhdt) < 0.: shallowing_locations = np.where(dhdt<0.) time_to_drain = -h[shallowing_locations]/dhdt[shallowing_locations] dtmax2 = alpha*np.amin(time_to_drain) dt = np.min([dtmax, dtmax2]) else: dt = dtmax # Update the water-depth field h[core_nodes] = h[core_nodes] + dhdt[core_nodes]*dt h[outlet_node] = h[node_next_to_outlet] # Update current time elapsed_time += dt # Remember discharge and time t.append(elapsed_time) q_outlet.append(abs(q[outlet_link])) # FINALIZE # Set the elevations of the nodata cells to the minimum active cell # elevation (convenient for plotting) z[np.where(z<=0.)] = 9999 # temporarily change their elevs ... zmin = np.amin(z) # ... so we can find the minimum ... z[np.where(z==9999)] = zmin # ... and assign them this value. # Get a 2D array version of the water depths and elevations # Clear previous plots pylab.figure(1) pylab.close() pylab.figure(2) pylab.close() # Plot discharge vs. time pylab.figure(1) pylab.plot(np.array(t), np.array(q_outlet)*mg.dx) pylab.xlabel('Time (s)') pylab.ylabel('Q (m3/s)') pylab.title('Outlet discharge') # Plot topography pylab.figure(2) pylab.subplot(121) imshow_grid(mg, z, allow_colorbar=False) pylab.xlabel(None) pylab.ylabel(None) im = pylab.set_cmap('RdBu') cb = pylab.colorbar(im) cb.set_label('Elevation (m)', fontsize=12) pylab.title('Topography') # Plot water depth pylab.subplot(122) imshow_grid(mg, h, allow_colorbar=False) im2 = pylab.set_cmap('RdBu') pylab.clim(0, 0.25) cb = pylab.colorbar(im2) cb.set_label('Water depth (m)', fontsize=12) pylab.title('Water depth') # ## Display the plots pylab.show() print('Done.') print('Total run time = '+str(time.time()-start_time)+' seconds.')
# instantiate the Lithology component lith = Lithology(rmg, thickness, [1, 2], attrs) # put in the damage zone a third of the way in the model spatially_variable_rock_id = rmg.ones('node') # Comment/Uncomment below to introduce a damage zone kdc! spatially_variable_rock_id[(rmg.y_of_node > 2 * ymax / 5) & (rmg.y_of_node < 3 * ymax / 5)] = 2 # grow the topography up (this is clearly dumb) z += 1. dz_ad = 0. lith.run_one_step(dz_advection=dz_ad, rock_id=spatially_variable_rock_id) imshow_grid(rmg, 'rock_type__id', cmap='viridis', vmin=0, vmax=3) # since we will not update z after this, the erodability parameters of the rock should not change # ...at least that is the idea ################################################################################ ## Third, we now set parameters to control and build our landscape ############ ################################################################################ # Erosion variables # #K = 0.08 # value for the "erodability" of the landscape bedrock [kyr^-1] m = 0.5 # exponent on drainage area [non dimensional] n = 1 # exponent on river slope [non dimensional] #D = 0.02 # Hillslope linear diffusivity [meters sqared per kiloyear] # Tectonic variables #
im = curax.plot(ycoord_rast[1:-1, int(ncols // 2)], elev_rast[1:-1, int(ncols // 2)], color=ucolr[j]) curax.set_xlabel('distance, km', fontsize='small') curax.set_ylabel('profile elev, km', fontsize='small') curax.set_title('d') curax.set_ylim(-0.005, 0.065) j = j + 1 plt.sca(ax2) cm = "jet" im = imshow_grid(mg, 'topographic__elevation', grid_units=['km', 'km'], var_name='Elevation (km)', cmap=cm, vmin=0, vmax=0.06) ax2.axhline(y=1, lw=0.5, color='k', ls=':', label='profile c') ax2.axvline(x=1, lw=0.5, color='k', ls='--', label='profile d') ax2.set_title('b') ax2.legend() fig.tight_layout() """ ------------------------------------------------ FIGURE 2 ------------------------------------------------ """
def reset(self): """ Reset function. Resets the world to its initial state. """ super(FloodWorld, self).reset() # Terrain generation shape = (self.grid_size,) * 2 size = self.grid_size * self.grid_size # Set initial simple topography z = self.vertical_scale * self.simple_topography(shape) # Create raster model if it does not exist if self.mg is None: self.mg = RasterModelGrid(shape, int(round(self.world_size/self.grid_size))) self.mg.set_closed_boundaries_at_grid_edges(True, True, True, True) self.z = self.mg.add_field('node', 'topographic__elevation', z) self.swd = self.mg.add_zeros('node', 'surface_water__depth') else: self.mg.at_node['topographic__elevation'] = z self.swd[:] = np.zeros(size) import matplotlib.pyplot as plt plt.figure() from landlab.plot import imshow_grid imshow_grid(self.mg, 'topographic__elevation', colorbar_label='m') plt.draw() # Set evolution parameters uplift_rate = self.inputs['uplift_rate'] total_t = self.inputs['total_time'] dt = self.inputs['dt'] nt = int(total_t // dt) # Loops uplift_per_step = uplift_rate * dt self.fr = FlowAccumulator(self.mg, **self.inputs) self.sp = FastscapeEroder(self.mg, **self.inputs) # Erode terrain for i in range(nt): self.fr.run_one_step() # Not time sensitive self.sp.run_one_step(dt) self.mg.at_node['topographic__elevation'][self.mg.core_nodes] += uplift_per_step # add the uplift if i % 10 == 0: print('Erode: Completed loop %d' % i) plt.figure() imshow_grid(self.mg, 'topographic__elevation', colorbar_label='m') plt.draw() plt.show() # Setup surface water flow self.of = OverlandFlow(self.mg, steep_slopes=True, mannings_n=0.01) # Setup initial flood self.swd[[5050, 5051, 5150, 5151]] += self.h_init self.active = np.greater(np.flip(np.reshape(self.swd, shape), axis=0), self.flood_threshold)
# # * Make a plot to see the initial topography. mg = RasterModelGrid((200, 150), 50.) # The grid is 200 rows by 100 columns, with dx = dy = 50 m. for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge): mg.status_at_node[edge] = CLOSED_BOUNDARY for edge in (mg.nodes_at_top_edge, mg.nodes_at_bottom_edge): mg.status_at_node[edge] = FIXED_VALUE_BOUNDARY z = mg.add_zeros('node', 'topographic__elevation') initial_roughness = np.random.rand(mg.core_nodes.size) / 100000. mg.at_node['topographic__elevation'][mg.core_nodes] += initial_roughness imshow_grid(mg, z, grid_units=['m', 'm'], var_name='Elevation (m)') # ### Intitalize time and uplift for the model run. # # * Note that units are not imposed by many of the Landlab components, and the # grid has no assumed units. # * In our case, with the `FastscapeEroder`, we just need to enter values with # consistent units. # * For example, the grid was made with an assumed dx in meters. Time values # are in years. So the erodibility coefficient in the `FastscapeEroder` should # have units of meters and years. total_t = 300000. # years dt = 5000 # years nt = int(total_t // dt) # number of time steps
fig=plt.figure(figsize=(8,6)) fig.suptitle('Kd='+str(lin_dif)+' Ks='+str(K_sp)+' U='+str(uplift_rate)+'\n\n') ax1=fig.add_subplot(221) ax2=fig.add_subplot(222,sharex=ax1,sharey=ax1) ax3=fig.add_subplot(223,sharex=ax1,sharey=ax1) ax4=fig.add_subplot(224) ax=[ax1,ax2,ax3] params=['topographic__elevation','topographic__steepest_slope', 'drainage_area'] pmin=[None,None,None] pmax=[None,None,None] cm='jet' for p in range(len(params)): plt.sca(ax[p]) im = imshow_grid(mg, params[p], grid_units = ['km','km'],cmap=cm,vmin=pmin[p], vmax=pmax[p]) gradient=mg.at_node['topographic__steepest_slope'] DA=mg.at_node['drainage_area'] ax4.loglog(DA,gradient,'r',marker='x',mew=.5,lw=0) DAbins,slope_means=bin_slopeDA(gradient,DA) ax4.loglog(DAbins,slope_means,'ko') # #
x, y, z = gaussian_hill_elevation(n) z = z * 100 mg = RasterModelGrid((n, n), node_spacing) gh_org = mg.add_field('node', 'topographic__elevation', z, units='meters', copy=True, clobber=False) fg1 = pl.figure(1) imshow_grid(mg, 'topographic__elevation', plot_name='Gaissian Hill', allow_colorbar=True) fg2, ax = pl.subplots(2, 2) crosssection_center = mg.node_vector_to_raster( gh_org, flip_vertically=True)[:, np.int(np.round(n / 2))].copy() crosssection_center_ycoords = mg.node_vector_to_raster( mg.node_y, flip_vertically=True)[:, np.int(np.round(n / 2))].copy() ax[0, 0].plot(crosssection_center_ycoords, crosssection_center, 'k', linewidth=3, label='Org. Gaussian Hill') ax[0, 0].grid() ax[0, 0].set_xlabel('Distance along profile [m]', fontsize=12) ax[0, 0].set_ylabel('Height [m]', fontsize=12)
#%% Create an uplifted block in the center of model domain #Create a raster grid with 100 rows, 100 columns, and cell spacing of 1 m n = 100 mg = RasterModelGrid((n, n), 1.0) z = mg.add_zeros('node', 'topographic__elevation') mg.set_closed_boundaries_at_grid_edges(right_is_closed=False, top_is_closed=False, \ left_is_closed=False, bottom_is_closed=False) #Create a diagonal fault across the grid blockuplift_nodes = np.where((mg.node_y < 55) & (mg.node_y > 45) & (mg.node_x < 55) & (mg.node_x > 45)) z[blockuplift_nodes] += 10.0 # View the initial grid figure() imshow_grid(mg, 'topographic__elevation', cmap='viridis', grid_units=['m', 'm']) show() linear_diffusivity = 0.01 #in m2 per year ld = LinearDiffuser(grid=mg, linear_diffusivity=linear_diffusivity) dt = 100. #Evolve landscape for i in range(25): ld.run_one_step(dt) #Plot new landscape figure() imshow_grid(mg,
##of.update_at_one_point(rg, rainfall_duration=480, model_duration=480,rainfall_intensity=0.0000183333) # Once run, we can plot the output ##of.plot_at_one_node() # Now the flow_across_grid() method will be discussed. The commands needed to # run this method are triple-commented ('###') for convenience. All flow_at_one_node() # methods calls *should* be commented out to run this driver quicker. # Again, this function reads in data using the ModelParameterDictionary and the default # input file. The only required arguments for this method are the RasterModelGrid instance # and the the initial elevations. # This is the standard call to the flow_across_grid() method of.flow_across_grid(rg, z) of.update_across_grid(rg, rainfall_duration=900, model_duration=900, rainfall_intensity=0.0000193333) of.update_across_grid(rg, rainfall_duration=480, model_duration=900, rainfall_intensity=0.0000183333) plt.figure('Total Erosion, m') imshow_grid(rg, of.total_dzdt, show=True) endtime = time.time() print endtime - start_time, "seconds"
# Let’s being importing python libraries, Landlab components, and python plotting tools import numpy as np from landlab.components import Radiation from landlab.components import PotentialEvapotranspiration from landlab.io import read_esri_ascii from landlab.plot import imshow_grid get_ipython().magic(u'matplotlib inline') from landlab.plot.imshow import imshow_grid_at_cell import matplotlib.pyplot as plt plt.show() # Read an existing esri grid as watershed and map the elevation field (watershed, z) = read_esri_ascii('DEM_10m.asc', name='topographic__elevation') imshow_grid(watershed, 'topographic__elevation') plt.show() # Constructions of Landlab Radiation and Potential Evapotranspiration components and codes can be found in the respective links below. # http://landlab.readthedocs.io/en/latest/landlab.components.radiation.html and # http://landlab.readthedocs.io/en/latest/landlab.components.pet.html # The radation components return relative radiation (ratio of radiation of a slopes surface to flat surface), used to scale PET calculated for flat surface by the PET component. # # Let's instantiate the radiation and PET components using only variables relevant to this exercise. rad = Radiation(watershed, method='Grid', latitude=34.) PET = PotentialEvapotranspiration( watershed, method='PriestleyTaylor', albedo=0.2, latitude=34.,
three_over_seven ) # water depth at left side (m) # And now we add it to the second column, in all rows that are not boundary rows. h[(leftside)[1 : len(leftside) - 1]] = h_boundary # Print and update current time print elapsed_time elapsed_time += dtmax # FINALIZE # Plot the water depth values across the grid at the end of the run plt.figure(1) imshow_grid(mg, h, show=True) # Compare the wave front to the analytical solution # First, we will get an array of the distance x = np.arange(0, ((numcols) * dx), dx) # Now we will solve the analytical solution h_analytical = -seven_over_three * n * n * u * u * (x - (u * 9000)) # We can only solve the analytical solution where water depth is positive... so we weed out negative # values to avoid NaN errors. h_analytical[np.where(h_analytical > 0)] = h_analytical[np.where(h_analytical > 0)] ** three_over_seven h_analytical[np.where(h_analytical < 0)] = 0.0 # And we will reshape our depth array we solved for in the above loop to access one row for plotting. # We will also remove the first (boundary) cell from this array, while also appending a [0] value at the
) * 100 years = range(0, yrs) pic = 0 plt.figure(pic) plt.plot(years, grass_cov, "-g", label="Grass") plt.hold(True) plt.plot(years, shrub_cov, "-r", label="Shrub") plt.hold(True) plt.plot(years, tree_cov, "-k", label="Tree") plt.ylabel(" % Coverage ") plt.xlabel("Time in years") plt.legend(loc=0) ## Plotting cmap = mpl.colors.ListedColormap(["green", "red", "black", "white", "red", "black"]) bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) ## Plot images to make gif. for year in range(0, yrs, 10): filename = "Year = " + "%05d" % year pic += 1 plt.figure(pic) imshow_grid(grid, VegType[year], values_at="cell", cmap=cmap, norm=norm, limits=[0, 5]) plt.title(filename) plt.savefig(filename) plt.show()
print(file) time = file.split(os.path.sep)[-1].split('_')[-1].split('.')[0] ds = xr.open_dataset(file, engine='netcdf4') mg.set_nodata_nodes_to_closed( ds.expected_topographic__elevation.values.flatten(), -9999) basic_fig_name = os.path.join(out_folder, set_key + '_' + time) # expected topography fig, ax = plt.subplots(figsize=fs, dpi=300) imshow_grid(mg, ds.expected_topographic__elevation.values.flatten(), vmin=1130, vmax=1940, cmap='viridis', plot_name='Expected Elevation at +' + time + ' yr [ft]') plt.axis('off') line_segments = LineCollection(segments, colors='k', linewidth=0.1) ax.add_collection(line_segments) plt.text(text_x, text_y, plot_text[set_key], color='w') plt.savefig(basic_fig_name + '_expected_topography.png') # expected erosion fig, ax = plt.subplots(figsize=fs, dpi=300) imshow_grid(mg, ds.expected_cumulative_erosion__depth.values.flatten(), vmin=-ero_lim, vmax=ero_lim, cmap=ero_col,
init_topo = ((200 - rmg.node_x) * 0.03) + 100. + np.random.normal(0, 0.005, 2500) # Create field for terrace wall locations terrWallLoc = np.zeros(2500) # Add terraces every 5 meters and save wall locations to field for i in range(5, 90, 5): terr_loc = np.where((rmg.node_x) <= i) init_topo[terr_loc] += 2.0 # add terrace wall location to field terrwallloc = np.where((rmg.node_x) == i) terrWallLoc[terrwallloc] += 1. # Add initial topography to raster model grid for later plotting rmg.add_field('node', 'initial_topographic__elevation', init_topo, noclobber=True) imshow_grid(rmg, 'initial_topographic__elevation') # Create separate elevation data so initial topography is not overwritten z = copy.deepcopy(init_topo) # Add elevation for topography to raster model grid rmg.add_field('node', 'topographic__elevation', z, noclobber=False) # Add terrace wall location field to rmg rmg.add_field('node', 'terrace_wall__location', terrWallLoc) # Set the boundary conditions: all NODATA nodes in the DEM are closed # boundaries, and the outlet is set to an open boundary. rmg.set_watershed_boundary_condition(z) # Set spatially variable diffusivity for soil creep