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_grid( self.grid, "osl_display", limits=(0.0, 2.0), cmap=self.cmap_for_osl ) show() figure(1)
) # 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_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.")
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_grid(mg, surface, cmap=surf_cmap, colorbar_label=colorbar_label) if receivers is None: receivers = mg.at_node["flow__receiver_node"] if proportions is None: if "flow__receiver_proportions" in mg.at_node: proportions = mg.at_node["flow__receiver_proportions"] else: receivers = np.asarray(receivers) if receivers.ndim == 1: receivers = np.expand_dims(receivers, axis=1) nreceievers = receivers.shape[-1] propColor = plt.get_cmap(quiver_cmap) for j in range(nreceievers): rec = receivers[:, j] is_bad = rec == -1 xdist = -0.8 * (mg.x_of_node - mg.x_of_node[rec]) ydist = -0.8 * (mg.y_of_node - mg.y_of_node[rec]) if proportions is None: proportions = np.ones_like(receivers, dtype=float) is_bad[proportions[:, j] == 0.0] = True xdist[is_bad] = np.nan ydist[is_bad] = np.nan prop = proportions[:, j] * 256.0 lu = np.floor(prop) colors = propColor(lu.astype(int)) shape = (mg.number_of_nodes, 1) plt.quiver( mg.x_of_node.reshape(shape), mg.y_of_node.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.x_of_node[mg.status_at_node == CORE_NODE], mg.y_of_node[mg.status_at_node == CORE_NODE], "b.", label="Core Nodes", zorder=4, ) fg, = plt.plot( mg.x_of_node[mg.status_at_node == FIXED_VALUE_BOUNDARY], mg.y_of_node[mg.status_at_node == FIXED_VALUE_BOUNDARY], "c.", label="Fixed Gradient Nodes", zorder=5, ) fv, = plt.plot( mg.x_of_node[mg.status_at_node == FIXED_GRADIENT_BOUNDARY], mg.y_of_node[mg.status_at_node == FIXED_GRADIENT_BOUNDARY], "g.", label="Fixed Value Nodes", zorder=6, ) c, = plt.plot( mg.x_of_node[mg.status_at_node == CLOSED_BOUNDARY], mg.y_of_node[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.x_of_node[flow_to_self], mg.y_of_node[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)
def main(): nr = 5 nc = 6 nnodes = nr*nc dx=1 #instantiate grid rg = RasterModelGrid(nr, nc, dx) #rg.set_inactive_boundaries(False, False, True, True) nodata_val=-1 z = nodata_val*np.ones( nnodes ) #set-up interior elevations with random numbers #for i in range(0, nnodes): # if rg.is_interior(i): # elevations[i]=random.random_sample() #set-up elevations helper = [7,8,9,10,13,14,15,16] for i in xrange(0, len(helper)): #print 'helper[i]', helper[i] z[helper[i]]=2+uniform(-0.5,0.5) helper = [19,20,21,22] for i in xrange(0, len(helper)): z[helper[i]]=3+uniform(-0.5,0.5) z[7]=1 #set up boundary conditions bc=WatershedBoundaryConditions() outlet_loc = bc.set_bc_find_outlet(rg, z, nodata_val) zoutlet=z[outlet_loc] #some helper and parameter values total_run_time = 500000 #yr uplift_rate = 0.001 #m/yr rain_rate = 1 #m/yr storm_duration = 50 #years elapsed_time = 0 #years #set up fluvial incision component incisor = PowerLawIncision('input_file.txt',rg) #print "elevations before ", rg.node_vector_to_raster(z) #interior_nodes are the nodes on which you will be operating interior_nodes = rg.get_active_cell_node_ids() while elapsed_time < total_run_time: #uplift the landscape z[interior_nodes] = z[interior_nodes]+uplift_rate * storm_duration z[outlet_loc]=zoutlet #erode the landscape z = incisor.run_one_storm(rg,z,rain_rate,storm_duration) #update the time elapsed_time = elapsed_time+storm_duration #below purely for plotting reasons #instantiate variable of type RouteFlowD8 Class flow_router = RouteFlowD8(len(z)) #initial flow direction flowdirs, max_slopes = flow_router.calc_flowdirs(rg,z) #insantiate variable of type AccumFlow Class accumulator = AccumFlow(rg) #initial flow accumulation drain_area = accumulator.calc_flowacc(rg, z, flowdirs) #m,b = polyfit(log10(drain_area[interior_nodes]), log10(max_slopes[interior_nodes]), 1) z[interior_nodes] = z[interior_nodes]+uplift_rate * storm_duration z[outlet_loc]=zoutlet plt.loglog(np.array(drain_area),np.array(max_slopes),'ro',) plt.show() imshow_grid(rg,z, values_at='node')
# Increased elapsed time elapsed_time += of.dt # End time... endtime = time() # Now we calculate how long the run actually took and print out the value. totaltime = endtime - starttime print("Total time: ", totaltime, " seconds") # Plotting # Our first figure will be the wave front on the horizontal plane pylab.plt.figure(1) imshow_grid(rmg, 'water__depth', cmap="Blues", grid_units=("m", "m")) # The second figure will compare the depth profiles of the analytical solution # and our modeled solution. # Here is the total plane distance x = np.arange(0, ((numcols) * dx), dx) x = np.insert(x, 0, 0) # Now we will solve the analytical solution h_analytical = (-seven_over_three * n * n * u * u * (x - (u * run_time))) # 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)
slope_horn,aspect_horn = \ grid.calculate_slope_aspect_at_nodes_horn(ids,vals = 'Elevation') ## BestFitPlane slope_BFP, aspect_BFP = grid.calculate_slope_aspect_at_nodes_bestFitPlane( ids, elev) pic = 0 plt.figure(pic) imshow_field(grid, 'Elevation', values_at='node', grid_units=('m', 'm')) plt.title('Elevation in m') #plt.savefig('Elevation_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(slope_Burrough), values_at='cell', grid_units=('m', 'm')) plt.title('Slope in degrees - Burrough 1998') #plt.savefig('Slope_Burrough_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(aspect_Burrough), values_at='cell', grid_units=('m', 'm')) plt.title('Aspect in degrees - Burrough 1998') #plt.savefig('aspect_Burrough_NS') pic += 1 plt.figure(pic)
rmg.at_node["surface_water__depth"][inside_left_edge] = h_boundary # Increased elapsed time elapsed_time += of.dt # End time... endtime = time() # Now we calculate how long the run actually took, print out the total value. totaltime = endtime - starttime print("Total time: ", totaltime, " seconds") # Plotting # Our first figure will be the wave front on the horizontal plane pylab.plt.figure(1) imshow_grid(rmg, "surface_water__depth", cmap="Purples", grid_units=("m", "m")) # The second figure will compare the depth profiles of the analytical solution # and our modeled solution # Here is the total plane 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 * run_time)) # 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 )
rad.update(current_time) """ Create a figure window available from pyplot library. This allows separating figures while plotting multiple figures. """ plt.figure(0) """ Plot the cellular field 'TotalShortWaveRadiation' that is available on the grid. imshow_grid is a Landlab plotting tool that reads the input of grid, the variable name that needs to be plotted, and type of field (whether it is 'cell' or 'node', etc... It also reads optional inputs (keywords), grid_units (units of grid X and Y axes , e.g. 'm'). For more options, please refer documentation for landlab.plot.imshow. """ imshow_grid(grid, 'TotalShortWaveRadiation', values_at='cell', grid_units=('m', 'm')) """ The plot created can be saved using the function 'savefig' available in pyplot library. This file will be saved in the current directory that your python shell is in. You can know the current directory by using 'pwd' command in the shell. (This documentation works if Enthought Canopy is used. It might work for other packages too but is not tested by the author.) """ plt.savefig('Radiation') """ Plot another figure. """ plt.figure(1) """ Using Landlab plotting tool, lets plot another variable 'RadiationFactor'.
def main(): nr = 5 nc = 6 nnodes = nr * nc dx = 1 #instantiate grid rg = RasterModelGrid(nr, nc, dx) #rg.set_inactive_boundaries(False, True, True, False) nodata_val = -1 z = nodata_val * np.ones(nnodes) #set-up interior elevations with random numbers #for i in range(0, nnodes): # if rg.is_interior(i): # elevations[i]=random.random_sample() #set-up elevations helper = [7, 8, 9, 10, 13, 14, 15, 16] for i in range(0, len(helper)): #print 'helper[i]', helper[i] z[helper[i]] = 2 + uniform(-0.5, 0.5) helper = [19, 20, 21, 22] for i in range(0, len(helper)): z[helper[i]] = 3 + uniform(-0.5, 0.5) z[7] = 1 #set up boundary conditions bc = WatershedBoundaryConditions() outlet_loc = bc.set_bc_find_outlet(rg, z, nodata_val) zoutlet = z[outlet_loc] #some helper and parameter values total_run_time = 500000 #yr uplift_rate = 0.001 #m/yr rain_rate = 1 #m/yr storm_duration = 50 #years elapsed_time = 0 #years #set up fluvial incision component incisor = PowerLawIncision('input_file.txt', rg) #print "elevations before ", rg.node_vector_to_raster(z) #interior_nodes are the nodes on which you will be operating interior_nodes = np.where(rg.status_at_node != CLOSED_BOUNDARY)[0] while elapsed_time < total_run_time: #uplift the landscape z[interior_nodes] = z[interior_nodes] + uplift_rate * storm_duration z[outlet_loc] = zoutlet #erode the landscape z = incisor.run_one_storm(rg, z, rain_rate, storm_duration) #update the time elapsed_time = elapsed_time + storm_duration #below purely for plotting reasons #instantiate variable of type RouteFlowD8 Class flow_router = RouteFlowD8(len(z)) #initial flow direction flowdirs, max_slopes = flow_router.calc_flowdirs(rg, z) #insantiate variable of type AccumFlow Class accumulator = AccumFlow(rg) #initial flow accumulation drain_area = accumulator.calc_flowacc(z, flowdirs) #m,b = polyfit(log10(drain_area[interior_nodes]), log10(max_slopes[interior_nodes]), 1) z[interior_nodes] = z[interior_nodes] + uplift_rate * storm_duration z[outlet_loc] = zoutlet plt.loglog( np.array(drain_area), np.array(max_slopes), 'ro', ) plt.show() imshow_grid(rg, z, values_at='node')
""" rad.update( current_time ) """ Create a figure window available from pyplot library. This allows separating figures while plotting multiple figures. """ plt.figure(0) """ Plot the cellular field 'TotalShortWaveRadiation' that is available on the grid. imshow_grid is a Landlab plotting tool that reads the input of grid, the variable name that needs to be plotted, and type of field (whether it is 'cell' or 'node', etc... It also reads optional inputs (keywords), grid_units (units of grid X and Y axes , e.g. 'm'). For more options, please refer documentation for landlab.plot.imshow. """ imshow_grid(grid,'TotalShortWaveRadiation', values_at = 'cell', grid_units = ('m','m')) """ The plot created can be saved using the function 'savefig' available in pyplot library. This file will be saved in the current directory that your python shell is in. You can know the current directory by using 'pwd' command in the shell. (This documentation works if Enthought Canopy is used. It might work for other packages too but is not tested by the author.) """ plt.savefig('Radiation') """ Plot another figure. """ plt.figure(1) """ Using Landlab plotting tool, lets plot another variable 'RadiationFactor'.
# Example to use potential_evapotranspiration_field.py #import landlab from landlab import RasterModelGrid from landlab.components.radiation.radiation_field import Radiation from landlab.components.pet.potential_evapotranspiration_field import ( PotentialEvapotranspiration) import numpy as np import matplotlib.pyplot as plt from landlab.plot.imshow import imshow_grid grid = RasterModelGrid( 100, 100, 20. ) elevation = np.random.rand(grid.number_of_nodes) * 1000 grid.add_zeros('node','Elevation',units = 'm') grid['node']['Elevation'] = elevation rad = Radiation( grid ) PET = PotentialEvapotranspiration( grid ) current_time = 0.56 rad.update( current_time ) PET.update( ConstantPotentialEvapotranspiration = 10.0 ) plt.figure(0) imshow_grid(grid,'RadiationFactor', values_at = 'cell', grid_units = ('m','m')) plt.figure(1) imshow_grid(grid,'PotentialEvapotranspiration', values_at = 'cell', grid_units = ('m','m')) plt.savefig('PET_test') plt.show()
import numpy as np from matplotlib.pyplot import show from six.moves import range from landlab import VoronoiDelaunayGrid from landlab.components import FlowAccumulator, StreamPowerEroder from landlab.plot.imshow import imshow_grid nnodes = 10000 x, y = np.random.rand(nnodes), np.random.rand(nnodes) mg = VoronoiDelaunayGrid(x, y) z = mg.add_field( "node", "topographic__elevation", np.random.rand(nnodes) / 10000., copy=False ) fr = FlowAccumulator(mg) spe = StreamPowerEroder(mg, "drive_sp_params_voronoi.txt") for i in range(100): z[mg.core_nodes] += 0.01 fr.run_one_step() spe.erode(mg, 1.) imshow_grid(mg, "topographic__elevation") show()
# Sai Nudurupati and Erkan Istanbulluoglu- 16May2014 : # Example to use potential_evapotranspiration_field.py #import landlab from landlab import RasterModelGrid from landlab.components.radiation import Radiation from landlab.components.pet import PotentialEvapotranspiration import numpy as np import matplotlib.pyplot as plt from landlab.plot.imshow import imshow_grid grid = RasterModelGrid( 100, 100, 20. ) elevation = np.random.rand(grid.number_of_nodes) * 1000 grid.add_zeros('node','Elevation',units = 'm') grid['node']['Elevation'] = elevation rad = Radiation( grid ) PET = PotentialEvapotranspiration( grid ) current_time = 0.56 rad.update( current_time ) PET.update( ConstantPotentialEvapotranspiration = 10.0 ) plt.figure(0) imshow_grid(grid,'RadiationFactor', values_at = 'cell', grid_units = ('m','m')) plt.figure(1) imshow_grid(grid,'PotentialEvapotranspiration', values_at = 'cell', grid_units = ('m','m')) plt.savefig('PET_test') plt.show()
SI = SoilInfiltrationGreenAmpt( mg,hydraulic_conductivity=hydraulic_conductivity, soil_type ='silt loam') for i in range(10): # 100s total SI.run_one_step(10.) swd = mg.at_node['surface_water__depth'] # array([ 1.00000000e-08, 1.00000000e-08, 1.00000000e-08, # 1.00000000e-08, 1.00000000e-08, 1.00000000e-08, # 9.88530416e-03, 9.88530416e-03, 9.88530416e-03, # 9.88530416e-03, 9.88530416e-03, 9.88530416e-03]) swid = mg.at_node['soil_water_infiltration__depth'] # array([ 0.20999999, 0.20999999, 0.20999999, 0.20999999, 0.20999999, # 0.20999999, 0.2001147 , 0.2001147 , 0.2001147 , 0.2001147 , # 0.2001147 , 0.2001147 ]) #SoilInfiltrationGreenAmpt.input_var_names plot_graph(mg, at="node") imshow_grid(mg, 'surface_water__depth') imshow_grid(mg, 'soil_water_infiltration__depth') #%% hugo_mg, z = read_esri_ascii('hugo_site.asc', name='topographic__elevation')
dt, node_drainage_areas="drainage_area", slopes_at_nodes="topographic__steepest_slope", Q_if_used=my_Q, ) # no uplift # print the stream power that was calculated: print("stream power values:") print(mg.at_node["stream_power_erosion"]) # 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_grid(mg, "topographic__elevation") # display a colored image pylab.figure(2) im = pylab.plot(dx * np.arange(nrows), elev_r[:, int(ncols // 2)]) pylab.title("Vertical cross section") pylab.show() print("Done.")
slope_BFP, aspect_BFP = grid.calculate_slope_aspect_at_nodes_bestFitPlane( ids, elev) # node_slopes_using_patches slope_NSP = grid.node_slopes_using_patches(elevs='Elevation', unit='degrees') pic = 0 plt.figure(pic) imshow_field(grid, 'Elevation', values_at='node', grid_units=('m', 'm')) plt.title('Elevation in m') # plt.savefig('Elevation_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(slope_Burrough), values_at='cell', grid_units=('m', 'm')) plt.title('Slope in degrees - Burrough 1998') # plt.savefig('Slope_Burrough_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(aspect_Burrough), values_at='cell', grid_units=('m', 'm')) plt.title('Aspect in degrees - Burrough 1998') # plt.savefig('aspect_Burrough_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(slope_horn), values_at='cell', grid_units=('m', 'm')) plt.title('Slope in degrees - Horn')
slope_burrough, aspect_burrough = \ grid.calculate_slope_aspect_at_nodes_burrough(ids, vals='Elevation') # Horn slope_horn, aspect_horn = \ grid.calculate_slope_aspect_at_nodes_horn(ids, vals='Elevation') # BestFitPlane slope_bfp, aspect_bfp = grid.calculate_slope_aspect_at_nodes_best_fit_plane( ids, elev) # node_slopes_using_patches slope_NSP = grid.node_slopes_using_patches(elevs='Elevation', unit='degrees') pic = 0 plt.figure(pic) imshow_grid(grid, 'Elevation', values_at='node', grid_units=('m', 'm')) plt.title('Elevation in m') # plt.savefig('Elevation_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(slope_burrough), values_at='cell', grid_units=('m', 'm')) plt.title('Slope in degrees - Burrough 1998') # plt.savefig('Slope_burrough_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(aspect_burrough), values_at='cell', grid_units=('m', 'm')) plt.title('Aspect in degrees - Burrough 1998')
mg = RasterModelGrid((nrows, ncols), xy_spacing=dx) # create the fields in the grid mg.add_zeros("topographic__elevation", at="node") z = mg.zeros(at="node") + 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_grid(mg, "topographic__elevation") # display a colored image pylab.figure(2) im = imshow_grid(mg, "lithosphere_surface__elevation_increment")
import numpy as np from matplotlib.pyplot import show from six.moves import range from landlab import VoronoiDelaunayGrid from landlab.components import FlowAccumulator, StreamPowerEroder from landlab.plot.imshow import imshow_grid nnodes = 10000 x, y = np.random.rand(nnodes), np.random.rand(nnodes) mg = VoronoiDelaunayGrid(x, y) z = mg.add_field("node", "topographic__elevation", np.random.rand(nnodes) / 10000., copy=False) fr = FlowAccumulator(mg) spe = StreamPowerEroder(mg, "drive_sp_params_voronoi.txt") for i in range(100): z[mg.core_nodes] += 0.01 fr.run_one_step() spe.erode(mg, 1.) imshow_grid(mg, "topographic__elevation") show()
# Increased elapsed time elapsed_time += of.dt # End time... endtime = time() # Now we calculate how long the run actually took and print out the total value. totaltime = endtime - starttime print("Total run time: ", totaltime, " seconds") # Plotting # Our first figure will be the wave front on the horizontal plane pylab.plt.figure(1) imshow_grid(rmg, 'water_depth', cmap="Blues", grid_units=("m", "m")) # The second figure will compare the depth profiles of the analytical solution # and our modeled solution. # Here is the total plane 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 * run_time))) # 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
# 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_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()
# # Let's take a graphical look at the elevation grid we've created. To do so, # we'll use the Pylab graphics library (imported under the name `plt`). # Finally, we will import Landlab's `imshow_grid` function to display our # gridded values. # In[ ]: import matplotlib.pyplot as plt from landlab.plot.imshow import imshow_grid # Let's plot the elevation values: # In[ ]: imshow_grid(mg, 'topographic__elevation') # There are elevation values associated with all 12 of the nodes on the grid. # The ones shown in black are **boundary nodes**; the two in the middle are # **core nodes**. This is our *scalar field*. # ## Links and gradients # # Next, we will calculate the gradient in this field of elevation values. We # want to find the gradient between each pair of adjacent nodes, and store that # value at the associated **link** between them. # # ### What are links? # # For each pair of adjacent nodes in a Landlab grid, there is a corresponding # **link**. Links are directed line segments whose endpoints are the
return polygon polygon_list = [ get_polygon_from_raster_file(os.path.join(data_dir, dem_file)) for dem_file in dem_file_list ] gdf = gpd.GeoDataFrame(polygon_list, geometry=0, crs=gdal.Open(os.path.join( data_dir, dem_file_list[0])).GetProjection()) gdf.plot() (rmg, z) = read_esri_ascii(dem_path, name='topographic__elevation') imshow_grid(rmg, 'topographic__elevation') # ## Landlab It # 92V5 works! dem_path = os.path.join(data_dir, '73V3.asc') (rmg, z) = read_esri_ascii(dem_path, name='topographic__elevation') rmg.set_nodata_nodes_to_closed(rmg.at_node['topographic__elevation'], -9999) imshow_grid(rmg, 'topographic__elevation') sfb = SinkFillerBarnes(rmg, fill_flat=False)
# Increased elapsed time elapsed_time += of.dt # End time... endtime = time() # Now we calculate how long the run actually took and print out the value. totaltime = endtime - starttime print("Total time: ", totaltime, " seconds") # Plotting # Our first figure will be the wave front on the horizontal plane pylab.plt.figure(1) imshow_grid(rmg, "surface_water__depth", cmap="Blues", grid_units=("m", "m")) # The second figure will compare the depth profiles of the analytical solution # and our modeled solution. # Here is the total plane distance x = np.arange(0, ((numcols) * dx), dx) x = np.insert(x, 0, 0) # Now we will solve the analytical solution h_analytical = -seven_over_three * n * n * u * u * (x - (u * run_time)) # 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
# BestFitPlane slope_bfp, aspect_bfp = grid.calculate_slope_aspect_at_nodes_best_fit_plane(ids, elev) # node_slopes_using_patches slope_NSP = grid.node_slopes_using_patches(elevs="Elevation", unit="degrees") pic = 0 plt.figure(pic) imshow_field(grid, "Elevation", values_at="node", grid_units=("m", "m")) plt.title("Elevation in m") # plt.savefig('Elevation_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(slope_burrough), values_at="cell", grid_units=("m", "m")) plt.title("Slope in degrees - Burrough 1998") # plt.savefig('Slope_burrough_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(aspect_burrough), values_at="cell", grid_units=("m", "m")) plt.title("Aspect in degrees - Burrough 1998") # plt.savefig('aspect_burrough_NS') pic += 1 plt.figure(pic) imshow_grid(grid, np.degrees(slope_horn), values_at="cell", grid_units=("m", "m")) plt.title("Slope in degrees - Horn") # plt.savefig('Slope_Horn_NS')
print(elapsed_time) # , total_h # Increased elapsed time elapsed_time += dt # End time... endtime = time() # Now we calculate how long the run actually took and print out the total value. totaltime = endtime - starttime print("Total time: ", totaltime, " seconds") # Plotting # Our first figure will be the wave front on the horizontal plane pylab.plt.figure(1) imshow_grid(rmg, "water_depth", cmap="Purples", grid_units=("m", "m")) # The second figure will compare the depth profiles of the analytical solution and our modeled solution # Here is the total plane 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 * run_time)) # 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
# ### Create the raster model grid of elevation (rmg, elevations) = read_esri_ascii("data/carbon_watershed_dem_30m.asc", name="topographic__elevation") # Set all no data nodes to "closed" boundaries rmg.set_nodata_nodes_to_closed(elevations, -3.4028234663852886e+38) import matplotlib matplotlib.rcParams['figure.figsize'] = (14, 7) imshow_grid( rmg, 'topographic__elevation', plot_name='LIDAR DEM, 2007-08 Mt. Rainier, Carbon Glacier watershed', var_name='elevation', var_units='m', grid_units=('m', 'm')) # Set watershed boundary condition; i.e. find outlet node # # If simple call doesn't work, set the outlet node to be the node with lowest elevation try: outlet_node = rmg.set_watershed_boundary_condition( elevations, return_outlet_id=True, remove_disconnected=True) except: outlet_id = rmg.core_nodes[np.argmin(rmg.at_node['topographic__elevation'][ rmg.core_nodes])] # find the lowest point on our DEM?
rmg.at_node['surface_water__depth'][inside_left_edge] = h_boundary # Increased elapsed time elapsed_time += of.dt # End time... endtime = time() # Now we calculate how long the run actually took, print out the total value. totaltime = endtime - starttime print("Total time: ", totaltime, " seconds") # Plotting # Our first figure will be the wave front on the horizontal plane pylab.plt.figure(1) imshow_grid(rmg, 'surface_water__depth', cmap="Purples", grid_units=("m", "m")) # The second figure will compare the depth profiles of the analytical solution # and our modeled solution # Here is the total plane 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 * run_time))) # 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
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_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_grid(mg, "surface_water__discharge") figure(2) imshow_grid(mg, "topographic__elevation") out_sum = np.sum(mg.at_node["surface_water__discharge"].reshape((nrows, ncols))[-3, :]) print(out_sum) print(
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_grid(mg, "drainage_area") lf.map_depressions(pits=mg.at_node["flow__sink_flag"]) figure("depression depth") imshow_grid(mg, "depression__depth") figure("new drainage area") imshow_grid(mg, "drainage_area")
(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_grid(mg, "drainage_area") lf.map_depressions(pits=mg.at_node["flow__sink_flag"]) figure("depression depth") imshow_grid(mg, "depression__depth") figure("new drainage area") imshow_grid(mg, "drainage_area")