def output_writer_1(m): min_z = np.min(m.z[np.where(m.z > 0)]) max_z = np.max(m.z[np.where(m.z > 0)]) lim_z = (min_z, max_z) # Creating the watershed masks from the model's model grid. mask = get_watershed_masks(m.grid) # Creating the figure with the subplots. figure(figsize=(20, 4)) subplot(151) imshow_grid(m.grid, 'initial_topographic__elevation', plot_name='initial_topographic__elevation', cmap='terrain', color_for_closed=None, limits=lim_z, shrink=0.5) subplot(152) imshow_grid(m.grid, 'topographic__elevation', plot_name=f'topographic__elevation -{m.model_time}', cmap='terrain', color_for_closed=None, limits=lim_z, shrink=0.5) subplot(153) imshow_grid(m.grid, 'cumulative_elevation_change', plot_name=f'Cumulative elevation change - {m.model_time}', cmap='viridis', color_for_closed=None, shrink=0.5) subplot(154) imshow_grid(m.grid, 'topographic__steepest_slope', plot_name=f'topographic__steepest_slope - {m.model_time}', cmap='YlOrRd', color_for_closed=None, shrink=0.5) subplot(155) imshow_grid(m.grid, mask, plot_name=f'Watersheds - {m.model_time}', cmap='tab20b', color_for_closed=None, shrink=0.5) plt.tight_layout() plt.show()
def plot_elev(file, index): grid = from_netcdf(file) fig = plt.figure(figsize=(8,6)) imshow_grid(grid,'topographic__elevation', cmap='gist_earth', limits=(0,max(elev)), colorbar_label = 'Elevation [m]', grid_units=('m','m')) plt.tight_layout() fig.canvas.draw() # draw the canvas, cache the renderer image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) plt.close() return image
def plot_flood_quiver(grid, resample=1): """Quiver plot of flood velocities. Inputs : grid : `obj` A landlab grid object resample `int` Downsampling value Returns : Draws a figure that can be rendered with plt.show() """ (_, _, flood_x, flood_y) = mvcn(grid) # down-sample for legible quiver plots if needed if resample != 1: xr = grid.x_of_node.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] yr = grid.y_of_node.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] fld_xr = flood_x.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] fld_yr = flood_y.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] else: xr = grid.x_of_node yr = grid.y_of_node fld_xr = flood_x fld_yr = flood_y # flood tide plt.figure() imshow_grid(grid, grid.at_node['topographic__elevation']) plt.quiver(xr, yr, fld_xr, fld_yr) plt.title('Flood Tide') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)')
def plot_ebb_quiver(grid, resample=1): """Quiver plot of ebb velocities. Inputs : grid : `obj` A landlab grid object resample `int` Downsampling value Returns : Draws a figure that can be rendered with plt.show() """ (ebb_x, ebb_y, _, _) = mf.map_velocity_components_to_nodes(grid) # down-sample for legible quiver plots if needed if resample != 1: xr = grid.x_of_node.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] yr = grid.y_of_node.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] ebb_xr = ebb_x.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] ebb_yr = ebb_y.reshape((grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] else: xr = grid.x_of_node yr = grid.y_of_node ebb_xr = ebb_x ebb_yr = ebb_y # ebb tide plt.figure() imshow_grid(grid, grid.at_node['topographic__elevation']) plt.quiver(xr, yr, ebb_xr, ebb_yr) plt.title('Ebb Tide') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)')
def plot_depth(grid, resample=1): """Plot of water depths. Inputs : grid : `obj` A landlab grid object resample : `int` Downsampling value Returns : Draws a figure that can be rendered with plt.show() """ # depth plt.figure() imshow_grid(grid, grid.at_node['mean_water__depth'], cmap='YlGnBu', color_for_closed='g') plt.title('Water depth (m)') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)')
def plot_flood_magnitudes(grid, resample=1): """Plot of flood velocities. Inputs : grid : `obj` A landlab grid object resample : `int` Downsampling value Returns : Draws a figure that can be rendered with plt.show() """ (_, _, flood_x, flood_y) = mf.map_velocity_components_to_nodes(grid) plt.figure() flood_vel_magnitude = np.sqrt(flood_x * flood_x + flood_y * flood_y) imshow_grid(grid, flood_vel_magnitude, cmap='magma', color_for_closed='g') plt.title('Flood Tide Velocity Magnitude (m/s)') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)')
def test_query_grid_on_button_press(): rmg = RasterModelGrid((5, 5)) imshow_grid(rmg, rmg.nodes, cmap='RdYlBu') # Programmatically create an event near the grid center. event = Event('simulated_event', gcf().canvas) event.xdata = int(rmg.number_of_node_columns * 0.5) event.ydata = int(rmg.number_of_node_rows * 0.5) results = query_grid_on_button_press(event, rmg) x_coord = results['grid location']['x_coord'] y_coord = results['grid location']['x_coord'] msg = 'Items: Simulated matplotlib event and query results.' assert_equal(x_coord, event.xdata, msg) assert_equal(y_coord, event.ydata, msg) msg = 'Items: Node ID and grid coordinates of simulated matplotlib event.' node = rmg.grid_coords_to_node_id(event.xdata, event.ydata) assert_equal(results['node']['ID'], node, msg)
def test_query_grid_on_button_press(): rmg = RasterModelGrid((5, 5)) imshow_grid(rmg, rmg.nodes, cmap='RdYlBu') # Programmatically create an event near the grid center. event = Event('simulated_event', gcf().canvas) event.xdata = int(rmg.number_of_node_columns * 0.5) event.ydata = int(rmg.number_of_node_rows * 0.5) results = query_grid_on_button_press(event, rmg) x_coord = results['grid location']['x_coord'] y_coord = results['grid location']['x_coord'] msg = 'Items: Simulated matplotlib event and query results.' assert_equal(x_coord, event.xdata, msg) assert_equal(y_coord, event.ydata, msg) msg = 'Items: Node ID and grid coordinates of simulated matplotlib event.' node = rmg.grid_coords_to_node_id(event.xdata, event.ydata) assert_equal(results['node']['ID'], node, msg)
def plot_ebb_magnitudes(grid, resample=1): """Plot of ebb velocities. Inputs : grid `obj` A landlab grid object resample : `int` Downsampling value Returns : Draws a figure that can be rendered with plt.show() """ (ebb_x, ebb_y, _, _) = mf.map_velocity_components_to_nodes(grid) ebb_vel_magnitude = np.sqrt(ebb_x * ebb_x + ebb_y * ebb_y) plt.figure() imshow_grid(grid, ebb_vel_magnitude, cmap='magma', color_for_closed='g') plt.title('Ebb Tide Velocity Magnitude (m/s)') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)')
def test_query_grid_on_button_press(): rmg = RasterModelGrid((5, 5)) imshow_grid(rmg, rmg.nodes, cmap="RdYlBu") # Programmatically create an event near the grid center. event = Event("simulated_event", gcf().canvas) event.xdata = int(rmg.number_of_node_columns * 0.5) event.ydata = int(rmg.number_of_node_rows * 0.5) results = query_grid_on_button_press(event, rmg) x_coord = results["grid location"]["x_coord"] y_coord = results["grid location"]["x_coord"] msg = "Items: Simulated matplotlib event and query results." assert_equal(x_coord, event.xdata, msg) assert_equal(y_coord, event.ydata, msg) msg = "Items: Node ID and grid coordinates of simulated matplotlib event." node = rmg.grid_coords_to_node_id(event.xdata, event.ydata) assert_equal(results["node"]["ID"], node, msg)
""" Creates a standarized topography and saves it in the numpy-inherent array format. Therefore needs numpy to work.""" ## Import necessary Python and Landlab Modules import numpy as np from matplotlib import pyplot as plt from landlab import RasterModelGrid from landlab import imshow_grid ncols = 101 nrows = 101 dx = 100 #creates landlab grid out of ncols and nrows to get the right amount of nodes #spacing. could also do completely with numpy but thats easier... mg = RasterModelGrid((nrows, ncols), dx) #creates random array with size of mg-grid topoSeed = np.random.rand(mg.at_node.size)/100 #saves topoSeed as numpy array np.save('topoSeed',topoSeed) plt.figure() imshow_grid(mg, topoSeed) plt.savefig('initalTopo.png') plt.close() print('------------------------------') print('Saved a output-topography to file topoSeed.npy') print('Saved a picture of the topography to initialTopo.png') print('------------------------------')
def run_one_step(self): """ """ # find the faulted node with the largest drainage area. largest_da = np.max(self._model.grid.at_node['drainage_area'][ self._model.boundary_handler['NormalFault'].faulted_nodes == True]) largest_da_ind = np.where( self._model.grid.at_node['drainage_area'] == largest_da)[0][0] start_node = self._model.grid.at_node['flow__receiver_node'][ largest_da_ind] (profile_IDs, dists_upstr) = analyze_channel_network_and_plot( self._model.grid, number_of_channels=1, starting_nodes=[start_node], create_plot=False) elevs = model.z[profile_IDs] self.relative_times.append(self._model.model_time / model.params['run_duration']) offset = np.min(elevs[0]) max_distance = np.max(dists_upstr[0][0]) self.channel_segments.append( np.array((dists_upstr[0][0], elevs[0] - offset)).T) self.xnormalized_segments.append( np.array((dists_upstr[0][0] / max_distance, elevs[0] - offset)).T) self.relative_times.append(self._model.model_time / model.params['run_duration']) colors = cm.viridis_r(self.relative_times) xmin = [xy.min(axis=0)[0] for xy in self.channel_segments] ymin = [xy.min(axis=0)[1] for xy in self.channel_segments] xmax = [xy.max(axis=0)[0] for xy in self.channel_segments] ymax = [xy.max(axis=0)[1] for xy in self.channel_segments] fs = (8, 6) fig, ax = plt.subplots(figsize=fs, dpi=300) ax.set_xlim(0, max(xmax)) ax.set_ylim(0, max(ymax)) line_segments = LineCollection(self.channel_segments, colors=colors, linewidth=0.5) ax.add_collection(line_segments) yr = str(self._model.model_time / (1e6)).zfill(4) plt.savefig('profile_' + yr + '.png') plt.close() fig, ax = plt.subplots(figsize=fs, dpi=300) ax.set_xlim(0, 1) ax.set_ylim(0, max(ymax)) line_segments = LineCollection(self.xnormalized_segments, colors=colors, linewidth=0.5) ax.add_collection(line_segments) yr = str(self._model.model_time / (1e6)).zfill(4) plt.savefig('normalized_profile_' + yr + '.png') plt.close() plt.figure() plot_channels_in_map_view(self._model.grid, profile_IDs) plt.savefig('topography_' + yr + '.png') plt.close() plt.figure() imshow_grid(model.grid, model.grid.at_node['soil__depth'], cmap='viridis', limits=(0, 15)) plt.savefig('soil_' + yr + '.png') plt.close() plt.figure() imshow_grid(self._model.grid, self._model.grid.at_node['sediment__flux'], cmap='viridis') plt.savefig('sediment_flux_' + yr + '.png') plt.close() U_eff = U_fast + U_back U_eff_slow = U_slow + U_back area = np.sort(self._model.grid.at_node['drainage_area'][ self._model.boundary_handler['NormalFault'].faulted_nodes == True]) area = area[area > 0] little_q = ( area * self._model.params['runoff_rate'])**self._model.params['m_sp'] #area_to_the_m = area ** self._model.params['m_sp'] detachment_prediction = ( (U_eff / (self._model.params['K_rock_sp'])) **(1.0 / self._model.params['n_sp']) * (1.0 / little_q)**(1.0 / self._model.params['n_sp'])) transport_prediction = ( ((U_eff * self._model.params['v_sc']) / (self._model.params['K_sed_sp'] * self._model.params['runoff_rate'])) + ((U_eff) / (self._model.params['K_sed_sp'])))**( 1.0 / self._model.params['n_sp']) * ( (1.0 / little_q)**(1.0 / self._model.params['n_sp'])) space_prediction = ( ((U_eff * self._model.params['v_sc']) * (1.0 - Ff) / (self._model.params['K_sed_sp'] * self._model.params['runoff_rate'])) + ((U_eff) / (self._model.params['K_rock_sp'])))**( 1.0 / self._model.params['n_sp']) * ( (1.0 / little_q)**(1.0 / self._model.params['n_sp'])) detachment_prediction_slow = ( (U_eff_slow / (self._model.params['K_rock_sp'])) **(1.0 / self._model.params['n_sp']) * (1.0 / little_q)**(1.0 / self._model.params['n_sp'])) transport_prediction_slow = ( ((U_eff_slow * self._model.params['v_sc']) / (self._model.params['K_sed_sp'] * self._model.params['runoff_rate'])) + ((U_eff_slow) / (self._model.params['K_sed_sp'])))**( 1.0 / self._model.params['n_sp']) * ( (1.0 / little_q)**(1.0 / self._model.params['n_sp'])) space_prediction_slow = ( ((U_eff_slow * self._model.params['v_sc']) * (1.0 - Ff) / (self._model.params['K_sed_sp'] * self._model.params['runoff_rate'])) + ((U_eff_slow) / (self._model.params['K_rock_sp'])))**( 1.0 / self._model.params['n_sp']) * ( (1.0 / little_q)**(1.0 / self._model.params['n_sp'])) # TODO need to fix space predictions here to include new soil thickness. fs = (8, 6) fig, ax = plt.subplots(figsize=fs, dpi=300) plt.plot(area, detachment_prediction, 'c', lw=5, label='Detachment Prediction') plt.plot(area, transport_prediction, 'b', label='Transport Prediction') plt.plot(area, space_prediction, 'm', label='Space Prediction') plt.plot(area, detachment_prediction_slow, 'c', lw=5, alpha=0.3) plt.plot(area, transport_prediction_slow, 'b', alpha=0.3) plt.plot(area, space_prediction_slow, 'm', alpha=0.3) plt.plot(self._model.grid.at_node['drainage_area'][ self._model.boundary_handler['NormalFault'].faulted_nodes == True], self._model.grid.at_node['topographic__steepest_slope'] [self._model.boundary_handler['NormalFault'].faulted_nodes == True], 'k.', label='Fault Block Nodes') plt.plot(self._model.grid.at_node['drainage_area'] [self._model.boundary_handler['NormalFault'].faulted_nodes == False], self._model.grid.at_node['topographic__steepest_slope'] [self._model.boundary_handler['NormalFault'].faulted_nodes == False], 'r.', label='Unfaulted Nodes') plt.plot(self._model.grid.at_node['drainage_area'][profile_IDs], self._model.grid.at_node['topographic__steepest_slope'] [profile_IDs], 'g.', label='Main Channel Nodes') plt.legend() ax.set_xscale('log') ax.set_yscale('log') plt.xlabel('log 10 Area') plt.ylabel('log 10 Slope') plt.savefig('slope_area_' + yr + '.png') plt.close()
if storm_flag == 'Base': starting_precip_mmhr = 5.0 starting_precip_ms = starting_precip_mmhr * (2.77778 * 10**-7) storm_duration = 7200. elif storm_flag == 'HigherIntensity': starting_precip_mmhr = 10.0 starting_precip_ms = starting_precip_mmhr * (2.77778 * 10**-7) storm_duration = 7200. elif storm_flag == 'LongerDuration': starting_precip_mmhr = 5.0 starting_precip_ms = starting_precip_mmhr * (2.77778 * 10**-7) storm_duration = 14400. # * Before we go further, let's pause to look at the landscape that we will be routing flow over. plt.figure(1) imshow_grid(rmg, z) # plot the DEM plt.show() # * Initialize a few more parameters, and getting ready to run the time loop and save data for plotting. # * These two components take time steps in *seconds* uplift_rate = 3.170979 * (10**-10) # m/s elapsed_time = 1.0 model_run_time = 43200.0 # s ## Lists for saving data discharge_at_outlet = [] hydrograph_time = [] incision_at_outlet = []
def makeExamplePlot(): plt.figure() imshow_grid(conGrid, 'topographic__elevation') plt.savefig('convertTopo.png') plt.close()
#write the erodibility values in an grid-field. This is not used for calculations, just for visualiziation afterwards. mg.at_node['fluvial_erodibility__soil'] = Kvs mg.at_node['fluvial_erodibility__bedrock'] = Kvb #increment counter counter += 1 #Run the output loop every outInt-times if elapsed_time % outInt == 0: print('Elapsed Time:', elapsed_time, ', writing output!') ##Create DEM plt.figure() imshow_grid(mg, 'topographic__elevation', grid_units=['m', 'm'], var_name='Elevation', cmap='terrain') plt.savefig('./ll_output/DEM/DEM_' + str(int(elapsed_time / outInt)).zfill(zp) + '.png') plt.close() ##Create Bedrock Elevation Map plt.figure() imshow_grid(mg, 'bedrock__elevation', grid_units=['m', 'm'], var_name='bedrock', cmap='jet') plt.savefig('./ll_output/BED/BED_' + str(int(elapsed_time / outInt)).zfill(zp) + '.png') plt.close()
""" Creates a standarized topography and saves it in the numpy-inherent array format. Therefore needs numpy to work.""" ## Import necessary Python and Landlab Modules import numpy as np from matplotlib import pyplot as plt from landlab import RasterModelGrid from landlab import imshow_grid ncols = 101 nrows = 101 dx = 100 #creates landlab grid out of ncols and nrows to get the right amount of nodes #spacing. could also do completely with numpy but thats easier... mg = RasterModelGrid((nrows, ncols), dx) #creates random array with size of mg-grid topoSeed = np.random.rand(mg.at_node.size) / 100 #saves topoSeed as numpy array np.save('topoSeed', topoSeed) plt.figure() imshow_grid(mg, topoSeed) plt.savefig('initalTopo.png') plt.close() print('------------------------------') print('Saved a output-topography to file topoSeed.npy') print('Saved a picture of the topography to initialTopo.png') print('------------------------------')
#%% Add cumulative quantities to the grid Qbc_cum = mg.add_zeros('node', 'cumulative__base_flow') Qbc_cum[:] = Qbc_cumulative Qsc_cum = mg.add_zeros('node', 'cumulative__surface_runoff') Qsc_cum[:] = Qsc_cumulative Taub_cum = mg.add_zeros('node', 'cumulative__shear_stress') Taub_cum[:] = Taub_cumulative #%% Plot cumulative quantities plt.figure() imshow_grid(mg, 'cumulative__base_flow', colorbar_label='Cumulative baseflow $[m^3]$') plt.figure() imshow_grid(mg, 'cumulative__surface_runoff', colorbar_label='Cumulative surface flow $[m^3]$') plt.figure() imshow_grid(mg, 'cumulative__shear_stress', colorbar_label='Cumulative shear stress $[N/m^2 \, hr]$') #%% Plots to look at timeseries at one node #node =
print(datetime.datetime.now().time()) mg.add_field('node', 'elevation', zrold, noclobber=False) # Outputs present day elevation mg.add_field('node', 'incision', incise_rate, noclobber=False) # Channels mg.add_field('node', 'channels', is_drainage, noclobber=False) # Incision rate mg.add_field('node', 'sedflux', q_rate, noclobber=False) # Sed flux rate # Visualise results print("Topography") imshow_grid(mg, 'elevation', output=True, plot_name="Topography", cmap='gist_earth', limits=(0, 1000), var_name="Elevation, m ") print("Drainage") imshow_grid(mg, 'channels', output=True, plot_name="Drainage", cmap='gist_earth', limits=(0, 1)) print("Incision Rate") imshow_grid(mg, 'incision', output=True, plot_name="Incision Rate",
#Create boundary conditions of the model grid (either closed or fixed-head) for edge in (mg.nodes_at_left_edge,mg.nodes_at_right_edge, mg.nodes_at_top_edge): mg.status_at_node[edge] = CLOSED_BOUNDARY for edge in (mg.nodes_at_bottom_edge): mg.status_at_node[edge] = FIXED_VALUE_BOUNDARY #Initialize Fastscape fc = FastscapeEroder(mg, K_sp = ksp , m_sp = msp, n_sp = nsp, rainfall_intensity = 1) fr = FlowRouter(mg) lm = DepressionFinderAndRouter(mg) for i in range(nSteps): fr.run_one_step(dt=1) lm.map_depressions() fc.run_one_step(dt=1) mg.at_node['topographic__elevation'][mg.core_nodes] += 0.0002 z = mg.at_node['topographic__elevation'] plt.figure() imshow_grid(mg,z) plt.savefig('test.png') plt.close() np.save('iniTopo',z)
files = sorted(grid_files, key=lambda x: int(x.split('_')[-1][:-3])) iteration = int(files[-1].split('_')[-1][:-3]) try: grid = from_netcdf(files[-1]) except KeyError: grid = read_netcdf(files[-1]) elev = grid.at_node['topographic__elevation'] base = grid.at_node['aquifer_base__elevation'] wt = grid.at_node['water_table__elevation'] # elevation plt.figure(figsize=(8, 6)) imshow_grid(grid, elev, cmap='gist_earth', colorbar_label='Elevation [m]', grid_units=('m', 'm')) plt.title('ID %d, Iteration %d' % (ID, iteration)) plt.savefig('../post_proc/%s/elev_ID_%d.png' % (base_output_path, ID)) plt.close() ########## Run hydrological model # load parameters and save just this ID (useful because some runs in a group have been redone with diff parameters) try: df_params = pd.read_csv('parameters.csv', index_col=0)[task_id] df_params.to_csv('../post_proc/%s/params_ID_%d.csv' % (base_output_path, ID), index=True) except FileNotFoundError: df_params = pickle.load(open('./parameters.p', 'rb'))
max_elev.append(np.max(mg.at_node['topographic__elevation'][mg.core_nodes])) min_elev.append(np.min(mg.at_node['topographic__elevation'][mg.core_nodes])) #SoilDepth mean_SD.append(np.mean(mg.at_node['soil__depth'][mg.core_nodes])) counter += 1 #print(counter) #Run the output loop every outInt-times if elapsed_time % outInt == 0: print('Elapsed Time:' , elapsed_time,', writing output!') ##Create DEM plt.figure() imshow_grid(mg,'topographic__elevation',grid_units=['m','m'],var_name = 'Elevation',cmap='terrain') plt.savefig('./DEM/DEM_'+str(int(elapsed_time/outInt)).zfill(zp)+'.png') plt.close() ##Create Flow Accumulation Map plt.figure() imshow_grid(mg,fr.drainage_area,grid_units=['m','m'],var_name = 'Drainage Area',cmap='bone') plt.savefig('./ACC/ACC_'+str(int(elapsed_time/outInt)).zfill(zp)+'.png') plt.close() ##Create Slope - Area Map plt.figure() plt.loglog(mg.at_node['drainage_area'][np.where(mg.at_node['drainage_area'] > 0)], mg.at_node['topographic__steepest_slope'][np.where(mg.at_node['drainage_area'] > 0)], marker='.',linestyle='None') plt.xlabel('Area') plt.ylabel('Slope')
def plot_tidal_flow(grid, resample=1): (ebb_x, ebb_y, flood_x, flood_y, ebb, flood) = map_velocity_components_to_nodes(grid) # depth plt.figure() imshow_grid(grid, grid.at_node['mean_water__depth'], cmap='YlGnBu', color_for_closed='g') plt.title('Water depth (m)') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)') # down-sample for legible quiver plots if needed if resample != 1: xr = grid.x_of_node.reshape( (grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] yr = grid.y_of_node.reshape( (grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] ebb_xr = ebb_x.reshape( (grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] ebb_yr = ebb_y.reshape( (grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] fld_xr = flood_x.reshape( (grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] fld_yr = flood_y.reshape( (grid.number_of_node_rows, grid.number_of_node_columns))[::resample, ::resample] else: xr = grid.x_of_node yr = grid.y_of_node ebb_xr = ebb_x ebb_yr = ebb_y fld_xr = flood_x fld_yr = flood_y # ebb tide plt.figure() imshow_grid(grid, grid.at_node['topographic__elevation']) plt.quiver(xr, yr, ebb_xr, ebb_yr) plt.title('Ebb Tide') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)') ebb_vel_magnitude = ebb plt.figure() imshow_grid(grid, ebb_vel_magnitude, cmap='magma', color_for_closed='g') plt.title('Ebb Tide Velocity Magnitude (m/s)') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)') # flood tide plt.figure() imshow_grid(grid, grid.at_node['topographic__elevation']) plt.quiver(xr, yr, fld_xr, fld_yr) plt.title('Flood Tide') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)') plt.figure() flood_vel_magnitude = flood imshow_grid(grid, flood_vel_magnitude, cmap='magma', color_for_closed='g') plt.title('Flood Tide Velocity Magnitude (m/s)') plt.xlabel('Distance (m)') plt.ylabel('Distance (m)')
#SoilDepth mean_SD.append(np.mean(mg.at_node['soil__depth'][mg.core_nodes])) counter += 1 #print(counter) #Run the output loop every outInt-times if elapsed_time % outInt == 0: print('Elapsed Time:', elapsed_time, ', writing output!') ##Create DEM plt.figure() imshow_grid(mg, 'topographic__elevation', grid_units=['m', 'm'], var_name='Elevation', cmap='terrain') plt.savefig('./DEM/DEM_' + str(int(elapsed_time / outInt)).zfill(zp) + '.png') plt.close() ##Create Flow Accumulation Map plt.figure() imshow_grid(mg, fr.drainage_area, grid_units=['m', 'm'], var_name='Drainage Area', cmap='bone') plt.savefig('./ACC/ACC_' + str(int(elapsed_time / outInt)).zfill(zp) + '.png') plt.close()
print ti/1000., 'kyr elapsed; ', np.mean(zr-zr_last) / dt * 1E6, \ 'um/yr surface uplift' print "Convergence reached! Landscape is at steady state." A = mg.at_node['drainage_area']#[not_edge] A = A.reshape(ncells_side, ncells_side) S = mg.at_node['topographic__steepest_slope'] S = S.reshape(ncells_side, ncells_side) np.savetxt('Synthetic_data/z.txt', zr, fmt='%.2f') np.savetxt('Synthetic_data/A.txt', A, fmt='%d') np.savetxt('Synthetic_data/S.txt', S, fmt='%.5f') # Do some plotting. First the topography: plt.figure('topo ') imshow_grid(mg, 'topographic__elevation', grid_units=('m', 'm'), var_name='Elevation (m)') #plt.title(title_text) plt.tight_layout() #edge = np.unique(mg.neighbors_at_node[mg.boundary_nodes, :]) #not_edge = np.in1d(mg.nodes.flatten(), edge, assume_unique=True, # invert=True) # Inner cells for slope--area diagram plt.figure('S-A') plt.loglog(A[5:-5, 5:-5], S[5:-5, 5:-5], 'kx') #xlim([1.e3, 1.e7]) plt.ylabel('Topographic slope', fontsize=16) plt.xlabel('Drainage area (m^2)', fontsize=16) #plt.title(title_text)
for metric in output_bundle: fp.write(str(metric) + '\n') cur_working = os.getcwd() cur_working_split = cur_working.split(os.path.sep) cur_working_split.append('png') try: cut_ind = cur_working_split.index('results') + 3 except: cut_ind = cur_working_split.index('study3py') + 3 fig_name = '.'.join(cur_working_split[cut_ind:]) imshow_grid(model.grid, model.z, vmin=1230, vmax=1940, cmap='viridis', output=fig_name) usage = resource.getrusage(resource.RUSAGE_SELF) usage_file.write('\n\nUsage At End of Job: \n') for name, desc in [ ('ru_utime', 'User time'), ('ru_stime', 'System time'), ('ru_maxrss', 'Max. Resident Set Size'), ('ru_ixrss', 'Shared Memory Size'), ('ru_idrss', 'Unshared Memory Size'), ('ru_isrss', 'Stack Size'), ('ru_inblock', 'Block inputs'), ('ru_oublock', 'Block outputs'), ]: