Package: apsimNGpy
Our cutting-edge open-source framework, apsimNGpy, empowers advanced agroecosystem modeling through the utilization
of object-oriented principles. It features fast batch file simulation, model prediction, evaluation,
apsimx file editing, seamless weather data retrieval, and efficient soil profile developmentRequirementsDotnet, install fromhttps://learn.microsoft.com/en-us/dotnet/core/install/Python3APSIM: Add the directory containing the models executable to the system’s PATH or python path (to locate the required .dll files). This can be achieved in either of the following ways:Utilize the APSIM installer provided for this purpose.Build APSIM from its source code. This is comming soonMinimum; 8GM RAM, CPU Core i7InstallationAll versions are currently in development, phase and they can be installed as follows:Method 1. install from PyPIpipinstallapsimNGpyMethod 1. clone the current development repositrygitclonehttps://github.com/MAGALA-RICHARD/apsimNGpy.git@devcdapsimNGpypipinstall.Method 2. Use pip straight away and install from githubpipinstallgit+https://github.com/MAGALA-RICHARD/apsimNGpy.git@devDebugging import error due to improper SYSTEM APSIM path configurationIf you have apsim installed and the program refuses to load run the following code at the top of your python script
before importing any apsimNGpy class, especially class from ApsimNGpy.core modules The classes are  CamelCased.# search for the program binary installation path and add to os.environ as followsimportosos.environ['APSIM']=r'path/toyourapsimbinaryfolder/bin# try importing SoilModel classfromapsimNGpy.core.apsimimportApsimModel# alternatively, you can add the path to the system environmental variablesThe above code is also applicable for running different versions of APSIM models. Please note that if your APSIM installation hasn’t been added to the system path, this script line should always be placed at the beginning of your simulation script.Required Dependencies:numpypandaspythonnetxmltodicttqdmrequestsPlease note that apsimNGpy is tested on Python 3. We are not aware of its performance in Python 2 because it utilizes some of the new libraries like pathlib and f-strings.UsageimportapsimNGpyfromapsimNGpy.core.base_dataimportLoadExampleFilesfromapsimNGpy.core.apsimimportApsimModelasSoilModelfrompathlibimportPathimportosfromapsimNGpy.validation.visualimportplot_datacwd=Path.cwd().home()# sending this to your home folderwd=cwd.joinpath("apsimNGpy_demo")ifnotwd.exists():os.mkdir(wd)# change directoryos.chdir(wd)# Create the datadata=LoadExampleFiles(wd)# Get maize modelmaize=data.get_maize# Initialize the simulation methodsapsim=SoilModel(maize,copy=True)# Run the fileapsim.run()# use run to print time taken to excute or run the model# print the resultsprint(apsim.results)# prints all data frames in the storage domain subset usign report names# check the manager modules in the apsim simulation file# first get the simualtion namessim_name=apsim.extract_simulation_nameapsim.examine_management_info(simulations=sim_name)# show current simulation in apsim GUI# plot the datares=apsim.results['MaizeR']plot_data(res.Year,res.Yield,xlabel='Years',ylabel=" Maize Yield (kg/ha)")A graph should be able to appear like the ones below. Note that plot_data function just wraps matplotlib plot function
for quick visualisationCongratulations you have successfuly used apsimNGpy packageChange APSIM simulation datesimportapsimNGpyfromapsimNGpy.core.base_dataimportLoadExampleFilesfromapsimNGpy.core.apsimimportApsimModelasSoilModelfrompathlibimportPathimportosfromapsimNGpy.validation.visualimportplot_datacwd=Path.cwd().home()# sending this to your home folderwd=cwd.joinpath("apsimNGpy_demo")ifnotwd.exists():os.mkdir(wd)# change directoryos.chdir(wd)# Create the datadata=LoadExampleFiles(wd)# Get maize modelmaize=data.get_maize# Initialize the simulation methodsapsim=SoilModel(maize,copy=True)apsim.change_simulation_dates(start_date='01/01/1998',end_date='12/31/2010')Change  APSIM model management decisions# First, examine the manager scripts in the simulation nodeapsim.examine_management_info()# now create dictionary holding the parameters. the key to this is that the name of the script manage must bepassedinthedictionary.# in this node we have a script named the Simple Rotation,we want to change the rotation to maybe Maize, Wheat orsomethingelserotation={'Name':"Simple Rotation","Crops":'Maize, Wheat, Soybean'# the crops must be seperated my commasapsim.update_multiple_management_decisions([rotation],simulations=apsim.extract_simulation_name,reload=True)# now you cans see we passed rotation as a list. That means you can add other scripts as much as you all  to bechangedatthesametimePopulating the APSIM model with new weather datafromapsimNGpy.core.weatherimportdaymet_bylocation_nocsvlonlat=-93.08,42.014start_year,end_year=2000,2002wf=daymet_bylocation_nocsv(lonlat,startyear,endyear,filename="mymet.met")# you may need to first see what file currently exists in the modelmis=apsim.show_met_file_in_simulation()print(mis)# changeapsim.replace_met_file(wf)# check again if you want tomis=apsim.show_met_file_in_simulation()print(mis)Evaluate Predicted VariablesThe apsimNGpy Python package provides a convenient way to validate model simulations against measured data. Below
is a step-by-step guide on how to use the validation.evaluator module from apsimNGpy.# Start by importing the required librariesfromapsimNGpy.validation.evaluatorimportvalidateimportpandasaspd# Load the data if external. Replace with your own datadf=pd.read_csv('evaluation.csv')apsim_results=apsim.results# Assuming 'apsim' is a predefined object from aopsimNGpy.core.core.APSIMN class and contains your simualted results# Preparing Data for Validation# Extract the relevant columns from your DataFrame for comparison. In this example, we use# 'Measured' for observed values and compare them with different model outputs:measured=df['Measured']predicted=apsim_results['MaizeR'].Yield# Now we need to pass both the measured and the observed in the validate classval=validate(measured,predicted)# Both variables should be the same length, and here we are assuming that they are sorted in the corresponding order# There are two options:# 1. Evaluate allmetrics=val.evaluate_all(verbose=True)# Setting verbose=True prints all the results on the go; otherwise, a dictionary is returned with the value for each metric# 2. Select or pass your desired metricRMSE=val.evaluate("RMSE")print(RMSE)# If you want to see the available metrics, use the code belowavailable_metrics=metrics.keys()print(available_metrics)# Then select your choice from the list