def initialize(self, input_file=None): MPD = ModelParameterDictionary() """We imported methods from ModelParameterDictionary to read the parameters from the input file. Necessary parameters to run this code include: mean_storm (type: float) mean_intensity (type: float) mean_interstorm (type: float) mean_storm_depth is calculated using mean storm and intensity data The random variables of storm_duration, interstorm_duration, storm_depth and intensity are found using methods declared later in the class """ if input_file is None: input_file = _DEFAULT_INPUT_FILE MPD.read_from_file(input_file) self.mean_storm = MPD.read_float("MEAN_STORM") self.mean_interstorm = MPD.read_float("MEAN_INTERSTORM") self.mean_storm_depth = MPD.read_float("MEAN_DEPTH") self.mean_intensity = self.mean_storm_depth / self.mean_storm self.storm_duration = self.get_precipitation_event_duration() self.interstorm_duration = self.get_interstorm_event_duration() self.storm_depth = self.get_storm_depth() self.intensity = self.get_storm_intensity() self.run_time = MPD.read_float("RUN_TIME") try: #DEJH thinks this is redundant self.delta_t = MPD.read_int("DELTA_T") except: pass
def test_tl_fluvial(): input_file = os.path.join(_THIS_DIR, 'stream_power_params_ideal.txt') inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('uplift_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime // dt) uplift_per_step = uplift_rate * dt mg = RasterModelGrid(nrows, ncols, dx) mg.add_zeros('node', 'topographic__elevation') z = np.loadtxt(os.path.join(_THIS_DIR, 'tl_init.txt')) mg['node']['topographic__elevation'] = z mg.set_closed_boundaries_at_grid_edges(True, False, True, False) mg.set_fixed_value_boundaries_at_grid_edges( False, True, False, True, value_of='topographic__elevation') fr = FlowRouter(mg) tl = TransportLimitedEroder(mg, input_file) for i in range(nt): mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step mg = fr.route_flow() mg, _ = tl.erode(mg, dt, stability_condition='loose') z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'tlz_tg.txt')) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_tg)
def test_tl_fluvial(): input_file = os.path.join(_THIS_DIR, 'stream_power_params_ideal.txt') inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('uplift_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime // dt) uplift_per_step = uplift_rate * dt mg = RasterModelGrid(nrows, ncols, dx) mg.add_zeros('node', 'topographic__elevation') z = np.loadtxt(os.path.join(_THIS_DIR, 'tl_init.txt')) mg['node']['topographic__elevation'] = z mg.set_closed_boundaries_at_grid_edges(True, False, True, False) mg.set_fixed_value_boundaries_at_grid_edges( False, True, False, True, value_of='topographic__elevation') fr = FlowRouter(mg) tl = TransportLimitedEroder(mg, input_file) for i in range(nt): mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step mg = fr.route_flow() mg, _ = tl.erode(mg, dt, stability_condition='loose') z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'tlz_tg.txt')) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_tg)
def test_storms(): input_file_string = os.path.join(_THIS_DIR, 'drive_sp_params_storms.txt') inputs = ModelParameterDictionary(input_file_string) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') mg = RasterModelGrid(nrows, ncols, dx) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.add_zeros('water__unit_flux_in', at='node') precip = PrecipitationDistribution(input_file=input_file_string) fr = FlowRouter(mg) sp = StreamPowerEroder(mg, **inputs) for (interval_duration, rainfall_rate) in \ precip.yield_storm_interstorm_duration_intensity(): if rainfall_rate != 0.: mg.at_node['water__unit_flux_in'].fill(rainfall_rate) mg = fr.route_flow() sp.run_one_step(dt) mg.at_node['topographic__elevation'][ mg.core_nodes] += uplift * interval_duration
def test_storms(): input_file_string = os.path.join(_THIS_DIR, 'drive_sp_params_storms.txt') inputs = ModelParameterDictionary(input_file_string) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') mg = RasterModelGrid(nrows, ncols, dx) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.add_zeros('water__unit_flux_in', at='node') precip = PrecipitationDistribution(input_file=input_file_string) fr = FlowRouter(mg) sp = StreamPowerEroder(mg, **inputs) for (interval_duration, rainfall_rate) in \ precip.yield_storm_interstorm_duration_intensity(): if rainfall_rate != 0.: mg.at_node['water__unit_flux_in'].fill(rainfall_rate) mg = fr.route_flow() sp.run_one_step(dt) mg.at_node['topographic__elevation'][ mg.core_nodes] += uplift * interval_duration
def initialize( self, shape ): """ Read Input File """ MPD = ModelParameterDictionary() MPD.read_from_file(_DEFAULT_INPUT_FILE) """ Read Input Parameters """ self._iterate_storm = MPD.read_int( 'N_STORMS' ) self._vegcover = MPD.read_float( 'VEG_COV' ) self._interception_cap = MPD.read_float( 'INTERCEPT_CAP' ) self._zr = MPD.read_float( 'ZR' ) self._runon = MPD.read_float( 'RUNON' ) self._fbare = MPD.read_float( 'F_BARE' ) self._soil_Ib = MPD.read_float( 'I_B' ) self._soil_Iv = MPD.read_float( 'I_V' ) self._soil_Ew = MPD.read_float( 'EW' ) self._soil_pc = MPD.read_float( 'PC' ) self._soil_fc = MPD.read_float( 'FC' ) self._soil_sc = MPD.read_float( 'SC' ) self._soil_wp = MPD.read_float( 'WP' ) self._soil_hgw = MPD.read_float( 'HGW' ) self._soil_beta = MPD.read_float( 'BETA' ) self._so = MPD.read_float( 'so' ) self._ETA = zeros(shape) self._S = zeros(shape) self._D = zeros(shape) self._Ro = zeros(shape) self._WS = zeros(shape) self._SO = self._so * ones(shape)
def test_sed_dep(): input_file = os.path.join(_THIS_DIR, "sed_dep_params.txt") inputs = ModelParameterDictionary(input_file, auto_type=True) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") uplift_rate = inputs.read_float("uplift_rate") runtime = inputs.read_float("total_time") dt = inputs.read_float("dt") nt = int(runtime // dt) uplift_per_step = uplift_rate * dt mg = RasterModelGrid((nrows, ncols), xy_spacing=(dx, dx)) mg.add_zeros("topographic__elevation", at="node") z = np.loadtxt(os.path.join(_THIS_DIR, "seddepinit.txt")) mg["node"]["topographic__elevation"] = z mg.set_closed_boundaries_at_grid_edges(True, False, True, False) fr = FlowAccumulator(mg, flow_director="D8") sde = SedDepEroder(mg, **inputs) for i in range(nt): mg.at_node["topographic__elevation"][mg.core_nodes] += uplift_per_step mg = fr.run_one_step() mg, _ = sde.erode(dt) z_tg = np.loadtxt(os.path.join(_THIS_DIR, "seddepz_tg.txt")) assert_array_almost_equal( mg.at_node["topographic__elevation"][mg.core_nodes], z_tg[mg.core_nodes] )
def test_sed_dep(): input_file = os.path.join(_THIS_DIR, "sed_dep_params.txt") inputs = ModelParameterDictionary(input_file, auto_type=True) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") uplift_rate = inputs.read_float("uplift_rate") runtime = inputs.read_float("total_time") dt = inputs.read_float("dt") nt = int(runtime // dt) uplift_per_step = uplift_rate * dt mg = RasterModelGrid((nrows, ncols), xy_spacing=(dx, dx)) mg.add_zeros("topographic__elevation", at="node") z = np.loadtxt(os.path.join(_THIS_DIR, "seddepinit.txt")) mg["node"]["topographic__elevation"] = z mg.set_closed_boundaries_at_grid_edges(True, False, True, False) fr = FlowAccumulator(mg, flow_director="D8") sde = SedDepEroder(mg, **inputs) for i in range(nt): mg.at_node["topographic__elevation"][mg.core_nodes] += uplift_per_step mg = fr.run_one_step() mg, _ = sde.erode(dt) z_tg = np.loadtxt(os.path.join(_THIS_DIR, "seddepz_tg.txt")) assert_array_almost_equal( mg.at_node["topographic__elevation"][mg.core_nodes], z_tg[mg.core_nodes])
def __init__(self, input_file=None, mean_storm=None, mean_interstorm=None, mean_storm_depth=None, total_t=None, delta_t=None): """ This reads in information from the input_file (either default or user assigned, and creates an instantaneous storm event drawn from the Poisson distribution """ # First we create an instance of the Model Parameter Dictionary MPD = ModelParameterDictionary() # If no input_file is given,the default file is used if input_file is None: input_file = _DEFAULT_INPUT_FILE # This reads in the file information MPD.read_from_file(input_file) # And now we set our different parameters # using the model parameter dictionary... if mean_storm == None: self.mean_storm = MPD.read_float( 'MEAN_STORM') else: self.mean_storm = mean_storm if mean_interstorm == None: self.mean_interstorm = MPD.read_float( 'MEAN_INTERSTORM') else: self.mean_interstorm =mean_interstorm if mean_storm_depth== None: self.mean_storm_depth = MPD.read_float( 'MEAN_DEPTH') else: self.mean_storm_depth =mean_storm_depth if total_t== None: self.run_time = MPD.read_float( 'RUN_TIME') else: self.run_time =total_t if delta_t== None: self.delta_t = MPD.read_int( 'DELTA_T') else: self.detla_t =delta_t # Mean_intensity is not set by the MPD, but can be drawn from # the mean storm depth and mean storm duration. self.mean_intensity = self.mean_storm_depth / self.mean_storm # If a time series is created later, this blank list will be used. self.storm_time_series =[] # Given the mean values assigned above using either the model # parameter dictionary or the init function, we can call the # different methods to assign values from the Poisson distribution. self.storm_duration = self.get_precipitation_event_duration() self.interstorm_duration = self.get_interstorm_event_duration() self.storm_depth = self.get_storm_depth() self.intensity = self.get_storm_intensity()
def test_sp_new(): """ Tests new style component instantiation and run. """ input_str = os.path.join(_THIS_DIR, 'drive_sp_params.txt') inputs = ModelParameterDictionary(input_str, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), spacing=(dx, dx)) mg.set_closed_boundaries_at_grid_edges(False, False, True, True) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev numpy.random.seed(0) mg['node']['topographic__elevation'] = z + \ numpy.random.rand(len(z)) / 1000. fr = FlowRouter(mg) sp = StreamPowerEroder(mg, **inputs) elapsed_time = 0. while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time fr.route_flow() sp.run_one_step(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift * dt elapsed_time += dt z_trg = numpy.array([5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 1.02783376e-02, 9.66667235e-03, 6.15060782e-03, 3.83441519e-04, 7.91725038e-04, 1.00905776e-02, 8.98955843e-03, 5.32836181e-03, 7.10360582e-05, 8.71292997e-05, 9.96377080e-03, 9.63738797e-03, 7.31213677e-03, 8.70012148e-04, 9.78618342e-04, 1.02124693e-02, 8.78386002e-03, 4.88161060e-03, 1.18274426e-04, 6.39921021e-04, 1.00377580e-02, 9.54340293e-03, 6.05173814e-03, 4.14661940e-04, 2.64555612e-04, 1.02160196e-02, 8.61600088e-03, 4.77005225e-03, 1.87898004e-05, 6.17635497e-04, 9.30445558e-03, 9.48713993e-03, 7.25689742e-03, 6.81820299e-04, 3.59507901e-04, 5.79161813e-03, 6.83777542e-03, 6.18063842e-03, 6.66766715e-04, 6.70637870e-04, 2.10382561e-04, 1.28926298e-04, 3.15428351e-04, 3.63710771e-04]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_trg)
def test_sp_new(): """ Tests new style component instantiation and run. """ input_str = os.path.join(_THIS_DIR, 'drive_sp_params.txt') inputs = ModelParameterDictionary(input_str, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), spacing=(dx, dx)) mg.set_closed_boundaries_at_grid_edges(False, False, True, True) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev numpy.random.seed(0) mg['node']['topographic__elevation'] = z + \ numpy.random.rand(len(z)) / 1000. fr = FlowRouter(mg) sp = StreamPowerEroder(mg, **inputs) elapsed_time = 0. while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time fr.route_flow() sp.run_one_step(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift * dt elapsed_time += dt z_trg = numpy.array([5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 1.01830760e-02, 9.58036770e-03, 6.55865452e-03, 3.83441519e-04, 7.91725038e-04, 1.00142749e-02, 8.80798884e-03, 5.78387585e-03, 7.10360582e-05, 8.71292997e-05, 9.81911417e-03, 9.52243406e-03, 7.55093226e-03, 8.70012148e-04, 9.78618342e-04, 1.00629755e-02, 8.49253798e-03, 5.33216680e-03, 1.18274426e-04, 6.39921021e-04, 9.88956320e-03, 9.47119567e-03, 6.43790696e-03, 4.14661940e-04, 2.64555612e-04, 1.00450743e-02, 8.37262908e-03, 5.21540904e-03, 1.87898004e-05, 6.17635497e-04, 9.21286940e-03, 9.34022513e-03, 7.51114450e-03, 6.81820299e-04, 3.59507901e-04, 6.19166921e-03, 7.10456176e-03, 6.62585507e-03, 6.66766715e-04, 6.70637870e-04, 2.10382561e-04, 1.28926298e-04, 3.15428351e-04, 3.63710771e-04]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_trg)
def test_sp_new(): """ Tests new style component instantiation and run. """ input_str = os.path.join(_THIS_DIR, 'drive_sp_params.txt') inputs = ModelParameterDictionary(input_str, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), spacing=(dx, dx)) mg.set_closed_boundaries_at_grid_edges(False, False, True, True) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev numpy.random.seed(0) mg['node']['topographic__elevation'] = z + \ numpy.random.rand(len(z)) / 1000. fr = FlowAccumulator(mg, flow_director='D8') sp = StreamPowerEroder(mg, **inputs) elapsed_time = 0. while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time fr.run_one_step() sp.run_one_step(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift * dt elapsed_time += dt z_trg = numpy.array([ 5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 1.01830760e-02, 9.58036770e-03, 6.55865452e-03, 3.83441519e-04, 7.91725038e-04, 1.00142749e-02, 8.80798884e-03, 5.78387585e-03, 7.10360582e-05, 8.71292997e-05, 9.81911417e-03, 9.52243406e-03, 7.55093226e-03, 8.70012148e-04, 9.78618342e-04, 1.00629755e-02, 8.49253798e-03, 5.33216680e-03, 1.18274426e-04, 6.39921021e-04, 9.88956320e-03, 9.47119567e-03, 6.43790696e-03, 4.14661940e-04, 2.64555612e-04, 1.00450743e-02, 8.37262908e-03, 5.21540904e-03, 1.87898004e-05, 6.17635497e-04, 9.21286940e-03, 9.34022513e-03, 7.51114450e-03, 6.81820299e-04, 3.59507901e-04, 6.19166921e-03, 7.10456176e-03, 6.62585507e-03, 6.66766715e-04, 6.70637870e-04, 2.10382561e-04, 1.28926298e-04, 3.15428351e-04, 3.63710771e-04 ]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_trg)
def test_sp_new(): """ Tests new style component instantiation and run. """ input_str = os.path.join(_THIS_DIR, 'drive_sp_params.txt') inputs = ModelParameterDictionary(input_str, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), spacing=(dx, dx)) mg.set_closed_boundaries_at_grid_edges(False, False, True, True) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev numpy.random.seed(0) mg['node']['topographic__elevation'] = z + \ numpy.random.rand(len(z)) / 1000. fr = FlowRouter(mg) sp = StreamPowerEroder(mg, **inputs) elapsed_time = 0. while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time fr.route_flow() sp.run_one_step(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift * dt elapsed_time += dt z_trg = numpy.array([ 5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 1.02783376e-02, 9.66667235e-03, 6.15060782e-03, 3.83441519e-04, 7.91725038e-04, 1.00905776e-02, 8.98955843e-03, 5.32836181e-03, 7.10360582e-05, 8.71292997e-05, 9.96377080e-03, 9.63738797e-03, 7.31213677e-03, 8.70012148e-04, 9.78618342e-04, 1.02124693e-02, 8.78386002e-03, 4.88161060e-03, 1.18274426e-04, 6.39921021e-04, 1.00377580e-02, 9.54340293e-03, 6.05173814e-03, 4.14661940e-04, 2.64555612e-04, 1.02160196e-02, 8.61600088e-03, 4.77005225e-03, 1.87898004e-05, 6.17635497e-04, 9.30445558e-03, 9.48713993e-03, 7.25689742e-03, 6.81820299e-04, 3.59507901e-04, 5.79161813e-03, 6.83777542e-03, 6.18063842e-03, 6.66766715e-04, 6.70637870e-04, 2.10382561e-04, 1.28926298e-04, 3.15428351e-04, 3.63710771e-04 ]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_trg)
def __init__(self, input_file=None): """All initial values are set to zero until initalized using the initialize() method which reads in data using the ModelParameterDictionary and sets the random variables according to their respective distribution. REQUIRED PARAMETERS ------------------ Shape Parameter: Describes the skew of the Weibull distribution. If shape < 3.5, data skews left. If shape == 3.5, data is normal. If shape > 3.5, data skews right. Scale Parameter: Describes the peak of the Weibull distribution, located at 63.5% value of the cumulative distribution function. If unknown, it can be found using mean fire recurrence value and the get_scale_parameter() method described later. Mean Fire Recurrence : Average recurrence for a given area, elevation, veg type, etc. Total Run Time : Total model run time Delta T : Model time step. ------- Time to Next Fire: Value generated from the random.weibullvariate() function based on the scale and shape parameters """ # We import methods from ModelParameterDictionary # to read the parameters from the input file. #If the scale parameter is unknown, it can be found using the mean # fire recurrence value, which MUST be known or estimated to run the # get_scale_parameter() method.""" MPD = ModelParameterDictionary() if input_file is None: input_file = _DEFAULT_INPUT_FILE MPD.read_from_file(input_file) self.shape_parameter = MPD.read_float("SHAPE_PARAMETER") self.scale_parameter = MPD.read_float("SCALE_PARAMETER") self.mean_fire_recurrence = MPD.read_float("MEAN_FIRE_RECURRENCE") self.total_run_time = MPD.read_float("RUN_TIME") self.delta_t = MPD.read_int("DELTA_T") self.time_to_next_fire = 0.0
def __init__(self, input_file=None): """All initial values are set to zero until initalized using the initialize() method which reads in data using the ModelParameterDictionary and sets the random variables according to their respective distribution. REQUIRED PARAMETERS ------------------ Shape Parameter: Describes the skew of the Weibull distribution. If shape < 3.5, data skews left. If shape == 3.5, data is normal. If shape > 3.5, data skews right. Scale Parameter: Describes the peak of the Weibull distribution, located at 63.5% value of the cumulative distribution function. If unknown, it can be found using mean fire recurrence value and the get_scale_parameter() method described later. Mean Fire Recurrence : Average recurrence for a given area, elevation, veg type, etc. Total Run Time : Total model run time Delta T : Model time step. ------- Time to Next Fire: Value generated from the random.weibullvariate() function based on the scale and shape parameters """ # We import methods from ModelParameterDictionary # to read the parameters from the input file. #If the scale parameter is unknown, it can be found using the mean # fire recurrence value, which MUST be known or estimated to run the # get_scale_parameter() method.""" MPD = ModelParameterDictionary() if input_file is None: input_file = _DEFAULT_INPUT_FILE MPD.read_from_file(input_file) self.shape_parameter = MPD.read_float("SHAPE_PARAMETER") self.scale_parameter = MPD.read_float("SCALE_PARAMETER") self.mean_fire_recurrence = MPD.read_float("MEAN_FIRE_RECURRENCE") self.total_run_time = MPD.read_float("RUN_TIME") self.delta_t = MPD.read_int("DELTA_T") self.time_to_next_fire = 0.0
def initialize(self, input_file=None): MPD = ModelParameterDictionary() """We import methods from ModelParameterDictionary to read the parameters from the input file. If the scale parameter is unknown, it can be found using the mean fire recurrence value, which MUST be known or estimated to run the get_scale_parameter() method.""" if input_file is None: input_file = _DEFAULT_INPUT_FILE MPD.read_from_file(input_file) self.shape_parameter = MPD.read_float("SHAPE_PARAMETER") self.scale_parameter = MPD.read_float("SCALE_PARAMETER") self.mean_fire_recurrence = MPD.read_float("MEAN_FIRE_RECURRENCE") self.total_run_time = MPD.read_float("RUN_TIME") self.delta_t = MPD.read_int("DELTA_T")
def test_storms(): input_file_string = os.path.join(_THIS_DIR, "drive_sp_params_storms.txt") inputs = ModelParameterDictionary(input_file_string, auto_type=True) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") dt = inputs.read_float("dt") uplift = inputs.read_float("uplift_rate") mean_duration = inputs.read_float("mean_storm") mean_interstorm = inputs.read_float("mean_interstorm") mean_depth = inputs.read_float("mean_depth") storm_run_time = inputs.read_float("storm_run_time") delta_t = inputs.read_float("delta_t") mg = RasterModelGrid(nrows, ncols, xy_spacing=dx) mg.add_zeros("topographic__elevation", at="node") z = mg.zeros(at="node") mg["node"]["topographic__elevation"] = z + np.random.rand(len(z)) / 1000. mg.add_zeros("water__unit_flux_in", at="node") precip = PrecipitationDistribution( mean_storm_duration=mean_duration, mean_interstorm_duration=mean_interstorm, mean_storm_depth=mean_depth, total_t=storm_run_time, delta_t=delta_t, ) fr = FlowAccumulator(mg, flow_director="D8") sp = StreamPowerEroder(mg, **inputs) for ( interval_duration, rainfall_rate, ) in precip.yield_storm_interstorm_duration_intensity(): if rainfall_rate != 0.: mg.at_node["water__unit_flux_in"].fill(rainfall_rate) fr.run_one_step() sp.run_one_step(dt) mg.at_node["topographic__elevation"][mg.core_nodes] += ( uplift * interval_duration )
def test_storms(): input_file_string = os.path.join(_THIS_DIR, "drive_sp_params_storms.txt") inputs = ModelParameterDictionary(input_file_string, auto_type=True) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") dt = inputs.read_float("dt") uplift = inputs.read_float("uplift_rate") mean_duration = inputs.read_float("mean_storm") mean_interstorm = inputs.read_float("mean_interstorm") mean_depth = inputs.read_float("mean_depth") storm_run_time = inputs.read_float("storm_run_time") delta_t = inputs.read_float("delta_t") mg = RasterModelGrid((nrows, ncols), xy_spacing=dx) mg.add_zeros("topographic__elevation", at="node") z = mg.zeros(at="node") mg["node"]["topographic__elevation"] = z + np.random.rand(len(z)) / 1000.0 mg.add_zeros("water__unit_flux_in", at="node") precip = PrecipitationDistribution( mean_storm_duration=mean_duration, mean_interstorm_duration=mean_interstorm, mean_storm_depth=mean_depth, total_t=storm_run_time, delta_t=delta_t, ) fr = FlowAccumulator(mg, flow_director="D8") sp = StreamPowerEroder(mg, **inputs) for ( interval_duration, rainfall_rate, ) in precip.yield_storm_interstorm_duration_intensity(): if rainfall_rate != 0.0: mg.at_node["water__unit_flux_in"].fill(rainfall_rate) fr.run_one_step() sp.run_one_step(dt) mg.at_node["topographic__elevation"][mg.core_nodes] += ( uplift * interval_duration)
def test_storms(): input_file_string = os.path.join(_THIS_DIR, 'drive_sp_params_storms.txt') inputs = ModelParameterDictionary(input_file_string, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') mean_duration = inputs.read_float('mean_storm') mean_interstorm = inputs.read_float('mean_interstorm') mean_depth = inputs.read_float('mean_depth') storm_run_time = inputs.read_float('storm_run_time') delta_t = inputs.read_float('delta_t') mg = RasterModelGrid(nrows, ncols, dx) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.add_zeros('water__unit_flux_in', at='node') precip = PrecipitationDistribution( mean_storm_duration=mean_duration, mean_interstorm_duration=mean_interstorm, mean_storm_depth=mean_depth, total_t=storm_run_time, delta_t=delta_t) fr = FlowAccumulator(mg, flow_director='D8') sp = StreamPowerEroder(mg, **inputs) for (interval_duration, rainfall_rate) in \ precip.yield_storm_interstorm_duration_intensity(): if rainfall_rate != 0.: mg.at_node['water__unit_flux_in'].fill(rainfall_rate) fr.run_one_step() sp.run_one_step(dt) mg.at_node['topographic__elevation'][ mg.core_nodes] += uplift * interval_duration
def test_storms(): input_file_string = os.path.join(_THIS_DIR, 'drive_sp_params_storms.txt') inputs = ModelParameterDictionary(input_file_string, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') mean_duration = inputs.read_float('mean_storm') mean_interstorm = inputs.read_float('mean_interstorm') mean_depth = inputs.read_float('mean_depth') storm_run_time = inputs.read_float('storm_run_time') delta_t = inputs.read_float('delta_t') mg = RasterModelGrid(nrows, ncols, dx) mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.add_zeros('water__unit_flux_in', at='node') precip = PrecipitationDistribution(mean_storm_duration = mean_duration, mean_interstorm_duration = mean_interstorm, mean_storm_depth = mean_depth, total_t = storm_run_time, delta_t = delta_t) fr = FlowAccumulator(mg, flow_director='D8') sp = StreamPowerEroder(mg, **inputs) for (interval_duration, rainfall_rate) in \ precip.yield_storm_interstorm_duration_intensity(): if rainfall_rate != 0.: mg.at_node['water__unit_flux_in'].fill(rainfall_rate) fr.run_one_step() sp.run_one_step(dt) mg.at_node['topographic__elevation'][ mg.core_nodes] += uplift * interval_duration
def test_sed_dep(): input_file = os.path.join(_THIS_DIR, 'sed_dep_params.txt') inputs = ModelParameterDictionary(input_file, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('uplift_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime // dt) uplift_per_step = uplift_rate * dt mg = RasterModelGrid((nrows, ncols), (dx, dx)) mg.add_zeros('topographic__elevation', at='node') z = np.loadtxt(os.path.join(_THIS_DIR, 'seddepinit.txt')) mg['node']['topographic__elevation'] = z mg.set_closed_boundaries_at_grid_edges(True, False, True, False) fr = FlowAccumulator(mg, flow_director='D8') sde = SedDepEroder(mg, **inputs) for i in range(nt): mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step mg = fr.run_one_step() mg, _ = sde.erode(dt) z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'seddepz_tg.txt')) assert_array_almost_equal( mg.at_node['topographic__elevation'][mg.core_nodes], z_tg[mg.core_nodes])
def initialize(self, input_file=None): MPD = ModelParameterDictionary() """We imported methods from ModelParameterDictionary to read the parameters from the input file. Necessary parameters to run this code include: mean_storm (type: float) mean_intensity (type: float) mean_interstorm (type: float) mean_storm_depth is calculated using mean storm and intensity data The random variables of storm_duration, interstorm_duration, storm_depth and intensity are found using methods declared later in the class """ if input_file is None: input_file = _DEFAULT_INPUT_FILE MPD.read_from_file(input_file) self.mean_storm = MPD.read_float( "MEAN_STORM" ) self.mean_interstorm = MPD.read_float( "MEAN_INTERSTORM" ) self.mean_storm_depth = MPD.read_float( "MEAN_DEPTH" ) self.mean_intensity = self.mean_storm_depth / self.mean_storm self.storm_duration = self.get_precipitation_event_duration() self.interstorm_duration = self.get_interstorm_event_duration() self.storm_depth = self.get_storm_depth() self.intensity = self.get_storm_intensity() self.run_time = MPD.read_float("RUN_TIME") try: #DEJH thinks this is redundant self.delta_t = MPD.read_int("DELTA_T") except: pass
def test_sed_dep(): input_file = os.path.join(_THIS_DIR, 'sed_dep_params.txt') inputs = ModelParameterDictionary(input_file, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('uplift_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime // dt) uplift_per_step = uplift_rate * dt mg = RasterModelGrid((nrows, ncols), (dx, dx)) mg.add_zeros('topographic__elevation', at='node') z = np.loadtxt(os.path.join(_THIS_DIR, 'seddepinit.txt')) mg['node']['topographic__elevation'] = z mg.set_closed_boundaries_at_grid_edges(True, False, True, False) fr = FlowAccumulator(mg, flow_director='D8') sde = SedDepEroder(mg, **inputs) for i in range(nt): mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step mg = fr.run_one_step() mg, _ = sde.erode(dt) z_tg = np.loadtxt(os.path.join(_THIS_DIR, 'seddepz_tg.txt')) assert_array_almost_equal(mg.at_node['topographic__elevation'][ mg.core_nodes], z_tg[mg.core_nodes])
from __future__ import print_function from landlab import RasterModelGrid from landlab import ModelParameterDictionary from landlab.utils import structured_grid as sgrid from landlab.components.sed_trp_shallow_flow.transport_sed_in_shallow_flow import SurfaceFlowTransport import time import pylab import numpy as np #get the needed properties to build the grid: inputs = ModelParameterDictionary('./stof_params_basin.txt') nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') h_init = inputs.read_float('h_init') z_boundary = inputs.read_float('z_boundary') #now the outlet height drop_ht = inputs.read_float('drop_ht') #Now the inlet gradient initial_slope = inputs.read_float('initial_slope') time_to_run = inputs.read_int('run_time') inlet_nodes = [0,1,2, ncols, 2*ncols] mg = RasterModelGrid(nrows, ncols, dx) mg.set_inactive_boundaries(False, True, False, True) #mg.status_at_node[inlet_nodes] = 1 #mg.status_at_node[-5] = 1 #Fixed lip outlet #print sgrid.node_tolink_index(mg.shape)[1] #mg.reset_list_of_active_links()
def run_model(input_file=None, savepath=None, initial_topo_file=None, initial_seed_file=None): from landlab.components.flow_routing.route_flow_dn_JL import FlowRouter from landlab.components.stream_power.fastscape_stream_power_JL import FastscapeEroder #from landlab.components.stream_power.stream_power import StreamPowerEroder from landlab.components.sink_fill.pit_fill_pf import PitFiller from landlab.components.diffusion.diffusion import LinearDiffuser from landlab import ModelParameterDictionary #from landlab.plot import channel_profile as prf from landlab.plot.imshow import imshow_node_grid from landlab.io.esri_ascii import write_esri_ascii from landlab.io.esri_ascii import read_esri_ascii from landlab import RasterModelGrid #from analysis_method import analyze_drainage_percentage #from analysis_method import analyze_drainage_percentage_each_grid #from analysis_method import analyze_mean_erosion #from analysis_method import elev_diff_btwn_moraine_upland #from analysis_method import label_catchment #from analysis_method import cross_section #from analysis_method import analyze_node_below_threshold #from analysis_method import identify_drained_area #from analysis_method import save_result from analysis_method import shiftColorMap import copy import numpy as np import matplotlib import matplotlib.pyplot as plt import os import time import sys import shutil sys.setrecursionlimit(5000) #=============================================================================== #get the needed properties to build the grid: if input_file is None: input_file = './coupled_params_sp.txt' inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') initial_slope = inputs.read_float('initial_slope') rightmost_elevation = initial_slope * ncols * dx #rightmost_elevation = inputs.read_float('rightmost_elevation') uplift_rate = inputs.read_float('uplift_rate') incision_rate = inputs.read_float('incision_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime // dt) k_sp = inputs.read_float('K_sp') m_sp = inputs.read_float('m_sp') uplift_per_step = uplift_rate * dt incision_per_step = incision_rate * dt moraine_height = inputs.read_float('moraine_height') moraine_width = inputs.read_float('moraine_width') #valley_width = inputs.read_float('valley_width') valley_depth = inputs.read_float('valley_depth') num_outs = inputs.read_int('number_of_outputs') output_interval = int(nt // num_outs) diff = inputs.read_float('linear_diffusivity') #threshold_stream_power = inputs.read_float('threshold_stream_power') threshold_AS = inputs.read_float('threshold_AS') #threshold_erosion = dt*threshold_stream_power gw_coeff = inputs.read_float('gw_coeff') all_dry = inputs.read_bool('all_dry') fill_sink_with_water = inputs.read_bool('fill_sink_with_water') #=============================================================================== #=============================================================================== if initial_topo_file is None: #instantiate the grid object mg = RasterModelGrid(nrows, ncols, dx) ##create the elevation field in the grid: #create the field #specifically, this field has a triangular ramp #moraine at the north edge of the domain. mg.add_zeros('node', 'topographic__elevation', units='m') z = mg.at_node['topographic__elevation'] moraine_start_y = np.max(mg.node_y) - moraine_width moraine_ys = np.where(mg.node_y > moraine_start_y) z[moraine_ys] += (mg.node_y[moraine_ys] - np.min( mg.node_y[moraine_ys])) * (moraine_height / moraine_width) #set valley #valley_start_x = np.min(mg.node_x)+valley_width #valley_ys = np.where((mg.node_x<valley_start_x)&(mg.node_y<moraine_start_y-valley_width)) #z[valley_ys] -= (np.max(mg.node_x[valley_ys])-mg.node_x[valley_ys])*(valley_depth/valley_width) #set ramp (towards valley) upland = np.where(mg.node_y < moraine_start_y) z[upland] -= (np.max(mg.node_x[upland]) - mg.node_x[upland]) * (rightmost_elevation / (ncols * dx)) z += rightmost_elevation #set ramp (away from moraine) #upland = np.where(mg.node_y<moraine_start_y) #z[upland] -= (moraine_start_y-mg.node_y[upland])*initial_slope #put these values plus roughness into that field if initial_seed_file is None: z += np.random.rand(len(z)) / 1 else: (seedgrid, seed) = read_esri_ascii(initial_seed_file, name='topographic__elevation_seed') z += seed mg.at_node['topographic__elevation'] = z #set river valley river_valley, = np.where( np.logical_and( mg.node_x == 0, np.logical_or(mg.status_at_node == 1, mg.status_at_node == 2))) mg.at_node['topographic__elevation'][river_valley] = -valley_depth else: (mg, z) = read_esri_ascii(initial_topo_file, name='topographic__elevation') #set river valley river_valley, = np.where( np.logical_and( mg.node_x == 0, np.logical_or(mg.status_at_node == 1, mg.status_at_node == 2))) mg.at_node['topographic__elevation'][river_valley] = -valley_depth #set up grid's boundary conditions (right, top, left, bottom) is inactive mg.set_closed_boundaries_at_grid_edges(True, True, False, True) #set up boundary along moraine #moraine_start_y = np.max(mg.node_y)-moraine_width #bdy_moraine_ids = np.where((mg.node_y > moraine_start_y) & (mg.node_x == 0)) #mg.status_at_node[bdy_moraine_ids]=4 #mg._update_links_nodes_cells_to_new_BCs() #=============================================================================== #=============================================================================== #instantiate the components: fr = FlowRouter(mg) pf = PitFiller(mg) sp = FastscapeEroder(mg, input_file, threshold_sp=threshold_AS * k_sp) #sp = StreamPowerEroder(mg, input_file, threshold_sp=threshold_erosion, use_Q=True) #diffuse = PerronNLDiffuse(mg, input_file) #lin_diffuse = LinearDiffuser(mg, input_file, method='on_diagonals') lin_diffuse = LinearDiffuser(mg, input_file) #=============================================================================== #=============================================================================== #instantiate plot setting plt.close('all') output_time = output_interval plot_num = 0 mycmap = shiftColorMap(matplotlib.cm.gist_earth, 'mycmap') #folder name if savepath is None: if all_dry: name_tag = 'All_dry' elif fill_sink_with_water: name_tag = 'Not_all_dry_no_sink' else: name_tag = 'Not_all_dry_sink' savepath = 'results/sensitivity_test_threshold_same_seed/'+name_tag+'_dt=' + str(dt) + '_total_time=' + str(runtime) + '_k_sp=' + str(k_sp) + \ '_uplift_rate=' + str(uplift_rate) + '_incision_rate=' + str(incision_rate) + '_initial_slope=' + str(initial_slope) + \ '_threshold=' + str(threshold_stream_power) if not os.path.isdir(savepath): os.makedirs(savepath) #copy params_file if not os.path.isfile(savepath + '/coupled_params_sp.txt'): shutil.copy(input_file, savepath + '/coupled_params_sp.txt') # Display a message print 'Running ...' print savepath #save initial topography write_esri_ascii(savepath + '/Topography_t=0.0.txt', mg, 'topographic__elevation') #time start_time = time.time() #=============================================================================== #=============================================================================== #perform the loops: for i in xrange(nt): #note the input arguments here are not totally standardized between modules ''' # simulate changing climate if (((i+1)*dt // 5000.) % 2) == 0.: all_dry = False else: all_dry = True ''' #sp = FastscapeEroder(mg, input_file, threshold_sp = threshold_stream_power) #update elevation mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step mg.at_node['topographic__elevation'][river_valley] -= incision_per_step #mg = lin_diffuse.diffuse(dt) #route and erode original_topo = mg.at_node['topographic__elevation'].copy() slope = mg.at_node['topographic__steepest_slope'].copy() filled_nodes = None if all_dry or fill_sink_with_water: mg = pf.pit_fill() filled_nodes, = np.where( (mg.at_node['topographic__elevation'] - original_topo) > 0) mg = fr.route_flow(routing_flat=all_dry) old_topo = mg.at_node['topographic__elevation'].copy() #mg, temp_z, temp_sp = sp.erode(mg, dt, Q_if_used='water__volume_flux') mg = sp.erode(mg, dt, flooded_nodes=filled_nodes) new_topo = mg.at_node['topographic__elevation'].copy() mg.at_node[ 'topographic__elevation'] = original_topo + new_topo - old_topo #diffuse #for j in range(10): # mg = lin_diffuse.diffuse(dt/10) mg = lin_diffuse.diffuse(dt) if i + 1 == output_time: print 'Saving data...' plot_num += 1 plt.figure(plot_num) im = imshow_node_grid(mg, 'topographic__elevation', plot_name='t = '+str(int((i+1)*dt))+' years', \ grid_units = ['m','m'], cmap=mycmap, allow_colorbar=True, \ vmin=0-valley_depth-incision_rate*runtime, vmax=5.+moraine_height+uplift_rate*runtime) plt.savefig(savepath + '/Topography_t=' + str( (i + 1) * dt) + '.jpg', dpi=300) write_esri_ascii( savepath + '/Topography_t=' + str((i + 1) * dt) + '.txt', mg, 'topographic__elevation') output_time += output_interval plt.close('all') print("--- %.2f minutes ---" % ((time.time() - start_time) / 60)), 'Completed loop', i + 1 plt.close('all') print 'Finished simulating.' #=============================================================================== #=============================================================================== #analyze_drainage_percentage(savepath, True) #analyze_mean_erosion(savepath, True) #elev_diff_btwn_moraine_upland(savepath, True) #label_catchment(savepath) #cross_section(savepath) #=============================================================================== print 'Done!' print '\n'
show_figs_in_run = True # disable to run straight through DL_or_TL = "DL" if DL_or_TL == "TL": init_interval = 20 else: init_interval = 100 # get the needed properties to build the grid: input_file = "./sed_dep_NMGparams2.txt" # NOTE: remember to change the fixed y-axis dimension in the plots!! y_max = 3000 make_output_plots = True out_interval = 15 # was 15 inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") leftmost_elev = inputs.read_float("leftmost_elevation") initial_slope = inputs.read_float("initial_slope") uplift_rate = inputs.read_float("uplift_rate") runtime = inputs.read_float("total_time") dt = inputs.read_float("dt") # check we have a plaubible grid mg = RasterModelGrid(nrows, ncols, dx) assert mg.number_of_nodes == nrows * ncols assert mg.dx == dx # Display a message
def __init__(self, input_stream): """ Reads in parameters and initializes the model. Example ------- >>> from six import StringIO >>> p = StringIO(''' ... model_grid_row__count: number of rows in grid ... 4 ... model_grid_column__count: number of columns in grid ... 4 ... plot_interval: interval for plotting to display, s ... 2.0 ... model__run_time: duration of model run, s ... 1.0 ... model__report_interval: time interval for reporting progress, real-time seconds ... 1.0e6 ... surface_bleaching_time_scale: time scale for OSL bleaching, s ... 2.42 ... light_attenuation_length: length scale for light attenuation, cells (1 cell = 1 mm) ... 2.0 ... ''') >>> tsbm = TurbulentSuspensionAndBleachingModel(p) >>> tsbm.node_state array([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]) >>> tsbm.grid.at_node['osl'] array([ 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.]) >>> tsbm.n_xn array([0, 1, 1, 0, 0, 1, 1, 0]) >>> tsbm.fluid_surface_height 3.5 """ # Get a source for input parameters. params = ModelParameterDictionary(input_stream) # Read user-defined parameters nr = params.read_int('model_grid_row__count') # number of rows (CSDMS Standard Name [CSN]) nc = params.read_int('model_grid_column__count') # number of cols (CSN) self.plot_interval = params.read_float('plot_interval') # interval for plotting output, s self.run_duration = params.read_float('model__run_time') # duration of run, sec (CSN) self.report_interval = params.read_float('model__report_interval') # report interval, in real-time seconds self.bleach_T0 = params.read_float('surface_bleaching_time_scale') # time scale for bleaching at fluid surface, s self.zstar = params.read_float('light_attenuation_length') # length scale for light attenuation in fluid, CELLS # Derived parameters self.fluid_surface_height = nr-0.5 # Calculate when we next want to report progress. self.next_report = time.time() + self.report_interval # Create grid mg = RasterModelGrid(nr, nc, 1.0) # Make the boundaries be walls mg.set_closed_boundaries_at_grid_edges(True, True, True, True) # Set up the states and pair transitions. ns_dict = { 0 : 'fluid', 1 : 'particle' } xn_list = self.setup_transition_list() # Create the node-state array and attach it to the grid node_state_grid = mg.add_zeros('node', 'node_state_map', dtype=int) # For visual display purposes, set all boundary nodes to fluid node_state_grid[mg.closed_boundary_nodes] = 0 # Initialize the node-state array: here, the initial condition is a pile of # resting grains at the bottom of a container. bottom_rows = where(mg.node_y<0.4*nr)[0] node_state_grid[bottom_rows] = 1 # Create a data array for bleaching. # Here, osl=optically stimulated luminescence, normalized to the original # signal (hence, initially all unity). Over time this signal may get # bleached out due to exposure to light. self.osl = mg.add_zeros('node', 'osl') self.osl[bottom_rows] = 1.0 self.osl_display = mg.add_zeros('node', 'osl_display') self.osl_display[bottom_rows] = 1.0 # We'll need an array to track the last time any given node was # updated, so we can figure out the duration of light exposure between # update events self.last_update_time = mg.add_zeros('node','last_update_time') # Call the base class (RasterCTS) init method super(TurbulentSuspensionAndBleachingModel, \ self).__init__(mg, ns_dict, xn_list, node_state_grid, prop_data=self.osl) # Set up plotting (if plotting desired) if self.plot_interval <= self.run_duration: self.initialize_plotting()
DEJH, 09/15/14 """ from __future__ import print_function import time import numpy import pylab from landlab import ModelParameterDictionary, RasterModelGrid from landlab.components import FlowAccumulator from landlab.components.stream_power import FastscapeEroder, StreamPowerEroder from landlab.plot.imshow import imshow_grid inputs = ModelParameterDictionary("./drive_sp_params.txt") nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") dt = inputs.read_float("dt") time_to_run = inputs.read_float("run_time") # nt needs defining uplift = inputs.read_float("uplift_rate") init_elev = inputs.read_float("init_elev") 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 + numpy.random.rand(len(z)) / 1000.
from landlab import RasterModelGrid from landlab import ModelParameterDictionary from landlab.components.sed_trp_shallow_flow.transport_sed_in_shallow_flow import SurfaceFlowTransport import time import pylab import numpy as np #get the needed properties to build the grid: inputs = ModelParameterDictionary('./stof_params.txt') nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') h_init = inputs.read_float('h_init') h_boundary = inputs.read_float('h_boundary') drop_ht = inputs.read_float('drop_ht') initial_slope = inputs.read_float('initial_slope') time_to_run = inputs.read_int('run_time') left_middle_node = ncols * (nrows / 2) z0 = drop_ht + dx * (ncols - 1) * initial_slope mg = RasterModelGrid(nrows, ncols, dx) mg.set_inactive_boundaries(True, False, True, False) #create the fields in the grid mg.create_node_array_zeros('topographic_elevation') mg.create_node_array_zeros('planet_surface__water_depth') #set the initial water depths h = mg.create_node_array_zeros() + h_init
class TestModelParameterDictionary(unittest.TestCase): def setUp(self): from StringIO import StringIO self.param_file = StringIO(_TEST_PARAM_DICT_FILE) self.param_dict = ModelParameterDictionary() self.param_dict.read_from_file(self.param_file) def test_read_file(self): all_keys = set([ 'FLOAT_VAL', 'INT_VAL', 'STRING_VAL', 'TRUE_BOOL_VAL', 'FALSE_BOOL_VAL', ]) param_list = set(self.param_dict.params()) self.assertEqual(param_list, all_keys) def test_read_file_name(self): (prm_fd, prm_file_name) = tempfile.mkstemp() prm_file = os.fdopen(prm_fd, 'w') prm_file.write(_TEST_PARAM_DICT_FILE) prm_file.close() param_dict = ModelParameterDictionary() param_dict.read_from_file(prm_file_name) os.remove(prm_file_name) all_keys = set([ 'FLOAT_VAL', 'INT_VAL', 'STRING_VAL', 'TRUE_BOOL_VAL', 'FALSE_BOOL_VAL', ]) param_list = set(param_dict.params()) self.assertEqual(param_list, all_keys) def test_read_file_like_twice(self): from StringIO import StringIO param_file = StringIO(_TEST_PARAM_DICT_FILE) param_dict_1 = ModelParameterDictionary() param_dict_2 = ModelParameterDictionary() param_dict_1.read_from_file(param_file) param_dict_2.read_from_file(param_file) def test_read_int(self): self.assertEqual(self.param_dict.read_int('INT_VAL'), 1) with self.assertRaises(ParameterValueError): self.param_dict.read_int('FLOAT_VAL') with self.assertRaises(MissingKeyError): self.param_dict.read_int('MISSING_INT') self.assertEqual(self.param_dict.read_int('MISSING_INT', 2), 2) def test_get_int(self): self.assertEqual(self.param_dict.get('INT_VAL', ptype=int), 1) with self.assertRaises(ParameterValueError): self.param_dict.get('FLOAT_VAL', ptype=int) with self.assertRaises(MissingKeyError): self.param_dict.get('MISSING_INT', ptype=int) def test_set_default(self): self.param_dict.setdefault('MISSING_INT', 2) self.assertEqual(self.param_dict.read_int('MISSING_INT'), 2) def test_read_float(self): self.assertEqual(self.param_dict.read_float('FLOAT_VAL'), 2.2) self.assertEqual(self.param_dict.read_float('INT_VAL'), 1) with self.assertRaises(ParameterValueError): self.param_dict.read_float('STRING_VAL') with self.assertRaises(MissingKeyError): self.param_dict.read_float('MISSING_FLOAT') def test_read_string(self): self.assertEqual(self.param_dict.read_string('STRING_VAL'), 'The Landlab') self.assertEqual(self.param_dict.read_string('INT_VAL'), '1') self.assertEqual(self.param_dict.read_string('FLOAT_VAL'), '2.2') with self.assertRaises(MissingKeyError): self.param_dict.read_string('MISSING_STRING') def test_read_bool(self): self.assertEqual(self.param_dict.read_bool('TRUE_BOOL_VAL'), True) self.assertEqual(self.param_dict.read_bool('FALSE_BOOL_VAL'), False) with self.assertRaises(MissingKeyError): self.param_dict.read_bool('MISSING_BOOLEAN') with self.assertRaises(ParameterValueError): self.param_dict.read_bool('STRING_VAL') def test_dict_keys(self): all_keys = set([ 'FLOAT_VAL', 'INT_VAL', 'STRING_VAL', 'TRUE_BOOL_VAL', 'FALSE_BOOL_VAL', ]) self.assertEqual(set(self.param_dict), all_keys) for key in all_keys: self.assertTrue(key in self.param_dict) def test_dict_index(self): self.assertEqual(self.param_dict['INT_VAL'], '1')
def test_diffusion(): inputs = ModelParameterDictionary(os.path.join(_THIS_DIR, 'diffusion_params.txt')) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), (dx, dx)) uplift_rate = mg.node_y[mg.core_cells] / 100000. # create the fields in the grid mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev np.random.seed(0) mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True) # instantiate: dfn = LinearDiffuser(mg, inputs) # perform the loop: elapsed_time = 0. # total time in simulation while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time dfn.diffuse(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_rate * dt elapsed_time += dt z_target = np.array([5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 4.37587211e-04, 8.91773001e-04, 9.63662761e-04, 3.83441519e-04, 7.91725038e-04, 9.17712569e-04, 1.02071232e-03, 1.10556005e-03, 1.14946096e-03, 1.20022436e-03, 1.12938983e-03, 1.12734463e-03, 1.00699946e-03, 8.70012148e-04, 9.78618342e-04, 1.12639399e-03, 1.41449092e-03, 2.66410106e-03, 2.80054364e-03, 2.82446032e-03, 2.68730913e-03, 2.44468915e-03, 2.03932919e-03, 4.14661940e-04, 2.64555612e-04, 2.14829293e-03, 2.77874345e-03, 3.21568734e-03, 3.45767578e-03, 4.46407381e-03, 4.25087300e-03, 3.82133955e-03, 3.24905386e-03, 6.81820299e-04, 3.59507901e-04, 3.36368061e-03, 4.19756389e-03, 4.81101469e-03, 5.12991298e-03, 5.14551834e-03, 4.82212362e-03, 5.21733341e-03, 4.36590155e-03, 3.63710771e-04, 5.70196770e-04, 4.64503306e-03, 5.67212626e-03, 6.43364397e-03, 6.85196170e-03, 6.84719792e-03, 6.44199511e-03, 5.63718526e-03, 4.53705235e-03, 2.44425592e-04, 1.58969584e-04, 5.85390586e-03, 7.15167925e-03, 8.09808225e-03, 8.58987393e-03, 8.60040722e-03, 8.08353544e-03, 7.11357773e-03, 5.74363061e-03, 9.60984079e-05, 9.76459465e-04, 6.28409752e-03, 7.69302638e-03, 9.77162122e-03, 1.03665461e-02, 1.03596559e-02, 9.77581391e-03, 8.63184402e-03, 7.06221620e-03, 1.18727719e-04, 3.17983179e-04, 7.42141185e-03, 9.16089943e-03, 1.04492602e-02, 1.11235269e-02, 1.21428645e-02, 1.14619409e-02, 1.01991149e-02, 8.52209581e-03, 9.29296198e-04, 3.18568952e-04, 8.66507665e-03, 1.06513243e-02, 1.20945739e-02, 1.28805314e-02, 1.28817803e-02, 1.21355585e-02, 1.16763419e-02, 9.65364442e-03, 4.69547619e-06, 6.77816537e-04, 9.99969455e-03, 1.21210512e-02, 1.37222525e-02, 1.45639747e-02, 1.45899214e-02, 1.37503063e-02, 1.21879324e-02, 1.00970967e-02, 9.52749012e-04, 4.47125379e-04, 1.11861039e-02, 1.35273547e-02, 1.52388381e-02, 1.61710069e-02, 1.61700373e-02, 1.52797248e-02, 1.35608698e-02, 1.12630871e-02, 6.92531590e-04, 7.25254280e-04, 1.14112447e-02, 1.38209264e-02, 1.66345746e-02, 1.75854796e-02, 1.76037603e-02, 1.66317633e-02, 1.48117588e-02, 1.22941311e-02, 2.90077607e-04, 6.18015429e-04, 1.24651035e-02, 1.49479969e-02, 1.67762718e-02, 1.77682020e-02, 1.87567995e-02, 1.77826641e-02, 1.59106401e-02, 1.33841504e-02, 4.31418435e-04, 8.96546596e-04, 1.34298871e-02, 1.58121125e-02, 1.76176213e-02, 1.85627061e-02, 1.85694232e-02, 1.75911811e-02, 1.67878955e-02, 1.43993331e-02, 9.98847007e-04, 1.49448305e-04, 1.40269701e-02, 1.63483655e-02, 1.80226762e-02, 1.89156586e-02, 1.88916976e-02, 1.79880403e-02, 1.62672916e-02, 1.39254090e-02, 6.91669955e-05, 6.97428773e-04, 1.46967049e-02, 1.65718319e-02, 1.79957330e-02, 1.87279193e-02, 1.87059832e-02, 1.79052307e-02, 1.64399258e-02, 1.44435378e-02, 1.71629677e-04, 5.21036606e-04, 1.40296771e-02, 1.54293506e-02, 1.75066749e-02, 1.80476077e-02, 1.79866098e-02, 1.73732550e-02, 1.62714602e-02, 1.47877073e-02, 3.18389295e-05, 1.64694156e-04, 1.41367998e-02, 1.49517470e-02, 1.57129817e-02, 1.59700260e-02, 1.68585204e-02, 1.64421520e-02, 1.58441873e-02, 1.50473253e-02, 3.11944995e-04, 3.98221062e-04, 2.09843749e-04, 1.86193006e-04, 9.44372390e-04, 7.39550795e-04, 4.90458809e-04, 2.27414628e-04, 2.54356482e-04, 5.80291603e-05, 4.34416626e-04]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_target)
from __future__ import print_function from landlab.components.craters.dig_craters import impactor from landlab import ModelParameterDictionary from landlab import RasterModelGrid import numpy as np import time import pylab #get the needed properties to build the grid: input_file = './craters_params_degrade.txt' inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') nt = inputs.read_int('number_of_craters_per_loop') loops = inputs.read_int('number_of_loops') mg = RasterModelGrid(nrows, ncols, dx) mg.set_looped_boundaries(True, True) #create the fields in the grid mg.create_node_array_zeros('topographic__elevation') mg['node'][ 'topographic__elevation'] = np.load('init_topo.npy') # Display a message print( 'Running ...' ) start_time = time.time()
from landlab.plot import channel_profile as prf from landlab.plot.imshow import imshow_node_grid from pylab import colorbar, show, plot, loglog, figure from landlab import RasterModelGrid import numpy as np import pylab from pylab import show from copy import copy, deepcopy from time import time #get the needed properties to build the grid: input_file = './sed_dep_params.txt' inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('uplift_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime//dt) uplift_per_step = uplift_rate * dt print 'uplift per step: ', uplift_per_step #instantiate the grid object mg = RasterModelGrid(nrows, ncols, dx)
from __future__ import print_function from landlab import RasterModelGrid from landlab import ModelParameterDictionary from landlab.components.sed_trp_shallow_flow import SurfaceFlowTransport import time import pylab import numpy as np # get the needed properties to build the grid: inputs = ModelParameterDictionary("./stof_params.txt") nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") h_init = inputs.read_float("h_init") h_boundary = inputs.read_float("h_boundary") drop_ht = inputs.read_float("drop_ht") initial_slope = inputs.read_float("initial_slope") time_to_run = inputs.read_int("run_time") left_middle_node = ncols * (nrows / 2) z0 = drop_ht + dx * (ncols - 1) * initial_slope mg = RasterModelGrid(nrows, ncols, dx) mg.set_inactive_boundaries(False, True, False, True) # create the fields in the grid mg.add_zeros("topographic__elevation", at="node") mg.add_zeros("planet_surface__water_depth", at="node")
def test_fastscape(): input_str = os.path.join(_THIS_DIR, "drive_sp_params.txt") inputs = ModelParameterDictionary(input_str) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") dt = inputs.read_float("dt") time_to_run = inputs.read_float("run_time") uplift = inputs.read_float("uplift_rate") init_elev = inputs.read_float("init_elev") mg = RasterModelGrid(nrows, ncols, xy_spacing=dx) mg.set_closed_boundaries_at_grid_edges(False, False, True, True) mg.add_zeros("topographic__elevation", at="node") z = mg.zeros(at="node") + init_elev numpy.random.seed(0) mg["node"]["topographic__elevation"] = z + numpy.random.rand(len(z)) / 1000. fr = FlowAccumulator(mg, flow_director="D8") fsp = Fsc(mg, input_str, method="D8") elapsed_time = 0. while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time mg = fr.run_one_step() mg = fsp.erode(mg, dt=dt) mg.at_node["topographic__elevation"][mg.core_nodes] += uplift * dt elapsed_time += dt z_trg = numpy.array( [ 5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 1.01830760e-02, 9.58036770e-03, 6.55865452e-03, 3.83441519e-04, 7.91725038e-04, 1.00142749e-02, 8.80798884e-03, 5.78387585e-03, 7.10360582e-05, 8.71292997e-05, 9.81911417e-03, 9.52243406e-03, 7.55093226e-03, 8.70012148e-04, 9.78618342e-04, 1.00629755e-02, 8.49253798e-03, 5.33216680e-03, 1.18274426e-04, 6.39921021e-04, 9.88956320e-03, 9.47119567e-03, 6.43790696e-03, 4.14661940e-04, 2.64555612e-04, 1.00450743e-02, 8.37262908e-03, 5.21540904e-03, 1.87898004e-05, 6.17635497e-04, 9.21286940e-03, 9.34022513e-03, 7.51114450e-03, 6.81820299e-04, 3.59507901e-04, 6.19166921e-03, 7.10456176e-03, 6.62585507e-03, 6.66766715e-04, 6.70637870e-04, 2.10382561e-04, 1.28926298e-04, 3.15428351e-04, 3.63710771e-04, ] ) assert_array_almost_equal(mg.at_node["topographic__elevation"], z_trg)
def test_diffusion(): infile = os.path.join(_THIS_DIR, 'diffusion_params.txt') inputs = ModelParameterDictionary(infile, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), (dx, dx)) uplift_rate = mg.node_y[mg.core_cells] / 100000. # create the fields in the grid mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev np.random.seed(0) mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True) # instantiate: dfn = LinearDiffuser(mg, **inputs) # perform the loop: elapsed_time = 0. # total time in simulation while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time dfn.run_one_step(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_rate * dt elapsed_time += dt z_target = np.array([ 5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 4.37587211e-04, 8.91773001e-04, 9.63662761e-04, 3.83441519e-04, 7.91725038e-04, 9.18166135e-04, 1.02015039e-03, 1.10666198e-03, 1.14866514e-03, 1.20224288e-03, 1.12953135e-03, 1.12966219e-03, 1.00745155e-03, 8.70012148e-04, 9.78618342e-04, 1.12628772e-03, 1.41663596e-03, 2.66338249e-03, 2.80420703e-03, 2.82445061e-03, 2.69263914e-03, 2.44620140e-03, 2.04237613e-03, 4.14661940e-04, 2.64555612e-04, 2.15073330e-03, 2.77965579e-03, 3.22134736e-03, 3.45859244e-03, 4.47224671e-03, 4.25371135e-03, 3.82941648e-03, 3.25127747e-03, 6.81820299e-04, 3.59507901e-04, 3.36577718e-03, 4.20490812e-03, 4.81467159e-03, 5.14099588e-03, 5.15029835e-03, 4.83533539e-03, 5.22312276e-03, 4.37284689e-03, 3.63710771e-04, 5.70196770e-04, 4.65122535e-03, 5.67854747e-03, 6.44757828e-03, 6.85985389e-03, 6.86464781e-03, 6.45159799e-03, 5.65255723e-03, 4.54258827e-03, 2.44425592e-04, 1.58969584e-04, 5.85971567e-03, 7.16648352e-03, 8.10954246e-03, 8.61082386e-03, 8.61350727e-03, 8.10597021e-03, 7.12594182e-03, 5.75483957e-03, 9.60984079e-05, 9.76459465e-04, 6.29476234e-03, 7.70594852e-03, 9.79504842e-03, 1.03829367e-02, 1.03869062e-02, 9.79374998e-03, 8.65447904e-03, 7.07179252e-03, 1.18727719e-04, 3.17983179e-04, 7.43078552e-03, 9.18353155e-03, 1.04682910e-02, 1.11542648e-02, 1.21643980e-02, 1.14930584e-02, 1.02184219e-02, 8.53727126e-03, 9.29296198e-04, 3.18568952e-04, 8.68034110e-03, 1.06702554e-02, 1.21275181e-02, 1.29049224e-02, 1.29184938e-02, 1.21616788e-02, 1.17059081e-02, 9.66728348e-03, 4.69547619e-06, 6.77816537e-04, 1.00128306e-02, 1.21521279e-02, 1.37494046e-02, 1.46053573e-02, 1.46205669e-02, 1.37908840e-02, 1.22146332e-02, 1.01165765e-02, 9.52749012e-04, 4.47125379e-04, 1.12069867e-02, 1.35547122e-02, 1.52840440e-02, 1.62069802e-02, 1.62196380e-02, 1.53169489e-02, 1.35997836e-02, 1.12818577e-02, 6.92531590e-04, 7.25254280e-04, 1.14310516e-02, 1.38647655e-02, 1.66771925e-02, 1.76447108e-02, 1.76515649e-02, 1.66885162e-02, 1.48507549e-02, 1.23206170e-02, 2.90077607e-04, 6.18015429e-04, 1.24952067e-02, 1.49924260e-02, 1.68435913e-02, 1.78291009e-02, 1.88311310e-02, 1.78422046e-02, 1.59665841e-02, 1.34122052e-02, 4.31418435e-04, 8.96546596e-04, 1.34612553e-02, 1.58763600e-02, 1.76887976e-02, 1.86526609e-02, 1.86492669e-02, 1.76752679e-02, 1.68480793e-02, 1.44368883e-02, 9.98847007e-04, 1.49448305e-04, 1.40672989e-02, 1.64140227e-02, 1.81162514e-02, 1.90091351e-02, 1.89959971e-02, 1.80757625e-02, 1.63425116e-02, 1.39643530e-02, 6.91669955e-05, 6.97428773e-04, 1.47340964e-02, 1.66453353e-02, 1.80835612e-02, 1.88335770e-02, 1.88048458e-02, 1.80022362e-02, 1.65110248e-02, 1.44854151e-02, 1.71629677e-04, 5.21036606e-04, 1.40633664e-02, 1.54867652e-02, 1.75865008e-02, 1.81309867e-02, 1.80760242e-02, 1.74501109e-02, 1.63343931e-02, 1.48208186e-02, 3.18389295e-05, 1.64694156e-04, 1.41550038e-02, 1.49870334e-02, 1.57563641e-02, 1.60213295e-02, 1.69074625e-02, 1.64888825e-02, 1.58787450e-02, 1.50671910e-02, 3.11944995e-04, 3.98221062e-04, 2.09843749e-04, 1.86193006e-04, 9.44372390e-04, 7.39550795e-04, 4.90458809e-04, 2.27414628e-04, 2.54356482e-04, 5.80291603e-05, 4.34416626e-04]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_target)
from landlab.components.craters.dig_craters import impactor from landlab import ModelParameterDictionary from landlab import RasterModelGrid import numpy as np import time import pylab # get the needed properties to build the grid: input_file = "./craters_params_init.txt" inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") leftmost_elev = inputs.read_float("leftmost_elevation") initial_slope = inputs.read_float("initial_slope") nt = inputs.read_int("number_of_craters_per_loop") loops = inputs.read_int("number_of_loops") mg = RasterModelGrid(nrows, ncols, dx) mg.set_looped_boundaries(True, True) # create the fields in the grid mg.create_node_array_zeros("planet_surface__elevation") z = mg.create_node_array_zeros() + leftmost_elev z += initial_slope * np.amax(mg.node_y) - initial_slope * mg.node_y mg["node"]["planet_surface__elevation"] = z # + np.random.rand(len(z))/10000. # Display a message print ("Running ...") start_time = time.time()
from __future__ import print_function from six.moves import range from landlab.components.craters import impactor from landlab import ModelParameterDictionary from landlab import RasterModelGrid import numpy as np import time import pylab #get the needed properties to build the grid: input_file = './craters_params.txt' inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') nt = inputs.read_int('number_of_craters_per_loop') loops = inputs.read_int('number_of_loops') mg = RasterModelGrid(nrows, ncols, dx) mg.set_inactive_boundaries(False, False, False, False) #create the fields in the grid mg.add_zeros('topographic__elevation', at='node') mg['node']['topographic__elevation'] = np.load('init.npy') # Display a message
from landlab import ModelParameterDictionary from landlab import RasterModelGrid from landlab.components import FlowRouter as Flow #from landlab.components.stream_power.stream_power import StreamPowerEroder from landlab.components import FastscapeEroder as Fsc from landlab.components import LinearDiffuser as Diff from landlab.components import PrecipitationDistribution #from landlab.plot import channel_profile as prf ###########################INITIALIZE #get the stuff needed to build the grid AND RUN THE MODEL: input_file = './shobe_modClass_params.txt' inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('up_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime//dt) t_plot = inputs.read_float('time_plot') uplift_per_step = uplift_rate * dt #Variable erodibility hard_layer_on_or_off = inputs.read_int('layered') k_erodible=inputs.read_float('k_erodible') #higher k for weaker rock
def __init__(self, input_stream): """ Reads in parameters and initializes the model. Example ------- >>> from six import StringIO >>> p = StringIO(''' ... model_grid_row__count: number of rows in grid ... 4 ... model_grid_column__count: number of columns in grid ... 4 ... plot_interval: interval for plotting to display, s ... 2.0 ... model__run_time: duration of model run, s ... 1.0 ... model__report_interval: time interval for reporting progress, real-time seconds ... 1.0e6 ... surface_bleaching_time_scale: time scale for OSL bleaching, s ... 2.42 ... light_attenuation_length: length scale for light attenuation, cells (1 cell = 1 mm) ... 2.0 ... ''') >>> tsbm = TurbulentSuspensionAndBleachingModel(p) >>> tsbm.node_state array([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]) >>> tsbm.grid.at_node['osl'] array([ 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.]) >>> tsbm.n_xn array([0, 1, 1, 0, 0, 1, 1, 0]) >>> tsbm.fluid_surface_height 3.5 """ # Get a source for input parameters. params = ModelParameterDictionary(input_stream) # Read user-defined parameters nr = params.read_int('model_grid_row__count' ) # number of rows (CSDMS Standard Name [CSN]) nc = params.read_int( 'model_grid_column__count') # number of cols (CSN) self.plot_interval = params.read_float( 'plot_interval') # interval for plotting output, s self.run_duration = params.read_float( 'model__run_time') # duration of run, sec (CSN) self.report_interval = params.read_float( 'model__report_interval') # report interval, in real-time seconds self.bleach_T0 = params.read_float( 'surface_bleaching_time_scale' ) # time scale for bleaching at fluid surface, s self.zstar = params.read_float( 'light_attenuation_length' ) # length scale for light attenuation in fluid, CELLS # Derived parameters self.fluid_surface_height = nr - 0.5 # Calculate when we next want to report progress. self.next_report = time.time() + self.report_interval # Create grid mg = RasterModelGrid(nr, nc, 1.0) # Make the boundaries be walls mg.set_closed_boundaries_at_grid_edges(True, True, True, True) # Set up the states and pair transitions. ns_dict = {0: 'fluid', 1: 'particle'} xn_list = self.setup_transition_list() # Create the node-state array and attach it to the grid node_state_grid = mg.add_zeros('node', 'node_state_map', dtype=int) # For visual display purposes, set all boundary nodes to fluid node_state_grid[mg.closed_boundary_nodes] = 0 # Initialize the node-state array: here, the initial condition is a pile of # resting grains at the bottom of a container. bottom_rows = where(mg.node_y < 0.4 * nr)[0] node_state_grid[bottom_rows] = 1 # Create a data array for bleaching. # Here, osl=optically stimulated luminescence, normalized to the original # signal (hence, initially all unity). Over time this signal may get # bleached out due to exposure to light. self.osl = mg.add_zeros('node', 'osl') self.osl[bottom_rows] = 1.0 self.osl_display = mg.add_zeros('node', 'osl_display') self.osl_display[bottom_rows] = 1.0 # We'll need an array to track the last time any given node was # updated, so we can figure out the duration of light exposure between # update events self.last_update_time = mg.add_zeros('node', 'last_update_time') # Call the base class (RasterCTS) init method super(TurbulentSuspensionAndBleachingModel, \ self).__init__(mg, ns_dict, xn_list, node_state_grid, prop_data=self.osl) # Set up plotting (if plotting desired) if self.plot_interval <= self.run_duration: self.initialize_plotting()
def test_sp_old(): input_str = os.path.join(_THIS_DIR, "drive_sp_params.txt") inputs = ModelParameterDictionary(input_str) nrows = inputs.read_int("nrows") ncols = inputs.read_int("ncols") dx = inputs.read_float("dx") dt = inputs.read_float("dt") time_to_run = inputs.read_float("run_time") uplift = inputs.read_float("uplift_rate") init_elev = inputs.read_float("init_elev") mg = RasterModelGrid((nrows, ncols), xy_spacing=(dx, dx)) mg.set_closed_boundaries_at_grid_edges(False, False, True, True) mg.add_zeros("topographic__elevation", at="node") z = mg.zeros(at="node") + init_elev numpy.random.seed(0) mg["node"]["topographic__elevation"] = z + numpy.random.rand( len(z)) / 1000.0 fr = FlowAccumulator(mg, flow_director="D8") sp = StreamPowerEroder(mg, input_str) elapsed_time = 0.0 while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time fr.run_one_step() sp.erode(mg, dt) mg.at_node["topographic__elevation"][mg.core_nodes] += uplift * dt elapsed_time += dt z_trg = numpy.array([ 5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 1.01830760e-02, 9.58036770e-03, 6.55865452e-03, 3.83441519e-04, 7.91725038e-04, 1.00142749e-02, 8.80798884e-03, 5.78387585e-03, 7.10360582e-05, 8.71292997e-05, 9.81911417e-03, 9.52243406e-03, 7.55093226e-03, 8.70012148e-04, 9.78618342e-04, 1.00629755e-02, 8.49253798e-03, 5.33216680e-03, 1.18274426e-04, 6.39921021e-04, 9.88956320e-03, 9.47119567e-03, 6.43790696e-03, 4.14661940e-04, 2.64555612e-04, 1.00450743e-02, 8.37262908e-03, 5.21540904e-03, 1.87898004e-05, 6.17635497e-04, 9.21286940e-03, 9.34022513e-03, 7.51114450e-03, 6.81820299e-04, 3.59507901e-04, 6.19166921e-03, 7.10456176e-03, 6.62585507e-03, 6.66766715e-04, 6.70637870e-04, 2.10382561e-04, 1.28926298e-04, 3.15428351e-04, 3.63710771e-04, ]) assert_array_almost_equal(mg.at_node["topographic__elevation"], z_trg)
def test_diffusion(): infile = os.path.join(_THIS_DIR, 'diffusion_params.txt') inputs = ModelParameterDictionary(infile, auto_type=True) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') dt = inputs.read_float('dt') time_to_run = inputs.read_float('run_time') init_elev = inputs.read_float('init_elev') mg = RasterModelGrid((nrows, ncols), (dx, dx)) uplift_rate = mg.node_y[mg.core_cells] / 100000. # create the fields in the grid mg.add_zeros('topographic__elevation', at='node') z = mg.zeros(at='node') + init_elev np.random.seed(0) mg['node']['topographic__elevation'] = z + np.random.rand(len(z)) / 1000. mg.set_fixed_value_boundaries_at_grid_edges(True, True, True, True) # instantiate: dfn = LinearDiffuser(mg, **inputs) # perform the loop: elapsed_time = 0. # total time in simulation while elapsed_time < time_to_run: if elapsed_time + dt > time_to_run: dt = time_to_run - elapsed_time dfn.run_one_step(dt) mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_rate * dt elapsed_time += dt z_target = np.array([ 5.48813504e-04, 7.15189366e-04, 6.02763376e-04, 5.44883183e-04, 4.23654799e-04, 6.45894113e-04, 4.37587211e-04, 8.91773001e-04, 9.63662761e-04, 3.83441519e-04, 7.91725038e-04, 9.18166135e-04, 1.02015039e-03, 1.10666198e-03, 1.14866514e-03, 1.20224288e-03, 1.12953135e-03, 1.12966219e-03, 1.00745155e-03, 8.70012148e-04, 9.78618342e-04, 1.12628772e-03, 1.41663596e-03, 2.66338249e-03, 2.80420703e-03, 2.82445061e-03, 2.69263914e-03, 2.44620140e-03, 2.04237613e-03, 4.14661940e-04, 2.64555612e-04, 2.15073330e-03, 2.77965579e-03, 3.22134736e-03, 3.45859244e-03, 4.47224671e-03, 4.25371135e-03, 3.82941648e-03, 3.25127747e-03, 6.81820299e-04, 3.59507901e-04, 3.36577718e-03, 4.20490812e-03, 4.81467159e-03, 5.14099588e-03, 5.15029835e-03, 4.83533539e-03, 5.22312276e-03, 4.37284689e-03, 3.63710771e-04, 5.70196770e-04, 4.65122535e-03, 5.67854747e-03, 6.44757828e-03, 6.85985389e-03, 6.86464781e-03, 6.45159799e-03, 5.65255723e-03, 4.54258827e-03, 2.44425592e-04, 1.58969584e-04, 5.85971567e-03, 7.16648352e-03, 8.10954246e-03, 8.61082386e-03, 8.61350727e-03, 8.10597021e-03, 7.12594182e-03, 5.75483957e-03, 9.60984079e-05, 9.76459465e-04, 6.29476234e-03, 7.70594852e-03, 9.79504842e-03, 1.03829367e-02, 1.03869062e-02, 9.79374998e-03, 8.65447904e-03, 7.07179252e-03, 1.18727719e-04, 3.17983179e-04, 7.43078552e-03, 9.18353155e-03, 1.04682910e-02, 1.11542648e-02, 1.21643980e-02, 1.14930584e-02, 1.02184219e-02, 8.53727126e-03, 9.29296198e-04, 3.18568952e-04, 8.68034110e-03, 1.06702554e-02, 1.21275181e-02, 1.29049224e-02, 1.29184938e-02, 1.21616788e-02, 1.17059081e-02, 9.66728348e-03, 4.69547619e-06, 6.77816537e-04, 1.00128306e-02, 1.21521279e-02, 1.37494046e-02, 1.46053573e-02, 1.46205669e-02, 1.37908840e-02, 1.22146332e-02, 1.01165765e-02, 9.52749012e-04, 4.47125379e-04, 1.12069867e-02, 1.35547122e-02, 1.52840440e-02, 1.62069802e-02, 1.62196380e-02, 1.53169489e-02, 1.35997836e-02, 1.12818577e-02, 6.92531590e-04, 7.25254280e-04, 1.14310516e-02, 1.38647655e-02, 1.66771925e-02, 1.76447108e-02, 1.76515649e-02, 1.66885162e-02, 1.48507549e-02, 1.23206170e-02, 2.90077607e-04, 6.18015429e-04, 1.24952067e-02, 1.49924260e-02, 1.68435913e-02, 1.78291009e-02, 1.88311310e-02, 1.78422046e-02, 1.59665841e-02, 1.34122052e-02, 4.31418435e-04, 8.96546596e-04, 1.34612553e-02, 1.58763600e-02, 1.76887976e-02, 1.86526609e-02, 1.86492669e-02, 1.76752679e-02, 1.68480793e-02, 1.44368883e-02, 9.98847007e-04, 1.49448305e-04, 1.40672989e-02, 1.64140227e-02, 1.81162514e-02, 1.90091351e-02, 1.89959971e-02, 1.80757625e-02, 1.63425116e-02, 1.39643530e-02, 6.91669955e-05, 6.97428773e-04, 1.47340964e-02, 1.66453353e-02, 1.80835612e-02, 1.88335770e-02, 1.88048458e-02, 1.80022362e-02, 1.65110248e-02, 1.44854151e-02, 1.71629677e-04, 5.21036606e-04, 1.40633664e-02, 1.54867652e-02, 1.75865008e-02, 1.81309867e-02, 1.80760242e-02, 1.74501109e-02, 1.63343931e-02, 1.48208186e-02, 3.18389295e-05, 1.64694156e-04, 1.41550038e-02, 1.49870334e-02, 1.57563641e-02, 1.60213295e-02, 1.69074625e-02, 1.64888825e-02, 1.58787450e-02, 1.50671910e-02, 3.11944995e-04, 3.98221062e-04, 2.09843749e-04, 1.86193006e-04, 9.44372390e-04, 7.39550795e-04, 4.90458809e-04, 2.27414628e-04, 2.54356482e-04, 5.80291603e-05, 4.34416626e-04 ]) assert_array_almost_equal(mg.at_node['topographic__elevation'], z_target)
from landlab import RasterModelGrid, CLOSED_BOUNDARY, FIXED_VALUE_BOUNDARY from landlab.io.netcdf import write_netcdf import numpy as np from netCDF4 import Dataset import time #get needed properties to build grid: input_file = 'LL_driver_params.txt' #initialize an object that will supply the parameters: inputs = ModelParameterDictionary(input_file) #load grid properties x = inputs.read_int('x') y = inputs.read_int('y') dx = inputs.read_float('dx') dt = inputs.read_float('dt') run_time = inputs.read_float('run_time') uplift = inputs.read_float('uplift_rate') initial_slope = inputs.read_float('initial_slope') nt = int(run_time//dt) #this is how many loops we'll need #Build the grid mg = RasterModelGrid(x, y, dx) #sp # Load topography output rotated from WRF-Hydro and add to topography field # Since the discharge files were created on the WRF-Hydro topography, we use that topography as our input. The original Landlab topography and the WRF-Hydro topography are almost identical, with only slight differences created by the rotation. topo=Dataset('topography_wrf_hydro.nc')
from landlab.components.flow_routing.route_flow_dn import FlowRouter from landlab.components.stream_power.fastscape_stream_power import SPEroder from landlab.components.nonlinear_diffusion.Perron_nl_diffuse import PerronNLDiffuse from landlab.components.diffusion.diffusion import DiffusionComponent from landlab import ModelParameterDictionary from landlab.plot import channel_profile as prf from landlab.plot.imshow import imshow_node_grid from landlab import RasterModelGrid import numpy as np import pylab #get the needed properties to build the grid: input_file = './coupled_params.txt' inputs = ModelParameterDictionary(input_file) nrows = inputs.read_int('nrows') ncols = inputs.read_int('ncols') dx = inputs.read_float('dx') leftmost_elev = inputs.read_float('leftmost_elevation') initial_slope = inputs.read_float('initial_slope') uplift_rate = inputs.read_float('uplift_rate') runtime = inputs.read_float('total_time') dt = inputs.read_float('dt') nt = int(runtime // dt) uplift_per_step = uplift_rate * dt #instantiate the grid object mg = RasterModelGrid(nrows, ncols, dx) ##create the elevation field in the grid: #create the field
class TestModelParameterDictionary(unittest.TestCase): def setUp(self): from StringIO import StringIO self.param_file = StringIO(_TEST_PARAM_DICT_FILE) self.param_dict = ModelParameterDictionary() self.param_dict.read_from_file(self.param_file) def test_read_file(self): all_keys = set([ 'FLOAT_VAL', 'INT_VAL', 'STRING_VAL', 'TRUE_BOOL_VAL', 'FALSE_BOOL_VAL', ]) param_list = set(self.param_dict.params()) self.assertEqual(param_list, all_keys) def test_read_file_name(self): (prm_fd, prm_file_name) = tempfile.mkstemp() prm_file = os.fdopen(prm_fd, 'w') prm_file.write(_TEST_PARAM_DICT_FILE) prm_file.close() param_dict = ModelParameterDictionary() param_dict.read_from_file(prm_file_name) os.remove(prm_file_name) all_keys = set([ 'FLOAT_VAL', 'INT_VAL', 'STRING_VAL', 'TRUE_BOOL_VAL', 'FALSE_BOOL_VAL', ]) param_list = set(param_dict.params()) self.assertEqual(param_list, all_keys) def test_read_file_like_twice(self): from StringIO import StringIO param_file = StringIO(_TEST_PARAM_DICT_FILE) param_dict_1 = ModelParameterDictionary() param_dict_2 = ModelParameterDictionary() param_dict_1.read_from_file(param_file) param_dict_2.read_from_file(param_file) def test_read_int(self): self.assertEqual(self.param_dict.read_int('INT_VAL'), 1) with self.assertRaises(ParameterValueError): self.param_dict.read_int('FLOAT_VAL') with self.assertRaises(MissingKeyError): self.param_dict.read_int('MISSING_INT') self.assertEqual(self.param_dict.read_int('MISSING_INT', 2), 2) def test_get_int(self): self.assertEqual(self.param_dict.get('INT_VAL', ptype=int), 1) with self.assertRaises(ParameterValueError): self.param_dict.get('FLOAT_VAL', ptype=int) with self.assertRaises(MissingKeyError): self.param_dict.get('MISSING_INT', ptype=int) def test_set_default(self): self.param_dict.setdefault('MISSING_INT', 2) self.assertEqual(self.param_dict.read_int('MISSING_INT'), 2) def test_read_float(self): self.assertEqual(self.param_dict.read_float('FLOAT_VAL'), 2.2) self.assertEqual(self.param_dict.read_float('INT_VAL'), 1) with self.assertRaises(ParameterValueError): self.param_dict.read_float('STRING_VAL') with self.assertRaises(MissingKeyError): self.param_dict.read_float('MISSING_FLOAT') def test_read_string(self): self.assertEqual(self.param_dict.read_string('STRING_VAL'), 'The Landlab') self.assertEqual(self.param_dict.read_string('INT_VAL'), '1') self.assertEqual(self.param_dict.read_string('FLOAT_VAL'), '2.2') with self.assertRaises(MissingKeyError): self.param_dict.read_string('MISSING_STRING') def test_read_bool(self): self.assertEqual(self.param_dict.read_bool('TRUE_BOOL_VAL'), True) self.assertEqual(self.param_dict.read_bool('FALSE_BOOL_VAL'), False) with self.assertRaises(MissingKeyError): self.param_dict.read_bool('MISSING_BOOLEAN') with self.assertRaises(ParameterValueError): self.param_dict.read_bool('STRING_VAL') def test_dict_keys(self): all_keys = set([ 'FLOAT_VAL', 'INT_VAL', 'STRING_VAL', 'TRUE_BOOL_VAL', 'FALSE_BOOL_VAL', ]) self.assertEqual(set(self.param_dict), all_keys) for key in all_keys: self.assertTrue(key in self.param_dict) def test_dict_index(self): self.assertEqual(self.param_dict['INT_VAL'], '1')