def get_project(with_solute=False): if with_solute: p = cmf.project('X') X, = p.solutes else: p = cmf.project() X = None stores = [p.NewStorage('source{}'.format(i)) for i in range(10)] for l, r in zip(stores[:-1],stores[1:]): cmf.LinearStorageConnection(l, r, 1) stores[0].volume = 1 if with_solute: stores[0][X].source = 1 return p, stores, X
def run_model(self): """Runs the model with everything""" # Initialize project project = cmf.project() self.load_cmf_files() # Add cells and properties to them self.mesh_to_cells(project, self.mesh_path) for key in self.ground_dict.keys(): self.configure_cells(project, self.ground_dict[str(key)]) if self.trees_dict: for key in self.trees_dict.keys(): self.add_tree(project, self.trees_dict[str(key)]['face_index'], self.trees_dict[str(key)]['property']) # Create the weather self.create_weather(project) # Create boundary conditions if self.boundary_dict: self.create_boundary_conditions(project) # Run solver self.solve(project, self.solver_settings['tolerance']) # Save the results self.save_results() return project
def __init__(self, begin, end): """Initializes the model and build the core setup""" # tr_soil_GW = Residence time of the water in the soil to the GW self.params = [param("tr_soil_out", 0., 200.), # tr_GW_out = Residence time in the groundwater to # the outlet param('V0_soil', 0., 300.), # beta_soil_out = exponent that changes the form of the # flux from the soil to the outlet param("beta_soil_out", 0.3, 8.0), # ETV1 = the Volume that defines that the evaporation # is lowered because of not enough water in the soil param('ETV1', 0., 300.), # fETV0 = factor the ET is multiplied by, when water is # low param('fETV0', 0., 0.9), # Rate of snow melt param('meltrate', 0.01, 15.), # Snow_melt_temp = Temperature at which the snow melts # (needed because of averaged temp param('snow_melt_temp', -3.0, 3.0) ] self.begin = begin self.end = end # load the weather data and discharge data prec, temp, temp_min, temp_max, Q, wind, sun, \ rel_hum= self.loadPETQ() self.Q = Q # use only one core (faster when model is small cmf.set_parallel_threads(1) # Generate a cmf project with one cell for a lumped model self.project = cmf.project() p = self.project # Create a cell in the project c = p.NewCell(0, 0, 0, 1000) # Add snow storage c.add_storage("Snow", "S") cmf.Snowfall(c.snow, c) # Add the soil and groundwater layers soil = c.add_layer(2.0) # Give the storages a initial volume c.layers[0].volume = 15 # Install a calculation of the evaporation cmf.PenmanMonteithET(soil, c.transpiration) # Create an outlet self.outlet = p.NewOutlet("outlet", 10, 0, 0) # Create the meteo stations self.make_stations(prec, temp, temp_min, temp_max, wind, sun, rel_hum) self.project = p
def solve_ready_project(cmf_data): (ground_list, mesh_path, weather_dict, trees_dict, outputs, solver_settings, boundary_dict) = cmf_data project = cmf.project() project, mesh_info = hydrology.mesh_to_cells(project, mesh_path, False) for ground in ground_list: hydrology.configure_cells(project, ground, mesh_info[ground['mesh']]) if trees_dict: for key in trees_dict.keys(): hydrology.add_tree_to_project(project, trees_dict[key]['face_index'], trees_dict[key]['property']) # Create the weather if weather_dict: hydrology.create_weather(project) # Create boundary conditions if boundary_dict: hydrology.create_boundary_conditions(project) return project, solver_settings, outputs
def __init__(self, par): cmf.set_parallel_threads(1) # run the model self.project = cmf.project() self.cell = self.project.NewCell(x=0, y=0, z=238.628, area=1000, with_surfacewater=True) c = self.cell r_curve = cmf.VanGenuchtenMualem(Ksat=10**par.pKsat, phi=par.porosity, alpha=par.alpha, n=par.n) # Make the layer boundaries and create soil layers lthickness = [.01] * 5 + [0.025] * 6 + [0.05] * 6 + [0.1] * 5 ldepth = np.cumsum(lthickness) # Create soil layers and pick the new soil layers if they are inside of the evaluation depth's for d in ldepth: c.add_layer(d, r_curve) # Use a Richards model c.install_connection(cmf.Richards) # Use shuttleworth wallace self.ET = c.install_connection(cmf.ShuttleworthWallace) c.saturated_depth = 0.5 self.gw = self.project.NewOutlet('groundwater', x=0, y=0, z=.9) cmf.Richards(c.layers[-1], self.gw) self.gw.potential = c.z - 0.5 #IMPORTANT self.gw.is_source = True self.gwhead = cmf.timeseries.from_scalar(c.z - 0.5) self.solver = cmf.CVodeIntegrator(self.project, 1e-9)
def project_with_cells(cmf_data): (ground_list, mesh_paths, weather_dict, trees_dict, outputs, solver_settings, boundary_dict) = cmf_data project = cmf.project() return hydrology.mesh_to_cells(project, mesh_paths, False)
def test_describe(self): p = cmf.project() c = p.NewCell(0, 0, 0, 1000, True) p.meteo_stations.add_station('Giessen', (0, 0, 0)) c.add_layer(1.0) text = cmf.describe(p).split('\n') self.assertGreaterEqual(len(text), 25)
def canopyStorage(): import cmf import pylab as plt p = cmf.project() c = p.NewCell(0, 0, 0, 1000, True) # Add a single layer of 1 m depth l = c.add_layer(1.0, cmf.VanGenuchtenMualem()) # Use GreenAmpt infiltration from surface water c.install_connection(cmf.GreenAmptInfiltration) # Add a groundwater boundary condition gw = p.NewOutlet('gw', 0, 0, -2) # Use a free drainage connection to the groundwater cmf.FreeDrainagePercolation(l, gw) # Add some rainfall c.set_rainfall(5.0) # Make c.canopy a water storage c.add_storage('Canopy', 'C') # Split the rainfall from the rain source (RS) between # intercepted rainfall (RS->canopy) and throughfall (RS-surface) cmf.Rainfall(c.canopy, c, False, True) # RS->canopy, only intercepted rain cmf.Rainfall(c.surfacewater, c, True, False) # RS->surface, only throughfall # Use an overflow mechanism, eg. the famous Rutter-Interception Model cmf.RutterInterception(c.canopy, c.surfacewater, c) # And now the evaporation from the wet canopy (using a classical Penman equation) cmf.CanopyStorageEvaporation(c.canopy, c.evaporation, c) solver = cmf.CVodeIntegrator(p, 1e-9) res = [l.volume for t in solver.run(solver.t, solver.t + cmf.day, cmf.min * 15)] plt.figure() plt.plot(res) plt.show()
def __init__(self): self.Params = [ Param("tr_first_out", 0., 300), Param("tr_first_river", 0., 300), Param("tr_first_second", 0., 300), Param("tr_second_third", 0., 300), Param("tr_second_river", 0., 300), Param("tr_third_river", 0., 300), Param("tr_river_out", 0., 300), Param("beta_first_out", 0., 4), Param("beta_first_river", 0., 4), Param("beta_first_second", 0., 4), Param("beta_second_river", 0., 4), Param("beta_second_third", 0., 4), Param("beta_third_river", 0., 4), Param("beta_river_out", 0., 4), Param("canopy_lai", 1., 10), Param("canopy_closure", 0., 1.0), Param("snow_meltrate", 0.1, 15.), Param("snow_melt_temp", -5.0, 5.0), Param("V0_first_out", 0., 200), Param("V0_first_river", 0., 200), Param("V0_first_second", 0., 200), Param("ETV0", 0, 200), Param("fETV0", 0., 0.85) ] precipitation, temperature_avg, temperature_min, \ temperature_max, discharge = utils.load_data( "observed_discharge.txt", "temperature_max_min_avg.txt", "precipitation.txt", 2976.41 ) self.Q = discharge cmf.set_parallel_threads(1) self.project = cmf.project() project = self.project cell = project.NewCell(0, 0, 0, 1000) cell.add_storage("Snow", "S") cmf.Snowfall(cell.snow, cell) cell.add_layer(2.0) cell.add_layer(5.0) cell.add_layer(10.0) cmf.HargreaveET(cell.layers[0], cell.transpiration) self.outlet = project.NewOutlet("outlet", 10, 0, 0) self.make_stations(precipitation, temperature_avg, temperature_min, temperature_max) self.river = cell.add_storage("River", "R") self.canopy = cell.add_storage("Canopy", "C") self.begin = datetime.datetime(1979, 1, 1) self.end = datetime.datetime(1986, 12, 31)
def test_describe(self): p = cmf.project() c = p.NewCell(0, 0, 0, 1000, True) p.meteo_stations.add_station('Giessen', (0, 0, 0)) c.add_layer(1.0) text = cmf.describe(p).split('\n') print('cmf.describe(project) returns {} lines'.format(len(text))) self.assertGreaterEqual(len(text), 5)
def __init__(self): self.p = cmf.project() self.c = self.p.NewCell(0, 0, 0, 1000, with_surfacewater=True) self.c.add_layer(1.0) self.c: cmf.Cell cmf.RutterInterception.use_for_cell(self.c) self.et = cmf.ShuttleworthWallace.use_for_cell(self.c) cmf.MatrixInfiltration(self.c.layers[0], self.c.surfacewater)
def __init__(self): p = cmf.project('N DOC') self.project = p self.decompcell = self.cell_setup() self.outlet = self.make_boundaries() self.initialize() self.decompcell.depose_litter(10000, 0)
def test_mesh_to_cells(obj_file_paths): project = cmf.project() hydrology.mesh_to_cells(project, [ obj_file_paths, ], False) assert project assert project.cells
def testState(self): p = cmf.project('X Y Z') X, Y, Z = p.solutes ws = p.NewStorage('storage') ws.volume = 1.0 ws[X].state = 1.0 ws.volume = 2.0 self.assertAlmostEqual(ws[X].conc, 0.5) self.assertAlmostEqual(ws[X].state, 1.0) self.assertAlmostEqual(ws[Y].conc, 0.0)
def __init__(self, dataprovider: DataProvider): """ Creates the basic structure of the model """ self.data = dataprovider self.project = cmf.project() self.cell: cmf.Cell = self.project.NewCell(0, 0, 0, 1000) self.create_nodes() self.data.add_stations(self.project) self.create_connections(spotpy.parameter.create_set(self, 'optguess'))
def create_project(W0=0.9): """ Creates the cmf project with a single cell and one layer :return: """ p = cmf.project() c = p.NewCell(0, 0, 0, 1000, with_surfacewater=True) l = c.add_layer(0.1) c.set_rainfall(l.get_capacity()) si_con = cmf.SimpleInfiltration(l, c.surfacewater, W0) return p, si_con
def __init__(self, climate_file='data/climate.csv'): self.project = cmf.project() self.cell = self.project.NewCell(0, 0, 0, 1000) self.soil = self.cell.add_layer(1.0) self.gw = self.cell.add_layer(1.0) self.snow = self.cell.add_storage('Snow', 'S') self.outlet = self.project.NewOutlet('outlet') self.meteo, self.rainstation = load_climate_data( self.project, climate_file)
def __init__(self, subsurface_lateral_connection, surface_lateral_connection=None, layercount=0): """ Creates the cmf project :param subsurface_lateral_connection: Type of lateral subsurface connection, eg. cmf.Darcy :param surface_lateral_connection: Type of lateral surface flux connection, eg. cmf.KinematicSurfaceRunoff or None :param layercount: Number of layers in the subsurface :return: """ p = cmf.project() shp = Shapefile('data/vollnkirchner_bach_cells.shp') # Create cells self.outlet_cells = [] for feature in shp: # Create a cell for each feature in the shape file c = cmf.geometry.create_cell(p, feature.shape, feature.HEIGHT, feature.OID, with_surfacewater=False) # If it is an outlet feature, add cell to the list of outletcells if feature.LANDUSE_CU.startswith('outlet'): self.outlet_cells.append(c) else: # If it is a normal upload cell, add layers self.build_cell(c, layercount) # Build topology cmf.geometry.mesh_project(p, verbose=True) # Connect cells with fluxes cmf.connect_cells_with_flux(p, subsurface_lateral_connection) if surface_lateral_connection: cmf.connect_cells_with_flux(p, surface_lateral_connection) # Connect outlets with neighbor cells for o_cell in self.outlet_cells: self.connect_outlet_cell(o_cell, subsurface_lateral_connection, surface_lateral_connection) # Load driver data load_meteo(p) self.project = p self.solver = cmf.CVodeIntegrator(p, 1e-9) self.solver.t = p.meteo_stations[0].T.begin
def __init__(self, begin, end): """ Initialisiert das Modell und baut das Grundsetup zusammen MP111 - Änderungsbedarf: Sehr groß, hier wird es Euer Modell definiert Verständlichkeit: mittel """ # TODO: Parameterliste erweitern und anpassen. # Wichtig: Die Namen müssen genau die gleichen sein, # wie die Argumente in der Funktion setparameters. # # Parameter werden wie folgt definiert: # param(<Name>,<Minimum>,<Maximum>) self.params = [ param('tr', 0., 1000.), param('ETV1', 0., 1000.), param('Vr', 0., 1000.), param('fETV0', 0., 1.), param('beta', 0.3, 5.0) ] # Lädt die Treiber Daten P, T, Tmin, Tmax, Q = self.loadPETQ() self.Q = Q # Nutze nur einen Kern - für unser Modell ist das schneller cmf.set_parallel_threads(1) # Erzeuge ein Projekt mit einer Zelle für lumped Modell self.project = cmf.project() p = self.project c = p.NewCell(0, 0, 0, 1000) # Füge Speicher zur Zelle l = c.add_layer(1.0) # TODO: Weitere Layer / Speicher zur Zelle hinzufügen # Verdunstung cmf.HargreaveET(l, c.transpiration) # Outlet self.outlet = p.NewOutlet('outlet', 10, 0, 0) # Regen self.makestations(P, T, Tmin, Tmax) self.project = p self.begin = begin self.end = end
def create_project(self): """ Creates and CMF project with an outlet and other basic stuff and returns it. :return: cmf project and cmf outlet """ # Use only a single thread, that is better for a calibration run and # for small models cmf.set_parallel_threads(1) # make the project p = cmf.project() # make the outlet outlet = p.NewOutlet("outlet", 10, 0, 0) return p, outlet
def __init__(self, size, residence_time=1.0): """ Parameters ---------- size residence_time """ self.project = p = cmf.project() self.storages = [] self.outlet = p.NewOutlet('outlet', 0, 0, 0) for i in range(1, size+1): stor = p.NewStorage("S{}".format(i), i, 0, i) if self.storages: cmf.LinearStorageConnection(stor, self.storages[-1], residence_time / size) else: cmf.LinearStorageConnection(stor, self.outlet, residence_time / size) self.storages.append(stor)
def __init__(self, begin: datetime.datetime, end: datetime.datetime, subcatchment_names): """ :param begin: :param end: """ project = cmf.project() # Add outlet self.outlet = project.NewOutlet("Outlet", 50, 0, 0) self.project = project self.begin = begin self.end = end self.subcatchment_names = subcatchment_names self.dis_eval, self.subcatchments = self.load_data() self.params = self.create_params() self.cell_list = self.create_cells() cmf.set_parallel_threads(1)
def first_simple_model(): import cmf import datetime p = cmf.project() # Create W1 in project p W1 = p.NewStorage(name="W1",x=0,y=0,z=0) # Create W2 in project p without any volume as an initial state W2 = p.NewStorage(name="W2",x=10,y=0,z=0) # Create a linear storage equation from W1 to W2 with a residence time tr of one day q = cmf.kinematic_wave(source=W1,target=W2,residencetime=1.0) # Set the initial state of w1 to 1m³ of water. W1.volume = 1.0 # Create Outlet Out = p.NewOutlet(name="Outlet",x=20,y=0,z=0) qout = cmf.kinematic_wave(source=W2,target=Out,residencetime=2.0) # Create a Neumann Boundary condition connected to W1 In = cmf.NeumannBoundary.create(W1) # Create a timeseries with daily alternating values. In.flux = cmf.timeseries(begin = datetime.datetime(2012,1,1), step = datetime.timedelta(days=1), interpolationmethod = 0) for i in range(10): # Add 0.0 m3/day for even days, and 1.0 m3/day for odd days In.flux.add(i % 2) # Create an integrator for the ODE represented by project p, with an error tolerance of 1e-9 solver = cmf.RKFIntegrator(p,1e-9) # Set the intitial time of the solver solver.t = datetime.datetime(2012,1,1) # Iterate the solver hourly through the time range and return for each time step the volume in W1 and W2 result = [[W1.volume,W2.volume] for t in solver.run(datetime.datetime(2012,1,1),datetime.datetime(2012,1,7),datetime.timedelta(hours=1))] import pylab as plt plt.plot(result) plt.xlabel('hours') plt.ylabel('Volume in $m^3$') plt.legend(('W1','W2')) plt.show()
def create_project(self): """ Creates the cmf project with its basic elements """ # Use only a single thread, that is better for a calibration run and for small models cmf.set_parallel_threads(1) # make the project p = cmf.project() # make a new cell c = p.NewCell(0, 0, 0, 1000) # Add a storage layer = c.add_layer(1.0) # ET cmf.HargreaveET(layer, c.transpiration) # Outlet outlet = p.NewOutlet('outlet', 10, 0, 0) return p, outlet
def run_model(folder: str) -> cmf.project: """ Runs the model with everything. :return: Simulated CMF project """ # Initialize project project = cmf.project() (ground_list, mesh_paths, weather_dict, trees_dict, outputs, solver_settings, boundary_dict) = load_cmf_files(folder, False) # Add cells and properties to them project, mesh_info = mesh_to_cells(project, mesh_paths) for ground in ground_list: configure_cells(project, ground, mesh_info[ground['mesh']]) if trees_dict: for key in trees_dict.keys(): add_tree_to_project(project, trees_dict[key]['face_index'], trees_dict[key]['property']) # Create the weather if weather_dict: create_weather(project) # Create boundary conditions if boundary_dict: create_boundary_conditions(project) # Run solver results = solve_project(project, solver_settings, outputs) # Save the results save_results(results, folder) return project
def basic_model_setup(): """ Creates the basic layout needed for every model structure. :return: None """ # Basic Layout, same for all possible models prec = data["prec"] obs_discharge = data["discharge"] t_mean = data["t_mean"] t_min = data["t_min"] t_max = data["t_max"] self.obs_discharge = obs_discharge # Use only one core (quicker for smaller models) cmf.set_parallel_threads(1) # Generate a project with one cell for a lumped model self.project = cmf.project() project = self.project # Add one cell, which will include all other parts. The area is set # to 1000 m², so the units are easier to understand cell = project.NewCell(0, 0, 0, 1000) # Add a first layer, this one is always present, as a model with no # layers makes no sense first_layer = cell.add_layer(2.0) # Add an evapotranspiration cmf.HargreaveET(first_layer, cell.transpiration) # Create the CMF meteo and rain stations weather_stations.make_stations(self.project, prec, t_mean, t_min, t_max) # Create an outlet self.outlet = project.NewOutlet("outlet", 10, 0, 0)
def __init__(self,begin,end, with_valid_data = False, shift_one_day = False): """ Initializes the model and builds the core setup begin: begin of the calibration period eng: end of the calibration period with_calib_data: save also the data from the validation period the calibration is still only done form 'begin' to 'end' """ # tr_S = Residence time of the water in the soil to the GW self.params = [param('tr_soil_GW',0.5,150.), # tr_soil_river = residence time from soil to river param("tr_soil_fulda", 0.5,55.), # tr_surf = Residence time from surface param('tr_surf',0.001,30), # tr_GW_l = residence time in the lower groundwate param('tr_GW_l',1.,1000.), # tr_GW_u = Residence time in the upper groundwater to the river param('tr_GW_u_fulda',1.,750.), # tr_GW_u_GW_l = residencete time to GW_l from GW_u param("tr_GW_u_GW_l", 10., 750.), # tr_fulda = Residence time in the river (in days) param('tr_fulda', 0., 3.5), # V0_soil = field capacity for the soil param('V0_soil',15.,350.), # beta_P_soil = Exponent that changes the form of the flux from the soil param('beta_soil_GW',0.5,3.2), # beta_fulda = exponent that changes the form of the flux from the soil param("beta_fulda", 0.3,4.), # ETV1 = the Volume that defines that the evaporation is lowered because of not enough water param('ETV1',0.,100.), # fETV0 = factor the ET is multiplied with when water is low param('fETV0',0.,0.25), # Rate of snow melt param('meltrate',0.15,10.), # Snow_melt_temp = Temperature at which the snow melts (needed because of averaged temp param('snow_melt_temp',-1.0,4.2) , # #Qd_max = maximal flux from lower groundwater to drinking water production # param('Qd_max', 0.,3.), # # tw_thresholt = amount of water that can't be slurped out by the water pumps # param("TW_threshold", 0.,100.), # LAI = leaf area index param('LAI', 1.,12.), # Canopy Closure param("CanopyClosure",0.,0.5), # Ksat = saturated conductivity of the soil param("Ksat", 0., 1) ] # loads the data P,T,Tmin,Tmax,Q = self.loadPETQ() self.Q=Q # only use one core (quicker for small models) cmf.set_parallel_threads(1) # Generate a project with on ecell for a lumped model self.project = cmf.project() p = self.project # Add cell for soil and so on (x,y,z,area) c = p.NewCell(0,0,0,1000) # Add snow storage c.add_storage('Snow','S') cmf.Snowfall(c.snow,c) # Surfacewater is treated as a storage c.surfacewater_as_storage() # Add the soil and groundwater layers to the soil cell soil = c.add_layer(2.0) gw_upper = c.add_layer(5.0) gw_lower = c.add_layer(20.0) # Fill storages c.layers[0].volume = 15 c.layers[1].volume = 80 c.layers[2].volume = 120 # Evapotranspiration cmf.HargreaveET(soil,c.transpiration) #cmf.PenmanMonteith() # Add the Fulda River self.fulda = p.NewOpenStorage(name="Fulda",x=0,y=0,z=0, area = 3.3*10**6) # Giving the Fulda a mean depth self.fulda.potential = 1.5 # add the drinking water outlet # self.trinkwasser = p.NewOutlet('trinkwasser',20,0,0) # Outlet self.outlet = p.NewOutlet('outlet',10,0,0) # Storage for the interception I=c.add_storage('Canopy','C') # Rain self.makestations(P,T,Tmin,Tmax) self.project = p self.begin = begin self.end = end self.with_valid_data = with_valid_data self.shift_one_day = shift_one_day
def _run(self,alpha=None,n=None,porosity=None,ksat=None): #return alpha,n,porosity,ksat ''' Runs the model instance Input: Parameter set (in this case VAN-Genuchten Parameter alpha,n,porosity,ksat) Output: Simulated values on given observation days ''' #Check if given parameter set is in realistic boundaries if alpha<self.bound[0][0] or alpha>self.bound[0][1] or ksat<self.bound[1][0] \ or ksat>self.bound[1][1] or n<self.bound[2][0] or n>self.bound[2][1] or \ porosity<self.bound[3][0] or porosity>self.bound[3][1]: print('The following combination was ignored') text='n= '+str(n) print(text) text='alpha='+str(alpha) print(text) text='ksat= '+str(ksat) print(text) text='porosity= '+str(porosity) print(text) print('##############################') return self.observations*-np.inf else: project=cmf.project() cell = project.NewCell(x=0,y=0,z=0,area=1000, with_surfacewater=True) text='n= '+str(n) print(text) text='alpha='+str(alpha) print(text) text='ksat= '+str(ksat) print(text) text='porosity= '+str(porosity) print(text) print('##############################') r_curve = cmf.VanGenuchtenMualem(Ksat=ksat,phi=porosity,alpha=alpha,n=n) layers=5 ldepth=.01 for i in range(layers): depth = (i+1) * ldepth cell.add_layer(depth,r_curve) cell.install_connection(cmf.Richards) cell.install_connection(cmf.ShuttleworthWallace) cell.saturated_depth =.5 solver = cmf.CVodeIntegrator(project,1e-6) self._load_meteo(project) gw = project.NewOutlet('groundwater',x=0,y=0,z=.9)#layers*ldepth) cmf.Richards(cell.layers[-1],gw) gw.potential = -.5 #IMPORTANT gw.is_source=True solver.t = self.datastart Evalstep,evallist=0,[] rundays=(self.dataend-self.datastart).days for t in solver.run(solver.t,solver.t + timedelta(days=rundays),timedelta(hours=1)): if self.gw_array['Date'].__contains__(t)==True: Gw_Index=np.where(self.gw_array['Date']==t) gw.potential=self.gw_array[self.piezometer][Gw_Index] print(gw.potential) #TO DO: CHECK IF SOMETHING HAPPENS HERE!!!! if t > self.analysestart: if Evalstep !=len(self.eval_dates) and t == self.eval_dates[Evalstep]: evallist.append(cell.layers.wetness[0]*cell.layers.porosity[0]*100) Evalstep+=1 return evallist
def simple1D(): from matplotlib import pyplot as plt import cmf from datetime import datetime, timedelta project = cmf.project() # Add one cell at position (0,0,0), Area=1000m2 cell = project.NewCell(0, 0, 0, 1000, with_surfacewater=True) # Create a retention curve r_curve = cmf.VanGenuchtenMualem(Ksat=1, phi=0.5, alpha=0.01, n=2.0) # Add ten layers of 10cm thickness for i in range(10): depth = (i + 1) * 0.1 cell.add_layer(depth, r_curve) # Connect layers with Richards perc. # this can be shorten as cell.install_connection(cmf.Richards) # Create solver solver = cmf.CVodeIntegrator(project, 1e-6) solver.t = cmf.Time(1, 1, 2011) # Create groundwater boundary (uncomment to use it) # Create the boundary condition gw = project.NewOutlet('groundwater', x=0, y=0, z=-1.1) # Set the potential gw.potential = -2 # Connect the lowest layer to the groundwater using Richards percolation gw_flux=cmf.Richards(cell.layers[-1],gw) # Set inital conditions # Set all layers to a potential of -2 m cell.saturated_depth = 2. # 100 mm water in the surface water storage cell.surfacewater.depth = 0.1 # The run time loop, run for 72 hours # Save potential and soil moisture for each layer potential = [cell.layers.potential] moisture = [cell.layers.theta] for t in solver.run(solver.t, solver.t + timedelta(days=7), timedelta(hours=1)): potential.append(cell.layers.potential) moisture.append(cell.layers.theta) """ # Plot results plt.subplot(211) plt.plot(moisture) plt.ylabel(r'Soil moisture $\theta [m^3/m^3]$') plt.xlabel(r'$time [h]$') plt.grid() plt.subplot(212) plt.plot(potential) plt.ylabel(r'Water head $\Psi_{tot} [m]$') plt.xlabel(r'$time [h]$') plt.grid() plt.show() """ print(cell.vegetation)
cmf.RutterInterception(c.canopy, c.surfacewater, c) # And now the evaporation from the wet canopy (using a classical Penman equation) cmf.CanopyStorageEvaporation(c.canopy, c.evaporation, c) solver = cmf.CVodeIntegrator(p, 1e-9) res = [l.volume for t in solver.run(solver.t, solver.t + cmf.day, cmf.min * 15)] plt.figure() plt.plot(res) plt.show() #canopyStorage() #----------------------------------------------------------------------------------------------------------------------# import cmf import numpy as np from datetime import datetime,timedelta # Create a project project = cmf.project() print('rain stations', project.rainfall_stations) # Create a timeseries, starting Jan 1st, 2010 with 1h step, with random data raindata = cmf.timeseries.from_array(datetime(2010,1,1), timedelta(hours=1), np.random.uniform(0,30,24*365)) # Add a rainfall station to the project rainstation = project.rainfall_stations.add(Name='Random station', Data=raindata, Position=(0,0,0)) print('rain stations', project.rainfall_stations)
def __init__(self, begin, end): """Initializes the model and build the core setup""" # tr_soil_GW = Residence time of the water in the soil to the GW self.params = [ spotpy.parameter.List("tr_soil_gw", [361.95603672540824, 361.95603672540824]), spotpy.parameter.List("tr_soil_out", [86.36633856546166, 86.36633856546166]), spotpy.parameter.List("tr_gw_out", [81.8626412596028, 81.8626412596028]), spotpy.parameter.List("V0_soil", [291.9533350694828, 291.9533350694828]), spotpy.parameter.List("beta_soil_gw", [2.1866023626527475, 2.1866023626527475]), spotpy.parameter.List("beta_soil_out", [0.2, 0.2]), spotpy.parameter.List("ETV1", [101.66837396299148, 101.66837396299148]), spotpy.parameter.List("fETV0", [0.4727208059864018, 0.4727208059864018]), # spotpy.parameter.List("meltrate", # [7.609473369272333, # 7.609473369272333]), # spotpy.parameter.List("snow_melt_temp", # [2.887783422377442, # 2.887783422377442]), spotpy.parameter.List("LAI", [4.865867934808, 4.865867934808]), spotpy.parameter.List("CanopyClosure", [0.1924997461816065, 0.1924997461816065]), ] self.begin = begin self.end = end # load the weather data and discharge data prec, temp, temp_min, temp_max, Q, = self.loadPETQ() self.Q = Q # use only one core (faster when model is small cmf.set_parallel_threads(1) # Generate a cmf project with one cell for a lumped model self.project = cmf.project() p = self.project # Create a cell in the projectl_evapotranspiration c = p.NewCell(0, 0, 0, 1000, True) # # Add snow storage # c.add_storage("Snow", "S") # cmf.Snowfall(c.snow, c) # Add the soil and groundwater layers soil = c.add_layer(2.0) gw_upper = c.add_layer(5.0) # Give the storages a initial volume soil.volume = 15 gw_upper.volume = 80 # Create a storage for Interception I = c.add_storage("Canopy", "C") # Install a calculation of the evaporation cmf.HargreaveET(soil, c.transpiration) # Create an outlet self.outlet = p.NewOutlet("outlet", 10, 0, 0) # Create the meteo stations self.make_stations(prec, temp, temp_min, temp_max) self.project = p