def go(self): """ Runs the model. """ # RUN while self.current_time < self.run_duration: # Once in a while, print out simulation and real time to let the user # know that the sim is running ok current_real_time = time.time() if current_real_time >= self.next_report: print('Current sim time',self.current_time,'(',100*self.current_time/self.run_duration,'%)') self.next_report = current_real_time + self.report_interval # Run the model forward in time until the next output step self.run(self.current_time+self.plot_interval, self.node_state, plot_each_transition=False) self.current_time += self.plot_interval self.synchronize_bleaching(self.current_time) if self.plot_interval <= self.run_duration: # Plot the current grid self.ca_plotter.update_plot() # Display the OSL content of grains figure(3) clf() self.osl_display[:] = self.osl[self.propid]+self.node_state imshow_node_grid(self.grid, 'osl_display', limits=(0.0, 2.0), cmap='coolwarm') show() figure(1)
def do_display_output(self): # ok, here one problem is that we don't know what grid type we have if type(self.grid) is RasterModelGrid: print 'This is a raster grid' else: print 'non-raster grid' imshow_node_grid(self.grid, self.diffusion_component.z)
def show_possible_nodes(self): """ Once the subsets by aspect and slope have been set, call this function to see both the whole elevation map, and the subset of nodes that will be searched. """ possible_core_nodes = np.logical_and(self.steep_nodes, self.aspect_close_nodes) figure(1) gridshow.imshow_node_grid(self.grid, self.elevs) figure(2) gridshow.imshow_core_node_grid(self.grid, self.slopes) figure(3) gridshow.imshow_core_node_grid(self.grid, self.aspect) figure(4) gridshow.imshow_core_node_grid(self.grid, possible_core_nodes) show()
print("Elapsed time: ", time_off - time_on) time_off = time.time() print("Elapsed time: ", time_off - time_on) # Finalize and plot elev = mg["node"]["topographic__elevation"] elev_r = mg.node_vector_to_raster(elev) # Clear previous plots pylab.figure(1) pylab.close() # Plot topography pylab.figure(1) im = imshow_node_grid(mg, "topographic__elevation") # display a colored image print(elev_r) pylab.figure(2) im = pylab.plot(dx * numpy.arange(nrows), elev_r[:, int(ncols // 2)]) # display a colored image pylab.title("Vertical cross section") # Plot topography # pylab.figure(1) # im = imshow_node_grid(mg, 'topographic_elevation') # display a colored image # print elev_r pylab.show() print("Done.")
def drainage_plot(mg, surface='topographic__elevation', receivers=None, proportions=None, surf_cmap='gray', quiver_cmap='viridis', title = 'Drainage Plot'): if isinstance(surface, six.string_types): colorbar_label = surface else: colorbar_label = 'topographic_elevation' imshow_node_grid(mg, surface, cmap=surf_cmap, colorbar_label=colorbar_label) if receivers is None: try: receivers = mg.at_node['flow__receiver_nodes'] if proportions is None: try: proportions = mg.at_node['flow__receiver_proportions'] except: pass except: receivers = np.reshape(mg.at_node['flow__receiver_node'],(mg.number_of_nodes,1)) nreceievers = int(receivers.size/receivers.shape[0]) propColor=plt.get_cmap(quiver_cmap) for j in range(nreceievers): rec = receivers[:,j] is_bad = rec == -1 xdist = -0.8*(mg.node_x-mg.node_x[rec]) ydist = -0.8*(mg.node_y-mg.node_y[rec]) if proportions is None: proportions = np.ones_like(receivers, dtype=float) is_bad[proportions[:,j]==0.]=True xdist[is_bad] = np.nan ydist[is_bad] = np.nan prop = proportions[:,j]*256. lu = np.floor(prop) colors = propColor(lu.astype(int)) shape = (mg.number_of_nodes, 1) plt.quiver(mg.node_x.reshape(shape), mg.node_y.reshape(shape), xdist.reshape(shape), ydist.reshape(shape), color=colors, angles='xy', scale_units='xy', scale=1, zorder=3) # Plot differen types of nodes: o, = plt.plot(mg.node_x[mg.status_at_node == CORE_NODE], mg.node_y[mg.status_at_node == CORE_NODE], 'b.', label='Core Nodes', zorder=4) fg, = plt.plot(mg.node_x[mg.status_at_node == FIXED_VALUE_BOUNDARY], mg.node_y[mg.status_at_node == FIXED_VALUE_BOUNDARY], 'c.', label='Fixed Gradient Nodes', zorder=5) fv, = plt.plot(mg.node_x[mg.status_at_node == FIXED_GRADIENT_BOUNDARY], mg.node_y[mg.status_at_node ==FIXED_GRADIENT_BOUNDARY], 'g.', label='Fixed Value Nodes', zorder=6) c, = plt.plot(mg.node_x[mg.status_at_node == CLOSED_BOUNDARY], mg.node_y[mg.status_at_node ==CLOSED_BOUNDARY], 'r.', label='Closed Nodes', zorder=7) node_id = np.arange(mg.number_of_nodes) flow_to_self = receivers[:,0]==node_id fts, = plt.plot(mg.node_x[flow_to_self], mg.node_y[flow_to_self], 'kx', markersize=6, label = 'Flows To Self', zorder=8) ax = plt.gca() ax.legend(labels = ['Core Nodes', 'Fixed Gradient Nodes', 'Fixed Value Nodes', 'Closed Nodes', 'Flows To Self'], handles = [o, fg, fv, c, fts], numpoints=1, loc='center left', bbox_to_anchor=(1.7, 0.5)) sm = plt.cm.ScalarMappable(cmap=propColor, norm=plt.Normalize(vmin=0, vmax=1)) sm._A = [] cx = plt.colorbar(sm) cx.set_label('Proportion of Flow') plt.title(title) plt.show()
# Modify the boundary conditions of an interior rectangle in the grid from landlab import RasterModelGrid, CLOSED_BOUNDARY import numpy as np from landlab.plot.imshow import imshow_node_grid from matplotlib.pyplot import show get_ipython().magic(u'matplotlib inline') mg = RasterModelGrid(10,10,1.) min_x = 2.5 max_x = 5. min_y = 3.5 max_y = 7.5 x_condition = np.logical_and(mg.node_x < max_x, mg.node_x > min_x) y_condition = np.logical_and(mg.node_y < max_y, mg.node_y > min_y) my_nodes = np.logical_and(x_condition, y_condition) mg.status_at_node[my_nodes] = CLOSED_BOUNDARY z = mg.add_zeros('node', 'topographic__elevation') imshow_node_grid(mg, z)
dx = 1000.0 close("all") mg = RasterModelGrid(nrows, ncols, dx) z = (3000.0 - mg.node_x) * 0.5 # z = -mg.node_x-mg.node_y # z = np.sqrt(mg.node_x**2 + mg.node_y**2) # z = mg.node_x + mg.node_y # val_to_replace_with = z.reshape((nrows,ncols))[3,3] # z.reshape((nrows,ncols))[2:5,:] = val_to_replace_with mg.at_node["topographic__elevation"] = z # mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True) mg.set_closed_boundaries_at_grid_edges(False, True, True, True) figure(3) imshow_node_grid(mg, mg.status_at_node) mg.at_node["water__unit_flux_in"] = np.ones_like(z) pfr = PotentialityFlowRouter(mg, "pot_fr_params.txt") pfr.route_flow(route_on_diagonals=True) figure(1) imshow_node_grid(mg, "water__discharge") figure(2) imshow_node_grid(mg, "topographic__elevation") out_sum = np.sum(mg.at_node["water__discharge"].reshape((nrows, ncols))[-3, :]) print(out_sum) print(np.sum(mg.at_node["water__unit_flux_in"]), np.sum(mg.at_node["water__discharge"][mg.boundary_nodes]))
dx = 1000. close('all') mg = RasterModelGrid(nrows, ncols, dx) z = (3000.-mg.node_x)*0.5 #z = -mg.node_x-mg.node_y #z = np.sqrt(mg.node_x**2 + mg.node_y**2) #z = mg.node_x + mg.node_y #val_to_replace_with = z.reshape((nrows,ncols))[3,3] #z.reshape((nrows,ncols))[2:5,:] = val_to_replace_with mg.at_node['topographic__elevation'] = z #mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True) mg.set_closed_boundaries_at_grid_edges(True, True, True, False) figure(3) imshow_node_grid(mg, mg.node_boundary_status) mg.at_node['water__volume_flux_in'] = np.ones_like(z) pfr = PotentialityFlowRouter(mg, 'pot_fr_params.txt') pfr.route_flow(route_on_diagonals=True) figure(1) imshow_node_grid(mg, 'water__volume_flux_magnitude') figure(2) imshow_node_grid(mg, 'topographic__elevation') out_sum = np.sum(mg.at_node['water__volume_flux_magnitude'].reshape((nrows,ncols))[-3,:]) print(out_sum) print(np.sum(mg.at_node['water__volume_flux_in']), np.sum(mg.at_node['water__volume_flux_magnitude'][mg.boundary_nodes]))
mg.at_node['topographic__elevation'][section_col] = mg.at_node['topographic__elevation'][inlet_node]+1. #now pull down hard on the BL: mg.at_node['topographic__elevation'][mg.nodes_at_top_edge[mg.number_of_node_columns // 2]] =- 10. pfr.route_flow(route_on_diagonals=True) kd = mg.at_node['surface_water__discharge'] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g = mg.calc_grad_of_active_link(mg.at_node['topographic__elevation']) mg.map_max_of_link_nodes_to_link('surface_water__discharge', out=mg.at_link[ 'surface_water__discharge']) # map_link_end_node_max_value_to_link(mg, 'surface_water__discharge') kd_link = 1.e6*mg.at_link['surface_water__discharge'][mg.active_links] qs = -kd_link*g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dqsdx mg.at_node['topographic__elevation'][interior_nodes] += dzdt[interior_nodes]*dt if i%50==0: print('loop '+str(i)) section_downfan.append(mg.node_vector_to_raster(mg.at_node['topographic__elevation'])[1:,section_col].copy()) figure(1) imshow_node_grid(mg, 'topographic__elevation') figure(2) imshow_node_grid(mg, mg.calc_hillshade_of_node(), cmap='bone') figure(3) imshow_node_grid(mg, 'surface_water__discharge', cmap='Blues_r') figure(4) for i in range(len(section_downfan)): plot(section_downfan[i], '-')
dists_upstr = prf.get_distances_upstream( mg, len(mg.at_node["topographic__steepest_slope"]), profile_IDs, mg.at_node["links_to_flow_receiver"] ) prf.plot_profiles(dists_upstr, profile_IDs, mg.at_node["topographic__elevation"]) print("Completed loop ", i) print("Completed the simulation. Plotting...") # Finalize and plot # Clear previous plots pylab.figure(1) pylab.close() pylab.figure(1) im = imshow_node_grid(mg, "water__volume_flux", cmap="PuBu") # display a colored image pylab.figure(2) im = imshow_node_grid(mg, "topographic__elevation") # display a colored image elev = mg["node"]["topographic__elevation"] elev_r = mg.node_vector_to_raster(elev) pylab.figure(3) im = pylab.plot(mg.dx * np.arange(nrows), elev_r[:, int(ncols // 2)]) pylab.title("N-S cross_section") pylab.figure(4) im = pylab.plot(mg.dx * np.arange(ncols), elev_r[int(nrows // 4), :]) pylab.title("E-W cross_section") drainage_areas = mg["node"]["drainage_area"][mg.get_interior_nodes()]
mg = RasterModelGrid(25, 40, 10.0) #Create a field of node data (an array) on the grid called elevation. #Initially populate this array with zero values. z = mg.add_zeros('node', 'elevation') #Check the size of the array len(z) #Create a diagonal fault across the grid fault_y = 50.0 + 0.25*mg.node_x upthrown_nodes = numpy.where(mg.node_y>fault_y) z[upthrown_nodes] += 10.0 + 0.01*mg.node_x[upthrown_nodes] #Illustrate the grid imshow_node_grid(mg, z, cmap='jet', grid_units=['m','m']) show() #Define paramaters kd = 0.01 # 0.01 m2 per year dt = 0.2*mg.dx*mg.dx/kd # CFL condition #Set boundary conditions mg.set_closed_boundaries_at_grid_edges(False, True, False, True) #Get id values of the cord nodes on which you will operate interior_nodes = mg.get_core_nodes() #Evolve landscape for i in range(25): g = mg.calculate_gradients_at_active_links(z)
# This line performs the actual functionality of the component: # ***NB: both diffusers contain an "automatic" element of uplift. # You can suppress this for the linear diffuser with the *internal_uplift* keyword, =False # See the docstrings for both classes for more details. # Switch these lines to switch between diffusion styles: # mg = diffuse.diffuse(mg, i*dt) #nonlinear diffusion lin_diffuse.diffuse(dt) # linear diffusion # Plot a Xsection north-south through the middle of the data, once per loop pylab.figure(1) elev_r = mg.node_vector_to_raster(mg["node"]["topographic__elevation"]) im = pylab.plot(mg.dx * np.arange(nrows), elev_r[:, int(ncols // 2)]) print("Completed loop ", i) print("Completed the simulation. Plotting...") # Finalize and plot: # put a title on figure 1 pylab.figure(1) pylab.title("N-S cross_section") pylab.xlabel("Distance") pylab.ylabel("Elevation") # figure 2 is the map of the final elevations pylab.figure(2) im = imshow_node_grid(mg, "topographic__elevation") pylab.show() # this line displays all of the figures you've issued plot commands for, since you last called show()
#add uplift mg.at_node['topographic__elevation'][mg.core_nodes] += 5.*uplift*interval_duration #Finalize and plot elev = mg['node']['topographic__elevation'] elev_r = mg.node_vector_to_raster(elev) # Clear previous plots pylab.figure("topo") pylab.close() # Plot topography pylab.figure("topo") #im = pylab.imshow(elev_r, cmap=pylab.cm.RdBu) # display a colored image im = llplot.imshow_node_grid(mg, 'topographic__elevation') #print elev_r #pylab.colorbar(im) #pylab.title('Topography') pylab.figure("Xsec") im = pylab.plot(dx*numpy.arange(nrows), elev_r[:,int(ncols//2)]) # display a colored image pylab.title('Vertical cross section') pylab.figure("Slope-Area") im = pylab.loglog(mg.at_node['drainage_area'], mg.at_node['topographic__steepest_slope'],'.') pylab.title('Slope-Area') pylab.show() print('Done.')
for i in range(2000): #mg.at_node['topographic__elevation'][inlet_node] = 1. #maintain flux like this now instead: mg.at_node['topographic__elevation'][section_col] = mg.at_node['topographic__elevation'][inlet_node]+1. pfr.route_flow(route_on_diagonals=True) #imshow(mg, 'water__volume_flux_magnitude') #show() kd = mg.at_node['water__volume_flux_magnitude'] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g = mg.calculate_gradients_at_active_links(mg.at_node['topographic__elevation']) map_link_end_node_max_value_to_link(mg, 'water__volume_flux_magnitude') kd_link = 1.e6*mg.at_link['water__volume_flux_magnitude'][mg.active_links] qs = -kd_link*g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dqsdx mg.at_node['topographic__elevation'][interior_nodes] += dzdt[interior_nodes]*dt if i%50==0: print('loop '+str(i)) section_downfan.append(mg.node_vector_to_raster(mg.at_node['topographic__elevation'])[1:,section_col].copy()) figure(1) imshow_node_grid(mg, 'topographic__elevation') figure(2) imshow_node_grid(mg, 'water__depth') figure(3) imshow_node_grid(mg, 'water__volume_flux_magnitude', cmap='Blues_r') figure(4) for i in range(len(section_downfan)): plot(section_downfan[i], '-')
mg.at_node['water__unit_flux_in'][inlet_node] = 1. pfr = PotentialityFlowRouter(mg, 'pot_fr_params.txt') interior_nodes = mg.core_nodes # do the loop for i in range(2000): if i%50==0: print('loop '+str(i)) mg.at_node['topographic__elevation'][inlet_node] = 1. pfr.route_flow(route_on_diagonals=True) #imshow(mg, 'water__discharge') #show() kd = mg.at_node['water__discharge'] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g = mg.calc_grad_of_active_link(mg.at_node['topographic__elevation']) map_link_end_node_max_value_to_link(mg, 'water__discharge') kd_link = 1.e6*mg.at_link['water__discharge'][mg.active_links] qs = -kd_link*g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dqsdx mg.at_node['topographic__elevation'][interior_nodes] += dzdt[interior_nodes]*dt figure(1) imshow_node_grid(mg, 'topographic__elevation') figure(2) imshow_node_grid(mg, 'water__depth') figure(3) imshow_node_grid(mg, 'water__discharge')
outlet_column = 38 # Read in a DEM and set its boundaries DATA_FILE = os.path.join(os.path.dirname(__file__), dem_name) (grid, z) = read_esri_ascii(DATA_FILE, name='topographic__elevation') grid.set_nodata_nodes_to_closed(z, 0.) # set nodata nodes to inactive bounds outlet_node = grid.grid_coords_to_node_id(outlet_row, outlet_column) # Route flow flow_router = FlowRouter(grid) flow_router.route_flow() # Create a shaded image pylab.close() # clear any pre-existing plot pylab.figure(1) im = imshow_node_grid(grid, 'water__volume_flux', cmap = pylab.cm.RdBu) # add a title and axis labels pylab.title('Discharge') pylab.xlabel('Distance (m)') pylab.ylabel('Distance (m)') pylab.figure(2) im = imshow_node_grid(grid, 'topographic__elevation') pylab.title('DEM') pylab.xlabel('Distance (m)') pylab.ylabel('Distance (m)') # Display the plot pylab.show()
prf.plot_profiles(dists_upstr, profile_IDs, mg.at_node[ 'topographic__elevation']) print('Completed loop ', i) print('Completed the simulation. Plotting...') time_off = time() #Finalize and plot # Clear previous plots pylab.figure(1) pylab.close() pylab.figure(1) # display a colored image imshow_node_grid(mg, 'water__volume_flux', cmap='Blues') pylab.figure(2) imshow_node_grid(mg, 'topographic__elevation') # display a colored image elev = mg['node']['topographic__elevation'] elev_r = mg.node_vector_to_raster(elev) pylab.figure(3) im = pylab.plot(mg.dx * np.arange(nrows), elev_r[:, int(ncols // 2)]) pylab.title('N-S cross_section') pylab.figure(4) im = pylab.plot(mg.dx * np.arange(ncols), elev_r[int(nrows // 4), :]) pylab.title('E-W cross_section') drainage_areas = mg['node']['drainage_area'][mg.core_nodes]
# mg.at_node['topographic__elevation'][inlet_node] = 1. # maintain flux like this now instead: mg.at_node["topographic__elevation"][section_col] = mg.at_node["topographic__elevation"][inlet_node] + 1.0 pfr.route_flow(route_on_diagonals=True) # imshow(mg, 'surface_water__discharge') # show() kd = mg.at_node["surface_water__discharge"] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g = mg.calc_grad_of_active_link(mg.at_node["topographic__elevation"]) mg.map_max_of_link_nodes_to_link("surface_water__discharge", out=mg.at_link["surface_water__discharge"]) # map_link_end_node_max_value_to_link(mg, 'surface_water__discharge') kd_link = 1.0e6 * mg.at_link["surface_water__discharge"][mg.active_links] qs = -kd_link * g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dqsdx mg.at_node["topographic__elevation"][interior_nodes] += dzdt[interior_nodes] * dt if i % 50 == 0: print("loop " + str(i)) section_downfan.append(mg.node_vector_to_raster(mg.at_node["topographic__elevation"])[1:, section_col].copy()) figure(1) imshow_node_grid(mg, "topographic__elevation") figure(2) imshow_node_grid(mg, mg.calc_hillshade_of_node(), cmap="bone") figure(3) imshow_node_grid(mg, "surface_water__discharge", cmap="Blues_r") figure(4) for i in range(len(section_downfan)): plot(section_downfan[i], "-")
y_distance_from_center = mg.node_y-mg.node_y.mean() x_distance_from_edge = np.amin(np.vstack((mg.node_x.max()-mg.node_x, mg.node_x-mg.node_x.min())), axis=0) y_distance_from_edge = np.amin(np.vstack((mg.node_y.max()-mg.node_y, mg.node_y-mg.node_y.min())), axis=0) # make the "hole" hole_elev = np.sqrt(x_distance_from_center**2 + y_distance_from_center**2) # make the rim: rim_elev = np.sqrt(x_distance_from_edge**2 + y_distance_from_edge**2) # assemble z = np.amin(np.vstack((hole_elev, rim_elev)), axis=0) z += np.random.rand(nx*ny)/1000. mg.add_field('node', 'topographic__elevation', z, copy=False) fr = FlowAccumulator(mg, flow_director='D8') lf = DepressionFinderAndRouter(mg) fr.run_one_step() figure('old drainage area') imshow_node_grid(mg, 'drainage_area') lf.map_depressions(pits=mg.at_node['flow__sink_flag']) figure('depression depth') imshow_node_grid(mg, 'depression__depth') figure('new drainage area') imshow_node_grid(mg, 'drainage_area')
elapsed_time += dt #Finalize and plot elev = mg['node']['topographic__elevation'] elev_r = mg.node_vector_to_raster(elev) vid.produce_video() # Clear previous plots pylab.figure("topo") pylab.close() # Plot topography pylab.figure("topo") #im = pylab.imshow(elev_r, cmap=pylab.cm.RdBu) # display a colored image im = llplot.imshow_node_grid(mg, elev) #print elev_r #pylab.colorbar(im) #pylab.title('Topography') pylab.figure("Xsec") im = pylab.plot(dx*numpy.arange(nrows), elev_r[:,int(ncols//2)]) # display a colored image pylab.title('Vertical cross section') pylab.figure("Slope-Area") im = pylab.loglog(mg.at_node['drainage_area'], mg.at_node['topographic__steepest_slope'],'.') pylab.title('Slope-Area') pylab.show() print('Done.')
dx = 1000. close('all') mg = RasterModelGrid(nrows, ncols, dx) z = (3000.-mg.node_x)*0.5 #z = -mg.node_x-mg.node_y #z = np.sqrt(mg.node_x**2 + mg.node_y**2) #z = mg.node_x + mg.node_y #val_to_replace_with = z.reshape((nrows,ncols))[3,3] #z.reshape((nrows,ncols))[2:5,:] = val_to_replace_with mg.at_node['topographic__elevation'] = z #mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True) mg.set_closed_boundaries_at_grid_edges(False, True, True, True) figure(3) imshow_node_grid(mg, mg.status_at_node) mg.at_node['water__unit_flux_in'] = np.ones_like(z) pfr = PotentialityFlowRouter(mg, 'pot_fr_params.txt') pfr.route_flow(route_on_diagonals=True) figure(1) imshow_node_grid(mg, 'surface_water__discharge') figure(2) imshow_node_grid(mg, 'topographic__elevation') out_sum = np.sum(mg.at_node['surface_water__discharge'].reshape((nrows,ncols))[-3,:]) print(out_sum) print(np.sum(mg.at_node['water__unit_flux_in']), np.sum(mg.at_node['surface_water__discharge'][mg.boundary_nodes]))
mg.at_node['topographic__elevation'][section_col] = mg.at_node['topographic__elevation'][inlet_node]+1. pfr.route_flow(route_on_diagonals=True) #imshow(mg, 'surface_water__discharge') #show() kd = mg.at_node['surface_water__discharge'] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g = mg.calc_grad_of_active_link(mg.at_node['topographic__elevation']) mg.map_max_of_link_nodes_to_link('surface_water__discharge', out=mg.at_link[ 'surface_water__discharge']) # map_link_end_node_max_value_to_link(mg, 'surface_water__discharge') kd_link = 1.e6*mg.at_link['surface_water__discharge'][mg.active_links] qs = -kd_link*g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dqsdx mg.at_node['topographic__elevation'][interior_nodes] += dzdt[interior_nodes]*dt if i%50==0: print('loop '+str(i)) section_downfan.append(mg.node_vector_to_raster(mg.at_node['topographic__elevation'])[1:,section_col].copy()) figure(1) imshow_node_grid(mg, 'topographic__elevation') figure(2) imshow_node_grid(mg, 'surface_water__depth') figure(3) imshow_node_grid(mg, 'surface_water__discharge', cmap='Blues_r') figure(4) for i in range(len(section_downfan)): plot(section_downfan[i], '-')
mg = RasterModelGrid(nrows, ncols, dx) #create the fields in the grid mg.create_node_array_zeros('topographic__elevation') z = mg.create_node_array_zeros() + init_elev mg['node'][ 'topographic__elevation'] = z + np.random.rand(len(z))/1000. #make some surface load stresses in a field to test mg.at_node['surface_load__stress'] = np.zeros(nrows*ncols, dtype=float) square_qs = mg.at_node['surface_load__stress'].view().reshape((nrows,ncols)) square_qs[10:40, 10:40] += 1.e6 #instantiate: gf = gFlex(mg, './AW_gflex_params.txt') #perform the loop: elapsed_time = 0. #total time in simulation while elapsed_time < time_to_run: print(elapsed_time) if elapsed_time+dt>time_to_run: print("Short step!") dt = time_to_run - elapsed_time gf.flex_lithosphere() elapsed_time += dt pylab.figure(1) im = imshow_node_grid(mg, 'topographic__elevation') # display a colored image pylab.figure(2) im = imshow_node_grid(mg, 'lithosphere__vertical_displacement')
#Create a field of node data (an array) on the grid called elevation. #Initially populate this array with zero values. #The component wants the elevation field to be called 'topographic__elevation' z = mg.add_zeros('node', 'topographic__elevation') #Check the size of the array len(z) #Create a diagonal fault across the grid fault_y = 50.0 + 0.25*mg.node_x upthrown_nodes = numpy.where(mg.node_y>fault_y) z[upthrown_nodes] += 10.0 + 0.01*mg.node_x[upthrown_nodes] #Illustrate the grid imshow_node_grid(mg, 'topographic__elevation', cmap='jet', grid_units=['m','m']) show() #Instantiate the diffusion component: linear_diffuse = LinearDiffuser(grid=mg, input_stream='./diffusion_input_file.txt') #Set boundary conditions mg.set_closed_boundaries_at_grid_edges(False, True, False, True) #set a model timestep #(the component will subdivide this as needed to keep things stable) dt = 2000. #Evolve landscape for i in range(25): linear_diffuse.diffuse(dt)
#make some surface load stresses in a field to test mg.at_node['surface_load__stress'] = np.zeros(nrows*ncols, dtype=float) #instantiate: gf = gFlex(mg, './coupled_SP_gflex_params.txt') fsp = FastscapeEroder(mg, './coupled_SP_gflex_params.txt') sp = StreamPowerEroder(mg, './coupled_SP_gflex_params.txt') fr = FlowRouter(mg) #perform the loop: elapsed_time = 0. #total time in simulation while elapsed_time < time_to_run: print(elapsed_time) if elapsed_time+dt>time_to_run: print("Short step!") dt = time_to_run - elapsed_time mg = fr.route_flow() #mg = fsp.erode(mg) mg,_,_ = sp.erode(mg, dt, node_drainage_areas='drainage_area', slopes_at_nodes='topographic__steepest_slope') mg.at_node['surface_load__stress'] = (mg.at_node['topographic__elevation']+1000)*rock_stress_param gf.flex_lithosphere() mg.at_node['topographic__elevation'][mg.number_of_nodes//4:3.*mg.number_of_nodes//4] += uplift_perstep elapsed_time += dt pylab.figure(1) im = imshow_node_grid(mg, 'topographic__elevation') # display a colored image pylab.figure(2) im = imshow_node_grid(mg, 'lithosphere_surface__elevation_increment')
# There are 1000 grid nodes (25 x 40). The `z` array also has 1000 entries: one per grid cell. len(z) # Add a fault trace that angles roughly east-northeast. fault_trace_y = 50.0 + 0.25*mg.node_x # Find the ID numbers of the nodes north of the fault trace with help from Numpy's `where()` function. upthrown_nodes = numpy.where(mg.node_y > fault_trace_y) # Add elevation equal to 10m for all the nodes north of the fault, plus 1cm for every meter east (just to make it interesting). z[upthrown_nodes] += 10.0 + 0.01*mg.node_x[upthrown_nodes] # Show the newly created initial topography using Landlab's *imshow_node_grid* plotting function (which we first need to import). from landlab.plot.imshow import imshow_node_grid imshow_node_grid(mg, 'land_surface__elevation') # Define transport ("diffusivity") coefficient, `D`, and the time-step size, `dt`. D = 0.01 # m2/yr transport coefficient dt = 0.2*mg.dx*mg.dx/D dt # Set boundary conditions (ENWS) mg.set_closed_boundaries_at_grid_edges(False, True, False, True) # Calculate changes in elevation for nodes that are not boundaries core_nodes = mg.core_nodes len(core_nodes) # Loop through 25 iterations representing 50,000 years
mg.at_node['topographic__elevation'][section_col] = mg.at_node['topographic__elevation'][inlet_node]+1. pfr.route_flow(route_on_diagonals=True) #imshow(mg, 'water__volume_flux_magnitude') #show() kd = mg.at_node['water__volume_flux_magnitude'] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g = mg.calculate_gradients_at_active_links(mg.at_node['topographic__elevation']) mg.map_max_of_link_nodes_to_link('water__volume_flux_magnitude', out=mg.at_link[ 'water__volume_flux_magnitude']) # map_link_end_node_max_value_to_link(mg, 'water__volume_flux_magnitude') kd_link = 1.e6*mg.at_link['water__volume_flux_magnitude'][mg.active_links] qs = -kd_link*g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dqsdx mg.at_node['topographic__elevation'][interior_nodes] += dzdt[interior_nodes]*dt if i%50==0: print('loop '+str(i)) section_downfan.append(mg.node_vector_to_raster(mg.at_node['topographic__elevation'])[1:,section_col].copy()) figure(1) imshow_node_grid(mg, 'topographic__elevation') figure(2) imshow_node_grid(mg, mg.hillshade(), cmap='bone') figure(3) imshow_node_grid(mg, 'water__volume_flux_magnitude', cmap='Blues_r') figure(4) for i in range(len(section_downfan)): plot(section_downfan[i], '-')
def define_aspect_node_subset_local(self, dist_tolerance=4., angle_tolerance=15., dip_dir='E'): """ """ grid = self.grid try: print('using subset') # remember, steep_nodes is already core_nodes.size long subset = np.where(self.steep_nodes)[0] except NameError: print('using all nodes') subset = np.arange(grid.core_nodes.size) closest_ft_node = np.empty(subset.size, dtype=int) angle_to_ft = np.empty_like(closest_ft_node, dtype=float) new_angle_to_ft = np.empty_like(closest_ft_node, dtype=float) distance_to_ft = np.empty_like(closest_ft_node, dtype=float) distance_to_ft.fill(sys.float_info.max) new_distance_to_ft = np.empty_like(closest_ft_node, dtype=float) for i in self.ft_trace_node_ids: grid.get_distances_of_nodes_to_point((grid.node_x[i], grid.node_y[i]), node_subset=grid.core_nodes[ subset], get_az='angles', out_distance=new_distance_to_ft, out_azimuth=new_angle_to_ft) closer_nodes = new_distance_to_ft < distance_to_ft distance_to_ft[closer_nodes] = new_distance_to_ft[closer_nodes] angle_to_ft[closer_nodes] = new_angle_to_ft[closer_nodes] closest_ft_node[closer_nodes] = i self.closest_ft_node = -np.ones(grid.core_nodes.size) self.distance_to_ft = -np.ones(grid.core_nodes.size) self.angle_to_ft = -np.ones(grid.core_nodes.size) self.closest_ft_node[subset] = closest_ft_node self.distance_to_ft[subset] = distance_to_ft # angle_to_ft is actually the angle_from_ft! So we need to adjust. # a second problem is that pts downslope (opposite az) can also be on the line. # solution - take a dip_dir input... angle_to_ft = (angle_to_ft + np.pi) % (2. * np.pi) self.angle_to_ft[subset] = angle_to_ft #gridshow.imshow_node_grid(self.grid, self.distance_to_ft) # show() #gridshow.imshow_node_grid(self.grid, self.angle_to_ft) # show() # the relevant condition is now that the local aspect and angle to fault # are the same... # We need to bias the five degrees against distant points, as it's easier # to have similar angles in the far field. Rule should be in px - the # two angles should be within *angle_tol* px of each other at the ft # trace. divergence_at_ft = distance_to_ft * \ np.tan((angle_to_ft - self.aspect[subset]) % np.pi) # might be *too* forgiving for close-in nodes condition = np.less(np.fabs(divergence_at_ft), grid.node_spacing * dist_tolerance) #...so add another tester; must be w/i 15 degrees of each other: diff_angles = np.min([np.fabs(angle_to_ft - self.aspect[subset]), np.fabs( np.fabs(angle_to_ft - self.aspect[subset]) - 2. * np.pi)], axis=0) self.diff_angles = np.empty(grid.core_nodes.size, dtype=float) self.diff_angles.fill(sys.float_info.max) self.diff_angles[subset] = diff_angles #gridshow.imshow_node_grid(self.grid, self.angle_to_ft) # show() figure(6) gridshow.imshow_node_grid(self.grid, np.where( self.diff_angles < 100000., self.diff_angles, -1.)) condition2 = np.less(diff_angles, angle_tolerance * np.pi / 180.) condition = np.logical_and(condition, condition2) core_nodes_size_condition = np.zeros(grid.core_nodes.size, dtype=bool) core_nodes_size_condition[subset] = condition #gridshow.imshow_node_grid(self.grid, core_nodes_size_condition) # show() #core_nodes_size_condition = np.zeros(grid.core_nodes.size, dtype=bool) #core_nodes_size_condition[subset] = condition2 #gridshow.imshow_node_grid(self.grid, core_nodes_size_condition) # show() self.aspect_close_nodes = core_nodes_size_condition print('Calculated and stored nodes with aspects compatible with fault trace...') return self.aspect_close_nodes
mg,_,_ = sp.erode(mg, dt, node_drainage_areas='drainage_area', slopes_at_nodes='topographic__steepest_slope', K_if_used='K_values') #add uplift mg.at_node['topographic__elevation'][mg.core_nodes] += uplift*dt elapsed_time += dt time_off = time.time() print('Elapsed time: ', time_off-time_on) #Finalize and plot elev = mg['node']['topographic__elevation'] elev_r = mg.node_vector_to_raster(elev) # Clear previous plots pylab.figure(1) pylab.close() # Plot topography pylab.figure(1) im = imshow_node_grid(mg, 'topographic__elevation') # display a colored image print(elev_r) pylab.figure(2) im = pylab.plot(dx*numpy.arange(nrows), elev_r[:,int(ncols//2)]) # display a colored image pylab.title('Vertical cross section') pylab.show() print('Done.')
mg.at_node['flow_receiver']) dists_upstr = prf.get_distances_upstream(mg, len(mg.at_node['steepest_slope']), profile_IDs, mg.at_node['links_to_flow_receiver']) prf.plot_profiles(dists_upstr, profile_IDs, mg.at_node['topographic_elevation']) print 'Completed loop ', i print 'Completed the simulation. Plotting...' time_off = time() #Finalize and plot # Clear previous plots pylab.figure(1) pylab.close() pylab.figure(1) im = imshow_node_grid(mg, 'water_discharges', cmap='Blues') # display a colored image pylab.figure(2) im = imshow_node_grid(mg, 'topographic_elevation') # display a colored image elev = mg['node']['topographic_elevation'] elev_r = mg.node_vector_to_raster(elev) pylab.figure(3) im = pylab.plot(mg.dx*np.arange(nrows), elev_r[:,int(ncols//2)]) pylab.title('N-S cross_section') pylab.figure(4) im = pylab.plot(mg.dx*np.arange(ncols), elev_r[int(nrows//4),:]) pylab.title('E-W cross_section') drainage_areas = mg['node']['drainage_area'][mg.get_interior_nodes()]
from landlab import VoronoiDelaunayGrid # , RasterModelGrid from landlab.components.flow_routing.route_flow_dn import FlowRouter from landlab.components.stream_power.stream_power import StreamPowerEroder from landlab.plot.imshow import imshow_node_grid import numpy as np from matplotlib.pyplot import figure, show nnodes = 10000 x, y = np.random.rand(nnodes), np.random.rand(nnodes) mg = VoronoiDelaunayGrid(x,y) #mg = RasterModelGrid(4,5) z = mg.add_field('node', 'topographic__elevation', np.random.rand(nnodes)/10000., copy=False) fr = FlowRouter(mg) spe = StreamPowerEroder(mg, 'drive_sp_params_voronoi.txt') for i in xrange(100): z[mg.core_nodes] += 0.01 fr.route_flow() spe.erode(mg, 1.) imshow_node_grid(mg, 'topographic__elevation') show()
#make some surface load stresses in a field to test mg.at_node['surface_load__stress'] = np.zeros(nrows*ncols, dtype=float) #instantiate: gf = gFlex(mg, './coupled_SP_gflex_params.txt') fsp = FastscapeEroder(mg, './coupled_SP_gflex_params.txt') sp = StreamPowerEroder(mg, './coupled_SP_gflex_params.txt') fr = FlowAccumulator(mg, flow_director='D8') #perform the loop: elapsed_time = 0. #total time in simulation while elapsed_time < time_to_run: print(elapsed_time) if elapsed_time+dt>time_to_run: print("Short step!") dt = time_to_run - elapsed_time mg = fr.run_one_step() #mg = fsp.erode(mg) mg,_,_ = sp.erode(mg, dt, node_drainage_areas='drainage_area', slopes_at_nodes='topographic__steepest_slope') mg.at_node['surface_load__stress'] = (mg.at_node['topographic__elevation']+1000)*rock_stress_param gf.flex_lithosphere() mg.at_node['topographic__elevation'][mg.number_of_nodes//4:3.*mg.number_of_nodes//4] += uplift_perstep elapsed_time += dt pylab.figure(1) im = imshow_node_grid(mg, 'topographic__elevation') # display a colored image pylab.figure(2) im = imshow_node_grid(mg, 'lithosphere_surface__elevation_increment')