### Setup Virtual Environment and Install Dependencies Source: https://github.com/aquacropos/aquacrop/blob/master/CONTRIBUTING.md Use this command to create a virtual environment and install project dependencies. Ensure you activate the environment before proceeding. ```bash virtualenv venv source venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Install AquaCrop and Dependencies Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Uncomment and run this cell to install the necessary libraries if they are not already present. ```python # uncomment if required # !pip install aquacrop matplotlib seaborn # from google.colab import output # output.clear() ``` -------------------------------- ### Setup AquaCrop Model with Shallow Groundwater (2m) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Configures and runs an AquaCrop model simulation with a shallow groundwater table at 2 meters depth. This is a variation of the previous setup, demonstrating the impact of different groundwater table depths on the simulation results. ```python groundwater_2m = GroundWater('Y','Constant',dates=[f'{2000}/09/01'], values=[2]) model = AquaCropModel(sim_start_time=f'{2000}/09/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=clay_loam, crop=wheat_nov, irrigation_management=net_irr, initial_water_content=fc, groundwater=groundwater_2m, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_W_NetIrr_GW2m_fixedStart') run_comparison('Hyd_W_NetIrr_GW2m_2', model) ``` -------------------------------- ### Install and Import AquaCrop-OSPy Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_2.ipynb Installs the aquacrop library and imports necessary modules. Use the commented-out line if you prefer not to compile modules ahead-of-time. ```python # !pip install aquacrop # from google.colab import output # output.clear() ``` ```python # import os # os.environ['DEVELOPMENT'] = 'True' ``` ```python from aquacrop import AquaCropModel, Soil, Crop, InitialWaterContent, IrrigationManagement from aquacrop.utils import prepare_weather, get_filepath import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns ``` -------------------------------- ### Install AquaCrop Package Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_3.ipynb Installs the AquaCrop package. This is a prerequisite for running the model. ```python # !pip install aquacrop # from google.colab import output # output.clear() ``` -------------------------------- ### Find Good Starting Point for Optimization Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_3.ipynb Defines a function to generate random irrigation strategies and evaluate them to establish a good starting point for local optimization. This is useful when using local minimization functions to ensure a better overall result. ```python def get_starting_point(num_smts,max_irr_season,num_searches): """ find good starting threshold(s) for optimization """ # get random SMT's x0list = np.random.rand(num_searches,num_smts)*100 rlist=[] # evaluate random SMT's for xtest in x0list: r = evaluate(xtest,max_irr_season,) rlist.append(r) # save best SMT x0=x0list[np.argmin(rlist)] return x0 ``` ```python get_starting_point(4,300,10) ``` -------------------------------- ### Initialize and Run AquaCrop Model with Initial Water Content Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up the AquaCrop model with manual initial water content and runs the simulation. Use this to simulate crop growth under specific starting soil moisture conditions. ```python # IWC wetTop = InitialWaterContent('Prop','Depth',[0.5,2],['FC','WP']) wetTopManual = InitialWaterContent('Pct', 'Depth',[0.5,2], [50, 30]) model = AquaCropModel(sim_start_time=f'{2000}/08/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=paddy_soil, crop=local_rice, field_management=bunds20, irrigation_management=irr_mngt, initial_water_content=wetTopManual, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_Rice_wetTop') run_comparison('Hyd_Rice_wetTop', model) ``` -------------------------------- ### Initialize Soil, Crop, and Water Content Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_2.ipynb Sets up the soil type, crop, and initial soil water conditions for the simulation. The 'SandyLoam' soil, 'Maize' crop, and 'FC' (Field Capacity) initial water content are used in this example. ```python soil= Soil('SandyLoam') crop = Crop('Maize',planting_date='05/01') initWC = InitialWaterContent(value=['FC']) ``` -------------------------------- ### Install and Import AquaCrop-OSPy Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_4.ipynb Installs the AquaCrop-OSPy library and its dependencies. It also includes an option to clear the output, which can be useful in interactive environments. ```python # !pip install aquacrop tqdm matplotlib seaborn # from google.colab import output # output.clear() ``` -------------------------------- ### Setup AquaCrop Model with Irrigation Schedule Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Configures and runs the AquaCrop model with a defined irrigation schedule, weather data, soil, and crop. Ensure necessary libraries like pandas are imported. ```python irri_dates = ['2000-04-26', '2000-04-27', '2000-04-28', '2000-04-30', '2000-05-10'] n_years=len(irri_dates) depths=[21, 22, 23, 24, 25] schedule=pd.DataFrame([irri_dates,depths]).T # create pandas DataFrame schedule.columns=['Date','Depth'] # name columns irr_schedule = IrrigationManagement(irrigation_method=3, Schedule =schedule) # Brussels climate filepath=get_filepath('brussels_climate.txt') brussels_weather = prepare_weather(filepath) # Loamy sand soil loamy_sand = Soil(soil_type='LoamySand') # crops potato = Crop('PotatoLocalGDD', planting_date='04/25') # IWC fc = InitialWaterContent(value=['FC']) model = AquaCropModel(sim_start_time=f'{2000}/04/25', sim_end_time=f'{2000}/12/31', weather_df=brussels_weather, soil=loamy_sand, crop=potato, irrigation_management=irr_schedule, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Bru_Pot_Irr150RAW_noEToAdj') run_comparison('Bru_Pot_Irr150RAW_noEToAdj', model) ``` -------------------------------- ### Install AquaCrop-OSPy from GitHub Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb If pip installation fails, install AquaCrop-OSPy directly from its GitHub repository. This method is useful for obtaining the latest development version. ```python # !pip install git+https://github.com/aquacropos/aquacrop # from google.colab import output # output.clear() ``` -------------------------------- ### Setup AquaCrop Model with Shallow Groundwater (1m) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Configures and runs an AquaCrop model simulation with a shallow groundwater table at 1 meter depth. It includes preparing weather data, defining soil and crop parameters, and setting up irrigation management based on TAW. The conversion from RAW to TAW for net irrigation is explained. ```python # Hyderabad climate filepath=get_filepath('hyderabad_climate.txt') hyderabad_weather = prepare_weather(filepath) # Exercise states 30% of RAW, that's what I have input into the irrigation file in AQ-Win # AQ-Py only deals with TAW, not RAW, so a conversion must be done. # Conversion is based on the p_up2 attribute of crop, reflects proportion of TAW that is RAW. # BUT Win works from top down, whereas Py works from bottom up when measuring SMT # In this case (WheatGDD) has p_up2 of 0.65 so 30 * 0.65 = 0.195 # Then invert the percentage to get bottom-up value: 1 - 0.195 = 80.5 % of TAW net_irr = IrrigationManagement(irrigation_method=4,NetIrrSMT=80.5) clay_loam = Soil(soil_type='ClayLoam') wheat_nov = Crop('HydWheatGDD', planting_date='11/01') fc = InitialWaterContent(value=['FC']) groundwater_1m = GroundWater('Y','Constant',dates=[f'{2000}/09/01'], values=[1]) model = AquaCropModel(sim_start_time=f'{2000}/09/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=clay_loam, crop=wheat_nov, irrigation_management=net_irr, initial_water_content=fc, groundwater=groundwater_1m, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_W_NetIrr_GW1m') run_comparison('Hyd_W_NetIrr_GW1m_2', model) ``` -------------------------------- ### Create and Configure AquaCropModel Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Combines all specified components (weather, soil, crop, initial water content) into an AquaCropModel. Sets the simulation start and end dates. ```python # combine into aquacrop model and specify start and end simulation date model = AquaCropModel(sim_start_time=f'{1979}/10/01', sim_end_time=f'{1985}/05/30', weather_df=weather_data, soil=sandy_loam, crop=wheat, initial_water_content=InitWC) ``` -------------------------------- ### Run AquaCrop Simulation with Constant Depth Irrigation Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop model for potato cultivation with a constant depth irrigation method (irrigation_method=0). This example initializes the model and then runs it to completion, followed by a comparison function. ```python # Loamy sand soil loamy_sand = Soil(soil_type='LoamySand') # crop potato = Crop('PotatoLocalGDD', planting_date='04/25') # create model with IrrMethod= Constant depth model = AquaCropModel(sim_start_time=f'{1976}/04/25', sim_end_time=f'{2005}/12/31', weather_df=brussels_weather, soil=loamy_sand, crop=potato, irrigation_management=IrrigationManagement(irrigation_method=0), initial_water_content=fc, ) model.run_model(till_termination=True) # model._initialize() # while model._clock_struct.model_is_finished is False: # # get depth to apply, RAW = 36%, p_up2 = 0.6 so TAW = 21.6, inverse is 78.4 # depth=get_depth(model,78.4) # model._param_struct.IrrMngt.depth=depth # model.run_model(initialize_model=False) # python_output(model, 'Bru_Pot_Rainfed') run_comparison('Bru_Pot_Rainfed', model) ``` -------------------------------- ### Install AquaCrop Package Source: https://github.com/aquacropos/aquacrop/blob/master/README.md Install the AquaCrop library using pip. This is the standard method for adding the package to your Python environment. ```bash pip install aquacrop ``` -------------------------------- ### Run AquaCrop Simulation with Irrigation Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop simulation with a specific irrigation management strategy, weather data, soil type, and crop. This example uses a fixed irrigation amount based on soil moisture thresholds. ```python net_irr = IrrigationManagement(irrigation_method=1, SMT=[10]*4, MaxIrr=15, # NetIrrSMT= 60, ) # Brussels climate filepath=get_filepath('brussels_climate.txt') brussels_weather = prepare_weather(filepath) # Loamy sand soil loamy_sand = Soil(soil_type='LoamySand') # crops potato = Crop('PotatoLocalGDD', planting_date='04/25') # IWC fc = InitialWaterContent(value=['FC']) model = AquaCropModel(sim_start_time=f'{1976}/04/25', sim_end_time=f'{2005}/12/31', weather_df=brussels_weather, soil=loamy_sand, crop=potato, irrigation_management=net_irr, initial_water_content=fc, ) model.run_model(till_termination=True) run_comparison('Bru_Pot_Irr150RAW_noEToAdj', model) ``` -------------------------------- ### Calculate Datetime from Year, DAP, and Start Date Source: https://github.com/aquacropos/aquacrop/blob/master/tests/datetime_tests.ipynb Creates a DataFrame with year, day after planting (dap), and calculates the final datetime. It converts a combined year, month, and day string into a datetime object, determines the day of year, adds the dap, and then calculates the final datetime by adding the total days as a timedelta to the start date. ```python test_df=pd.DataFrame({'year':[1999,1999,1999,2000,2000,2000,2001,2001,2001,2002,2002,2002], # 'month':[1,1,2,1,1,2,1,1,2,1,1,2], 'dap':[1,6,9,1,6,9,1,6,9,1,6,9]}) start_month=3 start_day=25 # test_df['datetime']=test_df.apply(lambda x:datetime.datetime(x.year,start_month,start_day+1)+datetime.timedelta(x.dap),axis=1) # test_df['datetime']=pd.to_datetime() # print(test_df.datetime) test_df['combined']=test_df['year'].astype(str) + ' ' + str(start_month) + ' ' + str(start_day) test_df['start_date']=pd.to_datetime(test_df['combined'], format='%Y %m %d') test_df['start_doy'] = test_df["start_date"].dt.strftime('%j') test_df['doy_dap']=test_df['start_doy'].astype(int)+test_df['dap'].astype(int) test_df['time_added']=pd.to_timedelta(test_df['doy_dap'], 'd') test_df['datetime']=test_df['start_date'] + test_df['time_added'] print(test_df.datetime) ``` -------------------------------- ### Create Calendar-Based Irrigation Schedule Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_2.ipynb Generates a custom irrigation schedule using pandas to irrigate on the first Tuesday of each month. Requires simulation start and end dates. ```python import pandas as pd # import pandas library all_days = pd.date_range(sim_start,sim_end) # list of all dates in simulation period new_month=True dates=[] # iterate through all simulation days for date in all_days: #check if new month if date.is_month_start: new_month=True if new_month: # check if tuesday (dayofweek=1) if date.dayofweek==1: #save date dates.append(date) new_month=False ``` ```python depths = [25]*len(dates) # depth of irrigation applied schedule=pd.DataFrame([dates,depths]).T # create pandas DataFrame schedule.columns=['Date','Depth'] # name columns schedule ``` -------------------------------- ### Run AquaCrop with Wet/Dry Initial Water Content Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Initializes and runs the AquaCrop model with 'wet_dry' initial water content. This configuration is useful for simulating scenarios where the soil starts with a range of water content values. ```python irr_mngt = IrrigationManagement(irrigation_method=0) model = AquaCropModel(sim_start_time=f'{1979}/10/15', sim_end_time=f'{2002}/05/31', weather_df=tunis_weather, soil=sandy_loam, crop=wheat, irrigation_management=irr_mngt, initial_water_content=wet_dry, ) model.run_model(till_termination=True) python_output(model, 'Tun_WW_WetDry') run_comparison('Tun_WW_WetDry', model) ``` -------------------------------- ### Run AquaCrop with Initial Water Content (30% TAW) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs the AquaCrop model with initial water content set to 30% of Total Available Water (TAW) in specific soil layers. This is useful for scenarios where the soil is partially dry at the simulation start. The simulation uses Hyderabad climate data and local paddy soil. ```python # IWC taw30 = InitialWaterContent('Pct','Layer',[1,2],[30,30]) model = AquaCropModel(sim_start_time=f'{2000}/01/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=paddy_soil, crop=local_rice, irrigation_management=irr_mngt, field_management=bunds20, initial_water_content=taw30, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_Rice_30TAW') run_comparison('Hyd_Rice_30TAW', model) ``` -------------------------------- ### Optimize Irrigation Thresholds Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_3.ipynb Defines a function to optimize irrigation thresholds for profit maximization using scipy.optimize.fmin. It first finds a good starting point using `get_starting_point` and then runs the optimization, returning the optimized thresholds and evaluating the resulting yield. ```python def optimize(num_smts,max_irr_season,num_searches=100): """ optimize thresholds to be profit maximising """ # get starting optimization strategy x0=get_starting_point(num_smts,max_irr_season,num_searches) # run optimization res = fmin(evaluate, x0,disp=0,args=(max_irr_season,)) # reshape array smts= res.squeeze() # evaluate optimal strategy return smts ``` ```python smts=optimize(4,300) ``` ```python evaluate(smts,300,True) ``` -------------------------------- ### Run AquaCrop with Field Capacity Initial Water Content Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Initializes and runs the AquaCrop model with 'FC' (field capacity) as the initial water content. This is suitable for simulations starting with soil moisture at field capacity. ```python # Change initial water content field_capacity = InitialWaterContent(value=['FC']) model = AquaCropModel(sim_start_time=f'{1979}/10/15', sim_end_time=f'{2002}/05/31', weather_df=tunis_weather, soil=sandy_loam, crop=wheat, irrigation_management=irr_mngt, initial_water_content=field_capacity, ) model.run_model(till_termination=True) # python_output(model, 'Tun_WW_FC') run_comparison('Tun_WW_FC', model) ``` -------------------------------- ### Prepare Built-in Weather Data Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Access and prepare built-in weather data files provided with AquaCrop-OSPy using the `get_filepath` and `prepare_weather` functions. This is a convenient way to load example weather data for testing or demonstration purposes. ```python # locate built in weather file filepath=get_filepath('tunis_climate.txt') weather_data = prepare_weather(filepath) weather_data ``` -------------------------------- ### Extract Datetime from DataFrame Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Converts season and DAP (Days After Planting) information into a datetime format. Requires start year, month, and day for accurate conversion. Filters out entries with negative DAP. ```python def get_datetime(df, start_year, start_month, start_day): df['year']=df['season_counter'].astype(int)+int(start_year) df['combined']=df['year'].astype(str) + ' ' + str(start_month) + ' ' + str(start_day) df['start_date']=pd.to_datetime(df['combined'], format='%Y %m %d') df['dap-1']=df['dap']-1 df['time_added']=pd.to_timedelta(df['dap-1'], 'd') df['datetime']=df['start_date'] + df['time_added'] # df.drop(['combined','start_date','start_doy','doy_dap','time_added'],axis=1, inplace=True) df=df[(df['dap-1'] >= 0)] # dap starts at 0, anything below 0 is NA return(df) ``` -------------------------------- ### Save Aquacrop Model Outputs to CSV Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb A Python function to extract and save crop growth, water flux, and water storage data from an Aquacrop model to separate CSV files. It also saves the simulation start date information. ```python def python_output(model, name): # get model outputs model_growth = model.get_crop_growth() model_water = model.get_water_flux() model_storage = model.get_water_storage() # # get save path base_path = 'C:/Users/s10034cb/Dropbox (The University of Manchester)/Manchester Postdoc/aquacrop/outputs/' sp_path = base_path + name growth_path = sp_path + '_growth.csv' water_path = sp_path + '_water.csv' storage_path = sp_path + '_storage.csv' # # save outputs model_growth.to_csv(growth_path, index = False, encoding='utf-8') model_water.to_csv(water_path, index = False, encoding='utf-8') model_storage.to_csv(storage_path, index = False, encoding='utf-8') # # get start year and date start_year=int(model.sim_start_time.split('/')[0]) start_month,start_day=model.crop.planting_date.split('/') # # save starting date info start_info = pd.DataFrame(data = {'date_info' : [str(start_day) + '-' + str(start_month) + '-' + str(start_year)]}) # print(start_info) start_info.to_csv(sp_path + '_date.csv', index = False, encoding='utf-8') ``` -------------------------------- ### Initialize Crop, Soil, and Irrigation Parameters Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_4.ipynb Sets up the crop (Maize), soil (ClayLoam), initial water content (field capacity), and irrigation management policy (irrigates if soil moisture drops below 70% of total available water). ```python crop=Crop('Maize',planting_date='05/01', CalendarType=1,Emergence = 6,Senescence=107, MaxRooting=108,Maturity=132,HIstart=66, Flowering=13,YldForm=61,CDC=0.117,CGC=0.163) soil=Soil('ClayLoam') init_wc = InitialWaterContent() # default is field capacity irrmngt=IrrigationManagement(1,SMT=[70]*4) ``` -------------------------------- ### Prepare Weather Data and Initialize Model Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Prepares weather data for Tunis and initializes the AquaCropModel with local soil, wheat crop, and initial water content settings. The model is then run until termination. ```python wdf = prepare_weather(get_filepath('tunis_climate.txt')) soil=Soil(soil_type='ac_TunisLocal') crop = Crop('WheatGDD',planting_date= '10/15') iwc = InitialWaterContent('Num','Depth',[0.3,0.9],[0.3,0.15]) model = AquaCropModel('1979/10/15','2002/05/30',wdf,soil,crop,initial_water_content=iwc) %time model.run_model(till_termination=True) ``` -------------------------------- ### Initiate AquaCrop Library Source: https://github.com/aquacropos/aquacrop/blob/master/README.md Run this command in your terminal to initiate the AquaCrop library. This may be necessary if you encounter module import errors. ```bash python -m aquacrop.scripts.initiate_library ``` -------------------------------- ### Initialize and Run AquaCrop Model Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Initializes the AquaCropModel with simulation parameters, weather data, soil, crop, management, and initial water content. Then, it runs the simulation. ```python model = AquaCropModel(sim_start_time=f'{2000}/01/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=paddy_soil, crop=local_rice, field_management=bunds20, irrigation_management=irr_mngt, initial_water_content=taw75, ) model.run_model(till_termination=True) ``` -------------------------------- ### aquacrop.initialize Source: https://github.com/aquacropos/aquacrop/blob/master/docs/initialize.md The main initialization module for Aquacrop. ```APIDOC ## initialize ### Description This module contains functions for initializing the Aquacrop model. ### Functions - `calculate_HI_linear` - `calculate_HIGC` - `compute_crop_calendar` - `compute_variables` - `create_soil_profile` - `read_clocks_parameters` - `read_field_managment` - `read_groundwater_table` - `read_irrigation_management` - `read_model_initial_conditions` - `read_model_parameters` - `read_weather_inputs ``` -------------------------------- ### Define Simulation Timeframe Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_2.ipynb Sets the start and end dates for the AquaCrop simulation. These dates define the period over which the model will run. ```python sim_start = '1982/05/01' sim_end = '2018/10/30' ``` -------------------------------- ### Import AquaCrop Libraries Source: https://github.com/aquacropos/aquacrop/blob/master/tests/custom_crop_testing.ipynb Imports necessary modules from the AquaCrop library and other Python packages for data manipulation and plotting. Ensure these libraries are installed before running. ```python from aquacrop import AquaCropModel, Soil, Crop, InitialWaterContent, IrrigationManagement from aquacrop.utils import prepare_weather, get_filepath import pandas as pd import matplotlib.pyplot as plt ``` -------------------------------- ### Initialize and Run AquaCrop Model Source: https://github.com/aquacropos/aquacrop/blob/master/README.md Initializes the AquaCrop model with specified parameters including weather data, soil type, crop, and initial water content. Runs the simulation and prints the first few results. ```python from aquacrop import AquaCropModel, Soil, Crop, InitialWaterContent from aquacrop.utils import prepare_weather, get_filepath weather_file_path = get_filepath('tunis_climate.txt') model_os = AquaCropModel( sim_start_time=f"{1979}/10/01", sim_end_time=f"{1985}/05/30", weather_df=prepare_weather(weather_file_path), soil=Soil(soil_type='SandyLoam'), crop=Crop('Wheat', planting_date='10/01'), initial_water_content=InitialWaterContent(value=['FC']), ) model_os.run_model(till_termination=True) model_results = model_os.get_simulation_results().head() print(model_results) ``` -------------------------------- ### Run Paddy Rice Simulation (With Bunds) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop simulation for paddy rice in Hyderabad with bunds. Includes field management parameters for bunds. Requires weather data, soil parameters, crop details, and irrigation management settings. ```python # Hyderabad climate filepath=get_filepath('hyderabad_climate.txt') hyderabad_weather = prepare_weather(filepath) # Hyderabad soil paddy_soil = Soil(soil_type='Paddy') # crop local_rice = Crop('localpaddy', planting_date='08/01') # IWC fc = InitialWaterContent(value=['FC']) # irr management irr_mngt = IrrigationManagement(irrigation_method=0) # field management bunds20 = FieldMngt(bunds=True, z_bund=0.20) model = AquaCropModel(sim_start_time=f'{2000}/08/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=paddy_soil, crop=local_rice, field_management=bunds20, irrigation_management=irr_mngt, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_Rice_1Aug') run_comparison('Hyd_Rice_1Aug3', model) ``` -------------------------------- ### Evaluate Model with Default Parameters Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_3.ipynb Calls the `evaluate` function with default parameters to get the negative average yield for a specific irrigation strategy. This is often used to test the evaluation function itself. ```python evaluate([70]*4,300) ``` -------------------------------- ### Run AquaCrop Model Simulation Source: https://github.com/aquacropos/aquacrop/blob/master/docs/index.md This snippet demonstrates how to initialize and run the AquaCrop model with specified weather, soil, crop, and initial water content parameters. It then retrieves and prints the simulation results. ```python from aquacrop import AquaCropModel, Soil, Crop, InitialWaterContent from aquacrop.utils import prepare_weather, get_filepath weather_file_path = get_filepath('tunis_climate.txt') model_os = AquaCropModel( sim_start_time=f"{1979}/10/01", sim_end_time=f"{1985}/05/30", weather_df=prepare_weather(weather_file_path), soil=Soil(soil_type='SandyLoam'), crop=Crop('Wheat', planting_date='10/01'), initial_water_content=InitialWaterContent(value=['FC']), ) model_os.run_model(till_termination=True) model_results = model_os.get_simulation_results().head() print(model_results) ``` -------------------------------- ### Run AquaCrop Simulation for Paddy Rice (No Bunds) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop simulation for local paddy rice without bunds. Requires pre-defined weather data, soil parameters, irrigation management, and initial water content. The simulation is run for a specified period and compared using a helper function. ```python # NO BUNDS TEST # crop local_rice = Crop('localpaddy', planting_date='07/15') model = AquaCropModel(sim_start_time=f'{2000}/07/15', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=paddy_soil, crop=local_rice, irrigation_management=irr_mngt, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_Rice_15Jul_noBunds') run_comparison('Hyd_Rice_15Jul_noBunds', model) ``` -------------------------------- ### Run AquaCrop Model with 30% TAW Initial Conditions Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Initializes and runs the AquaCrop model with a specific initial water content (30% of TAW). The simulation results are then compared. ```python model = AquaCropModel('1979/01/01','2002/05/31',wdf,sandy_loam, crop,initial_water_content=iwc30taw) model.run_model(till_termination=True) _ = run_comparison(model,'tunis_test_3_30taw') ``` -------------------------------- ### Initialize AquaCropModel with Mulches Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Set up an AquaCropModel instance specifying field management with mulches covering 100% of the soil surface. This configuration impacts soil evaporation. ```python mulches_model = AquaCropModel(sim_start_time=f'{1979}/10/01', sim_end_time=f'{1985}/05/30', weather_df=weather_data, soil=sandy_loam, crop=wheat, initial_water_content=InitWC, field_management=FieldMngt(mulches=True, mulch_pct=100, f_mulch=0.5)) ``` -------------------------------- ### Adjust Compartment Depths Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Modify the default compartment depths of a soil profile by providing a list of thicknesses to the 'dz' argument during Soil object initialization. This example sets the top 6 compartments to 0.1m and the bottom 6 to 0.2m. ```python sandy_loam = Soil('SandyLoam',dz=[0.1]*6+[0.2]*6) ``` -------------------------------- ### Configure and Run AquaCrop Model for Tunis Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up the AquaCrop model with Tunis weather data, local soil type, wheat crop, initial water content, and irrigation management. The model is then executed. ```python # Tunis climate filepath=get_filepath('tunis_climate.txt') tunis_weather = prepare_weather(filepath) # Local Tunis soil tunis_soil = Soil(soil_type='ac_TunisLocal') # crops wheat = Crop('WheatGDD', planting_date='10/15') # IWC wet_dry = InitialWaterContent(wc_type='Num', method='Depth', depth_layer=[0.3,0.9], value=[0.3,0.15]) # irr management irr_mngt = IrrigationManagement(irrigation_method=0) model = AquaCropModel(sim_start_time=f'{1979}/10/15', sim_end_time=f'{2002}/03/31', weather_df=tunis_weather, soil=tunis_soil, crop=wheat, irrigation_management=irr_mngt, initial_water_content=wet_dry, ) model.run_model(till_termination=True) ``` -------------------------------- ### Run Paddy Rice Simulation (No Bunds) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop simulation for paddy rice in Hyderabad without bunds. Requires weather data, soil parameters, crop details, and irrigation management settings. ```python # NO BUNDS TEST # Hyderabad climate filepath=get_filepath('hyderabad_climate.txt') hyderabad_weather = prepare_weather(filepath) # Hyderabad soil paddy_soil = Soil(soil_type='Paddy') # crop local_rice = Crop('localpaddy', planting_date='08/01') # IWC fc = InitialWaterContent(value=['FC']) # irr management irr_mngt = IrrigationManagement(irrigation_method=0) model = AquaCropModel(sim_start_time=f'{2000}/08/01', sim_end_time=f'{2010}/12/31', weather_df=hyderabad_weather, soil=paddy_soil, crop=local_rice, irrigation_management=irr_mngt, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Hyd_Rice_1Aug_noBunds') run_comparison('Hyd_Rice_1Aug_noBunds', model) ``` -------------------------------- ### Run AquaCrop Model for Potato in Brussels Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Sets up and runs the AquaCrop model for potato cultivation in Brussels using loam soil. Compares the simulated results. ```python potato = Crop('PotatoLocal',planting_date= '04/25') loam = Soil('Loam') model = AquaCropModel('1976/01/01','2005/12/31',wdf,loam,potato,InitialWaterContent()) model.run_model(till_termination=True) _ = run_comparison(model,'potato') ``` -------------------------------- ### Run AquaCrop Model for Paddy Rice in Hyderabad Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Sets up and runs the AquaCrop model for paddy rice in Hyderabad. Includes initial water content and field management configurations. Compares model output with external data. ```python rice = Crop('localpaddy',planting_date= '08/01',) paddy = Soil('Paddy') iwc_paddy = InitialWaterContent(depth_layer=[1,2],value=['FC','FC']) fm = FieldMngt(bunds=True,z_bund=0.2) model = AquaCropModel('2000/01/01','2010/12/31',wdf,paddy, rice,initial_water_content=iwc_paddy,field_management=fm, fallow_field_management=fm) model.run_model(till_termination=True) _ = run_comparison(model,'paddyrice_hyderabad') ``` -------------------------------- ### Configure and Run AquaCrop Model for Local Wheat Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up the AquaCrop model with a local wheat variety, weather data, soil type, and irrigation management. It then runs the simulation and outputs the results for comparison. ```python # Local wheat variety local_wheat=Crop('WheatLongGDD', planting_date= '10/15') model = AquaCropModel(sim_start_time=f'{1979}/10/15', sim_end_time=f'{2002}/05/31', weather_df=tunis_weather, soil=sandy_loam, crop=local_wheat, irrigation_management=irr_mngt, initial_water_content=wet_dry, ) model.run_model(till_termination=True) python_output(model, 'Tun_WW_LongVar') run_comparison('Tun_WW_LongVar2', model) ``` -------------------------------- ### Run Potato Simulation in Brussels Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an Aquacrop model for potato cultivation in Brussels, using local soil and climate data. It then processes and compares the simulation outputs. ```python # Brussels climate filepath=get_filepath('brussels_climate.txt') brussels_weather = prepare_weather(filepath) # Local Brussels soil loam_soil = Soil(soil_type='Loam') # crops potato = Crop('PotatoLocalGDD', planting_date='04/25') # IWC fc = InitialWaterContent(value=['FC']) # irr management irr_mngt = IrrigationManagement(irrigation_method=0) model = AquaCropModel(sim_start_time=f'{1976}/04/25', # 1976 sim_end_time=f'{2005}/12/31', # 2005 weather_df=brussels_weather, soil=loam_soil, crop=potato, irrigation_management=irr_mngt, initial_water_content=fc, ) model.run_model(till_termination=True) python_output(model, 'Bru_Pot') run_comparison('Bru_Pot3', model) #daily_outputs = run_comparison_v7('Bru_Pot', model) ``` -------------------------------- ### Create and Run AquaCropModel with Clay Soil Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Initializes and runs a second AquaCrop model using a 'Clay' soil type, allowing for comparison with previous results. ```python # combine into aquacrop model and specify start and end simulation date model_clay = AquaCropModel(sim_start_time=f'{1979}/10/01', sim_end_time=f'{1985}/05/30', weather_df=weather_data, soil=Soil('Clay'), crop=wheat, initial_water_content=InitWC) model_clay.run_model(till_termination=True) ``` -------------------------------- ### Prepare Weather Data Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_2.ipynb Loads and prepares daily weather data from a specified file. Ensure the weather data file is accessible. ```python path = get_filepath('champion_climate.txt') wdf = prepare_weather(path) wdf ``` -------------------------------- ### Run AquaCrop Model with Net Irrigation Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Initializes and runs the AquaCrop model with defined irrigation management and crop parameters. The simulation output is then compared. ```python model = AquaCropModel('1979/08/15','2001/07/30',wdf,sandy_loam, wheat_dec,initial_water_content=wp,irrigation_management=net_irr) model.run_model(till_termination=True) res = run_comparison(model,'tunis_test_6') ``` -------------------------------- ### Specify Water Content by Percentage of Total Available Water (% TAW) Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Sets the initial water content as a percentage of the Total Available Water (% TAW) for the specified soil layers. ```python # Specify WC by percentage of Total Available Water (% TAW) tawWC = InitialWaterContent(wc_type = 'Pct', method = 'Layer', depth_layer= [1], value = [80]) ``` -------------------------------- ### Specify Water Content by Wilting Point (WP) Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Sets the initial water content to the Wilting Point (WP) for the specified soil layers. ```python # Specify WC by Wilting Point (WP) wpWC = InitialWaterContent(wc_type = 'Prop', method = 'Layer', depth_layer= [1], value = ['WP']) ``` -------------------------------- ### Initialize Model with Sandy Loam Soil and Run Comparison Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/05_comparison.ipynb Initializes the AquaCropModel with sandy loam soil and the same crop and weather data. The model is run, and the `run_comparison` function is called to compare results with MATLAB and Windows versions. ```python sandy_loam = Soil('SandyLoam') model = AquaCropModel('1979/01/01','2002/05/30',wdf,sandy_loam,crop,initial_water_content=iwc) model.run_model(till_termination=True) res = run_comparison(model,'tunis_test_1_SandyLoam') ``` -------------------------------- ### Run AquaCrop with 75% Initial Water Content Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets initial water content to 75% of total available water and runs the AquaCrop model. Use this to compare simulation results with different initial soil moisture levels. ```python # Change initial water content iwc75taw = InitialWaterContent('Pct','Layer',[1],[75]) model = AquaCropModel(sim_start_time=f'{1979}/10/15', sim_end_time=f'{2002}/05/31', weather_df=tunis_weather, soil=sandy_loam, crop=wheat, irrigation_management=irr_mngt, initial_water_content=iwc75taw, ) model.run_model(till_termination=True) # python_output(model, 'Tun_WW_75TAW') run_comparison('Tun_WW_75TAW', model) ``` -------------------------------- ### Run Unit Tests (with Numba) Source: https://github.com/aquacropos/aquacrop/blob/master/CONTRIBUTING.md Execute unit tests for the library. If you have made changes to Numba-compiled code, you may need to delete compiled files before re-running tests. ```bash python -m unittest ``` -------------------------------- ### Run Historical Climate Simulation Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop model simulation using historical climate data for Brussels. It configures the weather, soil, crop, irrigation, and initial water content, then runs the model and compares the output. ```python # Hist climate filepath=get_filepath('brussels_climate.txt') brussels_weather = prepare_weather(filepath) # Local Brussels soil loam_soil = Soil(soil_type='Loam') # crops potato = Crop('PotatoLocalGDD', planting_date='04/25') # IWC fc = InitialWaterContent(value=['FC']) # irr management irr_mngt = IrrigationManagement(irrigation_method=0) model = AquaCropModel(sim_start_time=f'{1976}/03/01', sim_end_time=f'{2005}/12/31', weather_df=brussels_weather, soil=loam_soil, crop=potato, irrigation_management=irr_mngt, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Bru_Pot_Historical') run_comparison('Bru_Pot_Historical3', model) ``` -------------------------------- ### Read Windows Daily Water Outputs (WABAL) Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Reads the WABAL.OUT file for daily water outputs. Assumes a specific file path and uses pandas for data manipulation. Includes options for different AquaCrop versions. ```python win_daily_water = pd.read_table('C:/Users/s10034cb/Dropbox (The University of Manchester)/Manchester Postdoc/AquaCrop-windows/AquaCropV7.1/OUTP/'+win_filename+'WABAL.OUT', skiprows=4, skipfooter=27, delim_whitespace=True,encoding="latin1") ``` -------------------------------- ### Run AquaCrop Model with Net Irrigation Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs the AquaCrop model with specific irrigation management parameters. Requires weather data, soil, crop, and initial water content. The conversion from RAW to TAW is handled internally based on crop attributes. ```python # Exercise states 35% of RAW, that's what I have input into the irrigation file in AQ-Win # AQ-Py only deals with TAW, not RAW, so a conversion must be done. # Conversion is based on the p_up2 attribute of crop, reflects proportion of TAW that is RAW. # In this case (PotatoLocalGDD) has p_up2 of 0.6 so 35 * 0.6 = 21 net_irr = IrrigationManagement(irrigation_method=4,NetIrrSMT=79, MaxIrr=40) model = AquaCropModel(sim_start_time=f'{1976}/03/01', sim_end_time=f'{2005}/12/31', weather_df=brussels_weather, soil=loam_soil, crop=potato, irrigation_management=net_irr, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Bru_Pot_NetIrr2') run_comparison('Bru_Pot_NetIrr2', model) ``` -------------------------------- ### Define Multi-Layered Initial Water Content (FC and WP) Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_1.ipynb Defines a multi-layered initial water content profile, specifying different water content types for each soil layer. The first value corresponds to the first soil layer. ```python # If you have more than one soil layer, you can specify the initial water content of each layer. # e.g. for soil profile with two layers, first filled to Field Capacity, second to Wilting Point: multiWC = InitialWaterContent(wc_type = 'Prop', method = 'Layer', depth_layer= [1,2], value = ['FC', 'WP']) ``` -------------------------------- ### Run Future Climate Simulation Source: https://github.com/aquacropos/aquacrop/blob/master/tests/v7_Comparison_exercises.ipynb Sets up and runs an AquaCrop model simulation using future climate data for Brussels. It configures the weather, soil, crop, irrigation, and initial water content, then runs the model and compares the output. ```python # Future climate filepath=get_filepath('C:/Users/s10034cb/Dropbox (The University of Manchester)/Manchester Postdoc/aquacrop/aquacrop/data/brussels_future.txt') brussels_future = prepare_weather(filepath) # crops potato = Crop('PotatoLocalGDD', planting_date='04/25') model = AquaCropModel(sim_start_time=f'{2041}/04/25', sim_end_time=f'{2070}/12/31', weather_df=brussels_future, soil=loam_soil, crop=potato, irrigation_management=irr_mngt, initial_water_content=fc, ) model.run_model(till_termination=True) # python_output(model, 'Bru_Pot_Future') run_comparison('Bru_Pot_Future3', model) ``` -------------------------------- ### Iterate Through Irrigation Limits and Optimize Source: https://github.com/aquacropos/aquacrop/blob/master/docs/notebooks/AquaCrop_OSPy_Notebook_3.ipynb Iterates through a range of maximum seasonal irrigation limits (0-450mm) to find the yield-maximizing irrigation schedule for each limit. It uses `tqdm` for a progress bar and saves the optimal thresholds, yield, and total irrigation for each iteration. ```python from tqdm.autonotebook import tqdm # progress bar opt_smts=[] yld_list=[] tirr_list=[] for max_irr in tqdm(range(0,500,50)): # find optimal thresholds and save to list smts=optimize(4,max_irr) opt_smts.append(smts) # save the optimal yield and total irrigation yld,tirr,_=evaluate(smts,max_irr,True) yld_list.append(yld) tirr_list.append(tirr) ```