def initialize(self, param_filename): # Read parameters from input file params = load_params(param_filename) self.elastic_thickness = params['elastic_thickness'] self.youngs_modulus = params['youngs_modulus'] self.rho_m = params['mantle_density'] self.grav_accel = params['gravitational_acceleration'] self.water_surf_elev = params['water_surface_elevation'] self.water_density = params['lake_water_density'] self.tolerance = params['lake_elev_tolerance'] # Read DEM print('Reading DEM file...') (self.grid, self.dem) = read_esri_ascii(params['dem_filename']) print('done.') # Store a copy that we'll modify self.flexed_dem = self.dem.copy() # Create and initialize Flexure component self.flexer = Flexure(self.grid, eet=self.elastic_thickness, youngs=self.youngs_modulus, method="flexure", rho_mantle=self.rho_m, gravity=self.grav_accel) self.load = self.grid.at_node[ 'lithosphere__overlying_pressure_increment'] self.deflection = self.grid.at_node[ 'lithosphere_surface__elevation_increment'] self.initialized = True
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 initialize(self, filename=None): """Initialize the GrainHill model. Parameters ---------- filename : str, optional Path to name of input file, or dict. """ if isinstance(filename, str): p = load_params(filename) elif isinstance(filename, dict): p = filename else: p = _DEFAULT_PARAMETERS if ('number_of_node_rows' in p and 'number_of_node_columns' in p): p['grid_size'] = (p['number_of_node_rows'], p['number_of_node_columns']) p.pop('number_of_node_rows') p.pop('number_of_node_columns') # Handle model type if 'model_type' in p: model_type = p.pop('model_type') else: model_type = 'grain_hill' # Instantiate model and get handle to grid if 'block' in model_type.lower(): self._model = BlockHill(**p) elif 'facet' in model_type.lower(): self._model = GrainFacetSimulator(**p) else: self._model = GrainHill(**p) self.grid = self._model.grid # Landlab grid as public attribute self._values = {"node_state": self.grid.at_node['node_state']} self._var_units = {"node_state": "-"} self._var_loc = {"node_state": "node"} self._grids = {0: ["node_state"]} self._grid_type = { 0: "unstructured" } # closest BMI category to hexagona self._initialized = True
def initialize(self, filename=None): """Initialize the MarshMorphoBmi model. Parameters ---------- filename : str, optional Path to name of input file, or dict. """ if isinstance(filename, str): p = load_params(filename) elif isinstance(filename, dict): p = filename else: p = _DEFAULT_PARAMETERS if ('number_of_node_rows' in p and 'number_of_node_columns' in p): p['grid_size'] = (p['number_of_node_rows'], p['number_of_node_columns']) p.pop('number_of_node_rows') p.pop('number_of_node_columns') # Instantiate model and get handle to grid self._model = MarshMorphoModel(**p) self.grid = self._model.grid # Landlab grid as public attribute
def main(): parser = argparse.ArgumentParser() parser.add_argument('loads', type=argparse.FileType('r'), help='loading file') parser.add_argument('--params', type=argparse.FileType('r'), help='parameter file') args = parser.parse_args() loads = np.loadtxt(args.loads) params = load_params(args.params) spacing = params.pop('spacing', [1., 1.]) grid = RasterModelGrid(loads.shape, spacing=spacing) grid.at_node['lithosphere__overlying_pressure_increment'] = loads flexure = Flexure(grid, **params) flexure.update() dz = grid.at_node['lithosphere_surface__elevation_increment'] np.savetxt(sys.stdout, dz.reshape(grid.shape))
get_edge_cell_ids, set_pft_at_cells, plot_marked_cells, get_fr_seeds) #from fires_csdms_2017 import create_fires from landlab.components import SpatialDisturbance import pickle import warnings warnings.filterwarnings("ignore") # Create dictionary that holds the inputs results_main_folder = 'E:\Disturbance_results' sub_fldr_name = 'sample_disturbance_run' #sample run for control case (Fig 7) P_factor = 1.0 #precipitation multiplier used to simulate climate change data = load_params('input_disturbance_new.yaml') # Fires Inputs fires = data['fires'] # If 1 -> It will execute creat_fires() algorithm grazing = data['grazing'] # If 1 -> It will execute grazing n_years = data['n_years'] # Approx number of years for model to run yr_step = data['yr_step'] # Year step to plot data # Create RasterModelGrids nrows = data['nrows'] ncols = data['ncols'] dx = data['dx'] dy = data['dy'] grid1 = RasterModelGrid((nrows, ncols), spacing=(dx, dy)) grid = RasterModelGrid((5, 4), spacing=(dx, dy))
@author: Sai Nudurupati & Erkan Istanbulluoglu """ import os #import time import numpy as np from landlab import RasterModelGrid, load_params from ecohyd_functions_flat import (initialize, empty_arrays, create_pet_lookup, calc_veg_cov, plot_veg_cov) grid1 = RasterModelGrid((100, 100), spacing=(5., 5.)) # (285, 799) grid = RasterModelGrid((5, 4), spacing=(5., 5.)) results_main_folder = 'E:\Figure_3' # Enter the path where you want the results to be written sub_fldr_name = 'demo' data = load_params('input_file.yaml') (precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass, soil_moisture, vegetation, vegca) = initialize(data, grid, grid1) n_years = 101 # Approx number of years for model to run yr_step = 50 # Calculate approximate number of storms per year fraction_wet = (data['doy__end_of_monsoon'] - data['doy__start_of_monsoon']) / 365. fraction_dry = 1 - fraction_wet no_of_storms_wet = 8760 * fraction_wet / (data['mean_interstorm_wet'] + data['mean_storm_wet']) no_of_storms_dry = 8760 * fraction_dry / (data['mean_interstorm_dry'] + data['mean_storm_dry'])
from ecohyd_functions_flat_coupled import (initialize, empty_arrays, create_pet_lookup, calc_veg_cov, plot_veg_cov, save_np_files, add_trees, add_shrubs, get_edge_cell_ids, set_pft_at_cells, plot_marked_cells, get_fr_seeds) #from fires_csdms_2017 import create_fires from landlab.components import SpatialDisturbance import pickle import warnings warnings.filterwarnings("ignore") # Create dictionary that holds the inputs data = load_params('ch_146_tr_sh.yaml') sim_type = 'output_fire_return_period' output_sub_fldr = 'ch_146_tr_sh_1_100yr' # Output subfolder name #data = load_params(sys.argv[1]+'.yaml') #sim_type = 'output_fire_return_period' #output_sub_fldr = sys.argv[1]+'1_100yr' # Output subfolder name #print(output_sub_fldr) #print(data['min_fr_shrubs']) #print(data['max_fr_shrubs']) # Fires Inputs fires = data['fires'] # If 1 -> It will execute creat_fires() algorithm grazing = data['grazing'] # If 1 -> It will execute grazing n_years = data['n_years'] # Approx number of years for model to run yr_step = data['yr_step'] # Year step to plot data
def run_ecohydrology_model(grid, input_data, input_file, synthetic_storms=True, number_of_storms=None, number_of_years=None, first_julian_day_of_observations=0, pet_method='Cosine', save_files=False, sim_name='Trial'): # Create data object by reading in the input_file data = load_params(input_file) # Create a grid that can hold enough cells to represent all individual # vegetation types grid_veg = rmg((5, 4), spacing=(5., 5.)) if pet_method == 'Cosine': (precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass, soil_moisture, vegetation, vegca) = initialize_components(data, grid_veg, grid, pet_method='Cosine') elif pet_method == 'PriestleyTaylor': (precip_dry, precip_wet, radiation, pet_met, soil_moisture, vegetation, vegca) = initialize_components(data, grid_veg, grid, pet_method='PriestleyTaylor') if number_of_years != None: # Calculate approximate number of storms per year fraction_wet = ( (data['doy__end_of_monsoon'] - data['doy__start_of_monsoon']) / 365.) fraction_dry = (1 - fraction_wet) number_of_storms_wet = ( 8760 * (fraction_wet) / (data['mean_interstorm_wet'] + data['mean_storm_wet'])) number_of_storms_dry = ( 8760 * (fraction_dry) / (data['mean_interstorm_dry'] + data['mean_storm_dry'])) number_of_storms = int(number_of_years * (number_of_storms_wet + number_of_storms_dry)) (precip, inter_storm_dt, storm_dt, Time, VegType, pet_arr, Rad_Factor, Rad_Factor_met, EP30, EP30_met, pet_threshold) = create_empty_arrays(number_of_storms, grid_veg, grid, pet_method=pet_method) if pet_method == 'Cosine': (pet_arr, EP30) = create_pet_lookup(grid_veg, radiation=radiation, Rad_Factor=Rad_Factor, EP30=EP30, pet_tree=pet_tree, pet_shrub=pet_shrub, pet_grass=pet_grass, pet_arr=pet_arr) if pet_method == 'PriestleyTaylor': (pet_arr, EP30_met) = create_pet_lookup( grid_veg, radiation=radiation, Rad_Factor_met=Rad_Factor_met, number_of_storms=number_of_storms, pet_met=pet_met, Tmax_met=input_data['Tmax_met'], Tmin_met=input_data['Tmin_met'], EP30_met=EP30_met, first_day=first_julian_day_of_observations, pet_method=pet_method, pet_arr=pet_arr) # declaring few variables that will be used in the storm loop current_time = first_julian_day_of_observations / 365.25 # Initial time time_check = 0. # Buffer to store current_time at previous storm yrs = 0 # Keep track of number of years passed water_stress = 0. # Buffer for Water Stress Tg = 0 # Growing season in days # # Run storm Loop for i in range(0, number_of_storms): # Update objects # Calculate Day of Year (DOY) julian = np.int( np.floor((current_time - np.floor(current_time)) * 365.)) if synthetic_storms: # Generate seasonal storms # for Dry season if julian < data['doy__start_of_monsoon'] or julian > data[ 'doy__end_of_monsoon']: precip_dry.update() precip[i] = precip_dry.storm_depth storm_dt[i] = precip_dry.storm_duration inter_storm_dt[i] = precip_dry.interstorm_duration # Wet Season - Jul to Sep - NA Monsoon else: precip_wet.update() precip[i] = precip_wet.storm_depth storm_dt[i] = precip_wet.storm_duration inter_storm_dt[i] = precip_wet.interstorm_duration else: precip[i] = input_data['precip_met'][i] storm_dt[i] = 0. inter_storm_dt[i] = 24. # Spatially distribute PET and its 30-day-mean (analogous to degree day) if pet_method == 'Cosine': grid_veg.at_cell['surface__potential_evapotranspiration_rate'] = ( pet_arr[julian]) grid_veg.at_cell[ 'surface__potential_evapotranspiration_30day_mean'] = ( EP30[julian]) grid_veg.at_cell[ 'surface__potential_evapotranspiration_rate__grass'] = ( np.full(grid_veg.number_of_cells, pet_arr[julian, 0])) elif pet_method == 'PriestleyTaylor': grid_veg.at_cell['surface__potential_evapotranspiration_rate'] = ( pet_arr[i]) grid_veg.at_cell[ 'surface__potential_evapotranspiration_30day_mean'] = ( EP30_met[i]) grid_veg.at_cell[ 'surface__potential_evapotranspiration_rate__grass'] = ( np.full(grid_veg.number_of_cells, pet_arr[i, 0])) # Assign spatial rainfall data grid_veg.at_cell['rainfall__daily_depth'] = (np.full( grid_veg.number_of_cells, precip[i])) # Update soil moisture component current_time = soil_moisture.update(current_time, Tr=storm_dt[i], Tb=inter_storm_dt[i]) # Decide whether its growing season or not if pet_method == 'Cosine': if julian != 364: if EP30[julian + 1, 0] > EP30[julian, 0]: pet_threshold = 1 # 1 corresponds to ETThresholdup (begin growing season) if EP30[julian, 0] > vegetation._ETthresholdup: growing_season = True else: growing_season = False else: pet_threshold = 0 # 0 corresponds to ETThresholddown (end growing season) if EP30[julian, 0] > vegetation._ETthresholddown: growing_season = True else: growing_season = False elif pet_method == 'PriestleyTaylor': if i != number_of_storms - 1: if EP30_met[i + 1, 0] > EP30_met[i, 0]: pet_threshold = 1 # 1 corresponds to ETThresholdup (begin growing season) if EP30_met[i, 0] > vegetation._ETthresholdup: growing_season = True else: growing_season = False else: pet_threshold = 0 # 0 corresponds to ETThresholddown (end growing season) if EP30_met[i, 0] > vegetation._ETthresholddown: growing_season = True else: growing_season = False # Update vegetation component vegetation.update(PETThreshold_switch=pet_threshold, Tb=inter_storm_dt[i], Tr=storm_dt[i]) if growing_season: # Update yearly cumulative water stress data Tg += (storm_dt[i] + inter_storm_dt[i] ) / 24. # Incrementing growing season storm count water_stress += ((grid_veg.at_cell['vegetation__water_stress']) * inter_storm_dt[i] / 24.) # Record time (optional) Time[i] = current_time # Update spatial PFTs with Cellular Automata rules if (current_time - time_check) >= 1.: if yrs % 100 == 0: print('Elapsed time = ', yrs, ' years') VegType[yrs] = grid.at_cell['vegetation__plant_functional_type'] WS_ = np.choose(VegType[yrs], water_stress) grid.at_cell['vegetation__cumulative_water_stress'] = WS_ / Tg vegca.update() time_check = np.floor(current_time) water_stress = 0 yrs += 1 Tg = 0 VegType[yrs] = grid.at_cell['vegetation__plant_functional_type'] if save_files: save_data(sim_name, inter_storm_dt, storm_dt, precip, VegType, yrs, 0, Time) if pet_method == 'Cosine': returns_debug = [ grid_veg, precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass, soil_moisture, vegetation, vegca ] elif pet_method == 'PriestleyTaylor': returns_debug = [ grid_veg, precip_dry, precip_wet, radiation, pet_met, soil_moisture, vegetation, vegca ] return (VegType, yrs - 1, returns_debug)
create_pet_lookup, get_slp_asp_mapping, get_sm_mapper, calc_veg_cov_wtrshd, calc_veg_cov_asp, plot_veg_cov) (grid, elevation) = read_esri_ascii('sev5m_nad27.txt') # Read the DEM grid.set_nodata_nodes_to_closed(elevation, -9999.) # Create a grid to hold combination of 6 veg_types X 9 slope_bins X 12 aspect_bins # therefore, number of cells needed = 648. 83X10 nodal grid - arbitrary # size to give a grid with 648 cells sm_grid = RasterModelGrid((83, 10), spacing=(5., 5.)) # Representative grid # create a grid for radiation factor: 9 slope_bins X 12 aspect_bins = 108 cells rad_grid = RasterModelGrid((14, 11), spacing=(5., 5.)) results_main_folder = 'E:\pub_wrr_ecohyd\ca_dem' # Enter the path where you want the results to be written sub_fldr_name = 'sm_calib_82_lnger_1' data = load_params( 'sm_calib_82.yaml') # Creates dictionary that holds the inputs # sub_fldr_name = sys.argv[1] + '_lnger_1' # data = load_params(sys.argv[1]+'.yaml') # Creates dictionary that holds the inputs (precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass, soil_moisture, vegetation, vegca) = initialize(data, grid, sm_grid, rad_grid, elevation) n_years = 200 # Approx number of years for model to run yr_step = 20 # Step for printing current time # Calculate approximate number of storms per year fraction_wet = (data['doy__end_of_monsoon'] - data['doy__start_of_monsoon']) / 365. fraction_dry = 1 - fraction_wet no_of_storms_wet = (8760 * (fraction_wet) / (data['mean_interstorm_wet'] + data['mean_storm_wet']))
return veg_grid # Point to the input DEM _DEFAULT_INPUT_FILE_1 = os.path.join(os.path.dirname(__file__), 'hugo10mws.txt') """ Importing Grid and Elevations from DEM """ ## For modeled Radiation model (grid,elevation) = read_esri_ascii(_DEFAULT_INPUT_FILE_1) (grid2, elevation) = read_esri_ascii(_DEFAULT_INPUT_FILE_1) grid.at_node['topographic__elevation'] = elevation grid2.at_node['topographic__elevation'] = elevation ## Name of the folder you want to store the outputs sub_fldr_name = 'trial21_runon_strms_wtrshd_veg12_pap' # veg1 flag is for veg compositions data = load_params('trial21_veg12.yaml') # Creates dictionary that holds the inputs runon_switch = 1 #days_n = 1266 nfs_data = pickle.load(open("nfs_daily_storm_analysis.p", "rb")) P_NFS = np.array(nfs_data['storm_depth']) P_NFS = ma.fix_invalid(P_NFS, fill_value=0.).data Tr_NFS = np.array(nfs_data['storm_duration']) Tb_NFS = np.array(nfs_data['inter_storm_duration']) strm_days = nfs_data['storm_start_time'] days_n = int(P_NFS.shape[0]) sfs_data = pickle.load(open("sfs_daily_storm_analysis.p", "rb")) P_SFS = np.array(sfs_data['storm_depth']) P_SFS = ma.fix_invalid(P_SFS, fill_value=0.).data Tr_SFS = np.array(sfs_data['storm_duration'])
from ecohyd_functions_flat_coupled import (initialize, empty_arrays, create_pet_lookup, calc_veg_cov, save_np_files, add_trees, add_shrubs, get_edge_cell_ids, set_pft_at_cells, plot_marked_cells, plot_veg_type, get_fr_seeds) #from fires_csdms_2017 import create_fires from landlab.components import SpatialDisturbance import pickle import warnings warnings.filterwarnings("ignore") # Create dictionary that holds the inputs #data = load_params('clust_59.yaml') #output_sub_fldr = 'clust_59' # Output subfolder name data = load_params(sys.argv[1] + '.yaml') output_sub_fldr = (sys.argv[1] + 'temporal') # Output subfolder name print(output_sub_fldr) # Fires Inputs fires = data['fires'] # If 1 -> It will execute creat_fires() algorithm grazing = data['grazing'] # If 1 -> It will execute grazing n_years = data['n_years'] # Approx number of years for model to run yr_step = data['yr_step'] # Year step to plot data # Create RasterModelGrids nrows = data['nrows'] ncols = data['ncols'] dx = data['dx'] dy = data['dy']
@author: Sai Nudurupati & Erkan Istanbulluoglu """ import os import time import numpy as np from landlab import RasterModelGrid, load_params from ecohyd_functions_flat import (initialize, empty_arrays, create_pet_lookup, calc_veg_cov, plot_veg_cov) grid1 = RasterModelGrid((285, 799), spacing=(5., 5.)) grid = RasterModelGrid((5, 4), spacing=(5., 5.)) results_main_folder = 'E:\pub_wrr_ecohyd\ca_flat' # Enter the path where you want the results to be written sub_fldr_name = 'sim_5m_82_lnger_1' data = load_params('sm_calib_82.yaml') (precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass, soil_moisture, vegetation, vegca) = initialize(data, grid, grid1) n_years = 200 # Approx number of years for model to run yr_step = 20 # Calculate approximate number of storms per year fraction_wet = (data['doy__end_of_monsoon'] - data['doy__start_of_monsoon']) / 365. fraction_dry = 1 - fraction_wet no_of_storms_wet = 8760 * fraction_wet / (data['mean_interstorm_wet'] + data['mean_storm_wet']) no_of_storms_dry = 8760 * fraction_dry / (data['mean_interstorm_dry'] + data['mean_storm_dry'])
m_sp: 0.5 n_sp: 1. rock_density: 2.7 sed_density: 2.7 linear_diffusivity: 0.0001 ''' #%% load and setup parameters: #LENGTH UNITS ARE NOW KM!!! input_file = './landlab_parameters1.txt' inputs = load_params(input_file) # load the data into a dictionary nrows = inputs['nrows'] ncols = inputs['ncols'] dx = inputs['dx'] uplift_rate = inputs['uplift_rate'] total_t = inputs['total_time'] dt = inputs['dt'] nt = int(total_t // dt) #this is how many loops we'll need uplift_per_step = uplift_rate * dt # illustrate what the MPD looks like: print(inputs) #Initiate model domain
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None): """ Handles inputs, sets params. """ # Make sure user has given us an input file or parameter dictionary # (but not both) if input_file is None and params is None: print('You must specify either an input_file or params dict') sys.exit(1) if input_file is not None and params is not None: print('ErosionModel constructor takes EITHER') print('input_file or params, but not both.') sys.exit(1) # If we have an input file, let's read it if input_file is None: self.params = params else: self.params = load_params(input_file) # if a pickled instance exists, load it instead of the standard init. try: self.save_model_name = self.params['pickle_name'] except KeyError: self.save_model_name = 'saved_model.model' # Read the topography data and create a grid if ((self.params.get('number_of_node_rows') is not None) and (self.params.get('DEM_filename') is not None)): raise ValueError( 'Both a DEM filename and number_of_node_rows have ' 'been specified.') try: (self.grid, self.z) = self.read_topography(self.params['DEM_filename'], name='topographic__elevation', halo=1) self.opt_watershed = True except KeyError: # this routine will set self.opt_watershed internally self.setup_rectangular_grid(self.params) try: feet_to_meters = self.params['feet_to_meters'] except KeyError: feet_to_meters = False try: meters_to_feet = self.params['meters_to_feet'] except KeyError: meters_to_feet = False # create prefactor for unit converstion if feet_to_meters and meters_to_feet: raise ValueError('Both "feet_to_meters" and "meters_to_feet" are' 'set as True. This is not realistic.') else: if feet_to_meters: self._length_factor = 1.0 / 3.28084 elif meters_to_feet: self._length_factor = 3.28084 else: self._length_factor = 1.0 # identify if initial conditions should be saved. # default behavior is to not save the first timestep try: self.save_first_timestep = self.params['save_first_timestep'] except KeyError: self.save_first_timestep = False # instantiate model time. self.model_time = 0. # instantiate container for computational timestep: self.compute_time = [tm.time()] # Set DEM boundaries if self.opt_watershed: try: self.outlet_node = self.params['outlet_id'] self.grid.set_watershed_boundary_condition_outlet_id( self.outlet_node, self.z, nodata_value=-9999) except: self.outlet_node = self.grid.set_watershed_boundary_condition( self.z, nodata_value=-9999, return_outlet_id=True) # Add fields for initial topography and cumulative erosion depth z0 = self.grid.add_zeros('node', 'initial_topographic__elevation') z0[:] = self.z # keep a copy of starting elevation self.grid.add_zeros('node', 'cumulative_erosion__depth') # identify which nodes are data nodes: self.data_nodes = self.grid.at_node['topographic__elevation'] != -9999. # Read and remember baselevel control param, if present try: self.outlet_lowering_rate = self.params['outlet_lowering_rate'] except KeyError: self.outlet_lowering_rate = 0.0 # Read and remember baselevel control param, if present try: file_name = self.params['outlet_lowering_file_path'] modern_outlet_elevation = self.params['modern_outlet_elevation'] postglacial_outlet_elevation = self.z[self.outlet_node] elev_change_df = np.loadtxt(file_name, skiprows=1, delimiter=',') time = elev_change_df[:, 0] elev_change = elev_change_df[:, 1] scaling_factor = np.abs(postglacial_outlet_elevation - modern_outlet_elevation) / np.abs( elev_change[0] - elev_change[-1]) outlet_elevation = (scaling_factor * elev_change_df[:, 1] ) + postglacial_outlet_elevation self.outlet_elevation_obj = interp1d(time, outlet_elevation) except KeyError: #self.outlet_lowering_rate = 0.0 self.outlet_elevation_obj = None if BaselevelHandlerClass is None: self.baselevel_handler = None else: self.baselevel_handler = BaselevelHandlerClass( self.grid, self.params) # Handle option for time-varying precipitation try: self.opt_var_precip = self.params['opt_var_precip'] except KeyError: self.opt_var_precip = False if self.opt_var_precip: self.setup_time_varying_precip() # Handle option to save if walltime is to short self.opt_save = self.params.get('opt_save') or False
from landlab.components import PotentialEvapotranspiration from landlab.components import SoilMoisture from landlab.components import Vegetation from landlab.components import VegCA import matplotlib as mpl #from matplotlib.axes import * import time # GRASS = 0; SHRUB = 1; TREE = 2; BARE = 3; # SHRUBSEEDLING = 4; TREESEEDLING = 5 ## Point to the input DEM _DEFAULT_INPUT_FILE_1 = os.path.join(os.path.dirname(__file__), 'DEM_10m.asc') data = load_params('trial_17.yaml') # Create dictionary that holds the inputs # Name of the folder you want to store the outputs sub_fldr_name = 'trial_17_copy_1' ## Importing Grid and Elevations from DEM (grid1,elevation) = read_esri_ascii(_DEFAULT_INPUT_FILE_1) grid1['node']['topographic__elevation'] = elevation grid = rmg(5,4,5) grid['node']['topographic__elevation'] = 1700. * np.ones(grid.number_of_nodes) grid1['cell']['vegetation__plant_functional_type'] = ( np.random.randint(0,6,grid1.number_of_cells)) grid['cell']['vegetation__plant_functional_type'] = np.arange(0,6) mat_data = scipy.io.loadmat('Sailow.mat') ObsYearsB = mat_data['YearsB'] # Observed LAI low years
import os import time import numpy as np from landlab import RasterModelGrid, load_params from ecohyd_functions_flat import (initialize, empty_arrays, create_pet_lookup, save, plot) grid1 = RasterModelGrid((100, 100), spacing=(5., 5.)) grid = RasterModelGrid((5, 4), spacing=(5., 5.)) # Create dictionary that holds the inputs data = load_params('inputs_vegetation_ca.yaml') (precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass, soil_moisture, vegetation, vegca) = initialize(data, grid, grid1) n_years = 2000 # Approx number of years for model to run # Calculate approximate number of storms per year fraction_wet = (data['doy__end_of_monsoon'] - data['doy__start_of_monsoon']) / 365. fraction_dry = 1 - fraction_wet no_of_storms_wet = 8760 * fraction_wet / (data['mean_interstorm_wet'] + data['mean_storm_wet']) no_of_storms_dry = 8760 * fraction_dry / (data['mean_interstorm_dry'] + data['mean_storm_dry']) n = int(n_years * (no_of_storms_wet + no_of_storms_dry))
import sys import numpy as np from landlab.io import read_esri_ascii from landlab import RasterModelGrid, load_params from ecohyd_functions_dem_bins import (initialize, empty_arrays, create_pet_lookup, get_slp_asp_mapping, get_sm_mapper, calc_veg_cov_wtrshd, calc_veg_cov_asp, plot_veg_cov) n_years = 501 # Approx number of years for model to run yr_step = 100 # Step for printing current time use_preloaded_pft = 0 # 1 if we want to use an existing PFT map to start with a vegtype_.npy file. results_main_folder = 'E:\Figure_3' # Enter the path where you want the results to be written sub_fldr_name = 'sample_run_DEM' data = load_params( 'input_file.yaml') # Creates dictionary that holds the inputs # sub_fldr_name = sys.argv[1] + '_lnger_1' # data = load_params(sys.argv[1]+'.yaml') # Creates dictionary that holds the inputs (grid, elevation) = read_esri_ascii( 'sev5m_nad27.txt' ) # Read the DEM sev5m_nad27.txt (285, 799) hugo10mws.txt OR hugo5m_wgs84.txt (98 148) grid.set_nodata_nodes_to_closed(elevation, -9999.) # Create a grid to hold combination of 6 veg_types X 9 slope_bins X 12 aspect_bins # therefore, number of cells needed = 648. 83X10 nodal grid - arbitrary # size to give a grid with 648 cells sm_grid = RasterModelGrid((83, 10), (5., 5.)) # Representative grid # create a grid for radiation factor: 9 slope_bins X 12 aspect_bins = 108 cells rad_grid = RasterModelGrid((14, 11), (5., 5.)) (precip_dry, precip_wet, radiation, pet_tree, pet_shrub, pet_grass,