apsimNGpy: The Next Generation Agroecosytem Simulation Library
====================================================================
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 development
Requirements
***********************************************************************************
1. Dotnet, install from https://learn.microsoft.com/en-us/dotnet/core/install/
2. Python3
3. APSIM: 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:
4. Utilize the APSIM installer provided for this purpose.
5. Build APSIM from its source code. This is comming soon
6. Minimum; 8GM RAM, CPU Core i7
.. _Installation:
Installation
********************************************************************************
All versions are currently in development, phase and they can be installed as follows:
- Method 1. install from PyPI
.. code:: bash
pip install apsimNGpy
- Method 1. clone the current development repository
.. code:: bash
git clone https://github.com/MAGALA-RICHARD/apsimNGpy.git
cd apsimNGpy
pip install .
- Method 2. Use pip straight away and install from github
.. code:: bash
pip install git+https://github.com/MAGALA-RICHARD/apsimNGpy.git@dev
GETTING STARTED
*****************************
Before using apsimNGpy, it is necessary to install APSIM. Please follow the instructions provided at the following link to complete the installation: https://www.apsim.info/download-apsim/downloads/
for MAcOS or Linux users see: https://apsimnextgeneration.netlify.app/install/
model documentation and tutorial are also available via; https://docs.apsim.info/
we expect that by accepting to use apsimNGpy, you have a basic understanding of APSIM process-based model, therefore, our focus is to make sure you are able to use apsimNGpy
In addition, make sure that the APSIM installation binaries folder is added to the system path.
if you run the following code and returns None you need to do something as explained below.
- 1. Use command line interface
.. code-block:: bash
apsim_bin_path -s
- 2. Use apsimNGpy config module
.. code-block:: python
from apsimNGpy.core import config
print(config.get_apsim_bin_path())
You can also try to check if automatic search will be successful as follows
.. code-block:: bash
apsim_bin_path --auto_search
The short cut
.. code-block:: bash
apsim_bin_path -a
Locating the APSIM Binaries
***************************************************************
By default the APSIM binaries are located automatically. The process for determining the APSIM binary path is as follows:
In apsimNGpy, priority is first given to the user-supplied binary path.
If no path is supplied, the module searches through the Python global environment
using the os module. If that fails, it searches through other folders.
If all approaches are exhausted and no valid path is found, a ValueError will be raised.
Changing/setting the APSIM installation binaries path
*********************************************************************************
If the automatic search fails, please follow one of the steps below to resolve the issue:
1. Manually configure the APSIM binary path. To do this:
*************************************************************************************
In your home folder you could look for folder named apsimNGpy_meta_info './APSIMNGpy_meta_data'
1. Locate the folder named `APSIMNGpy_meta_info` in your home directory (e.g., `./APSIMNGpy_meta_data`).
2. Open the file `apsimNGpy_config.ini` within this folder.
3. Modify the `apsim_location` entry to reflect your desired APSIM binary path.
2. change based os.environ module
************************************
Alternatively, you can use the code at the top of your script as follows
.. code-block:: python
# Search for the APSIM binary installation path and add it to os.environ as follows:
import os
os.environ['APSIM'] = r'path/to/your/apsim/binary/folder/bin'
- Note:
This approach may not work consistently in all scenarios, but you can try it.
The above script line should always be placed at the beginning of your simulation script.
However, why follow this approach when you can achieve the same result more efficiently? See the approach below:
3. Use the apsimNGpy config module:
*****************************************************************
.. code-block:: python
from apsimNGpy.config import set_apsim_bin_path
# Set the path to the APSIM binaries:
set_apsim_bin_path(path=r'path/to/your/apsim/binary/folder/bin')
4. Use command line interface
*********************************************************************
After installing apsimNGpy, navigate to your terminal and run the following
.. code-block:: bash
apsim_bin_path -u 'path/to/your/apsim/binary/folder/bin'
Or
.. code-block:: bash
apsim_bin_path --update 'path/to/your/apsim/binary/folder/bin'
# Now that the path is set, you can import any module attached to pythonnet.
*********************************************************************************************
.. code-block:: python
# For example, try importing the ApsimModel class:
from apsimNGpy.core.apsim import ApsimModel
.. _Usage:
The above code is also applicable for running different versions of APSIM models.
The `set_apsim_bin_path` function can be called once and retained unless you uninstall `apsimNGpy`
or the APSIM application itself. This implies that you can switch between apsim versions easily if you have more than one versions installed on your computer
Examples
********
This example demonstrates how to use `apsimNGpy` to load a default simulation, run it, retrieve results, and visualize the output.
.. code-block:: python
# Import necessary modules
import apsimNGpy
from apsimNGpy.core.base_data import load_default_simulations
from apsimNGpy.core.apsim import ApsimModel as SoilModel
from pathlib import Path
import os
from apsimNGpy.validation.visual import plot_data
The above code imports the necessary modules for running APSIM simulations. This includes `apsimNGpy` modules for loading default simulations and managing results, as well as standard Python libraries for file handling and visualization.
.. code-block:: python
# Load the default simulation
soybean_model = load_default_simulations(crop='soybean') # Case-insensitive crop specification
The `load_default_simulations` function loads a default APSIM simulation for the specified crop. In this example, the crop is set to soybean, but you can specify other crops as needed.
.. code:: python
# Load the simulation path without initializing the object
soybean_path_model = load_default_simulations(crop='soybean', simulation_object=False)
If you prefer not to initialize the simulation object immediately, you can load only the simulation path by setting `simulation_object=False`.
.. code-block:: python
# Initialize the APSIM model with the simulation file path
apsim = SoilModel(soybean_path_model)
This code initializes the APSIM model using the previously loaded simulation file path.
.. code-block:: python
# Run the simulation
apsim.run(report_name='Report')
The `run` method executes the simulation. The `report_name` parameter specifies which data table from the simulation will be used for results.
.. note::
report_name accepts a list of simulation data tables and hence can return a list of pandas data frame for each data table and if get_dict = True, a dictionary is returned
with each data table name as the key and data frame as the values
.. code-block:: python
# Retrieve and save the results
df = apsim.results
df.to_csv('apsim_df_res.csv') # Save the results to a CSV file
print(apsim.results) # Print all DataFrames in the storage domain
After the simulation runs, results are stored in the `apsim.results` attribute as pandas DataFrames. Please see note above. These results can be saved to a CSV file or printed to the console.
The code below retrieves the names of simulations from the APSIM model and examines the management modules used in the specified simulations.
.. code-block:: python
# Examine management modules in the simulation
sim_name = apsim.simulation_names # Retrieve simulation names
apsim.examine_management_info(simulations=sim_name)
You can preview the current simulation in the APSIM graphical user interface (GUI) using the `preview_simulation` method.
.. code-block:: python
# Preview the current simulation in the APSIM GUI
apsim.preview_simulation()
.. note::
apsimNGpy clones a every simulation file before passing it it dotnet runner, however, when you open it in GUI, take note of the version it will be difficult to re-open
it in the lower versions after opening it in the higher versions of apsim
Visualise the results. please note that python provide very many plotting libraries below is just a basic description of your results
.. code-block:: python
# Visualize the simulation results
res = apsim.results['MaizeR'] # Replace with the appropriate report name
plot_data(df['Clock.Today'], df.Yield, xlabel='Date', ylabel='Soybean Yield (kg/ha)')
Finally, the `plot_data` function is used to visualize the simulation results. Replace 'df['Clock.Today']' and `df.Yield` with the appropriate report name and column from your simulation results.
A graph similar to the example below should appear
Congratulations you have successfully used apsimNGpy package
*********************************************************************************
.. image:: ./apsimNGpy/examples/Figure_1.png
:alt: /examples/Figure_1.png
Change APSIM simulation dates
*********************************************************************************
.. code-block:: python
import apsimNGpy
from apsimNGpy.core.base_data import load_default_simulations
from apsimNGpy.core.apsim import ApsimModel as SoilModel
from pathlib import Path
import os
from apsimNGpy.validation.visual import plot_data
cwd = Path.cwd().home() # sending this to your home folder
wd = cwd.joinpath("apsimNGpy_demo")
if not wd.exists():
os.mkdir(wd)
# change directory
os.chdir(wd)
# Get maize model
maize_model = load_default_simulations(crop = 'maize')
maize_model.change_simulation_dates(start_date='01/01/1998', end_date='12/31/2010')
Change APSIM model management decisions
*********************************************************************************
.. code-block:: python
# First, examine the manager scripts in the simulation node
apsim.examine_management_info()
# now create dictionary holding the parameters. the key to this is that the name of the script manage must be
passed in the dictionary.
# in this node we if have a script named the Simple Rotation,we want to change the rotation to maybe Maize, Wheat or
something else
rotation = {'Name': "Simple Rotation", "Crops": 'Maize, Wheat, Soybean'}, # the crops must be seperated my commas
apsim.update_mgt(management = rotation)
# now you cans see we passed rotation as a tuple. That means you can add other scripts as your needs suggest. They will all be changed at the
#same time
Populating the APSIM model with new weather data
*********************************************************************************
.. code-block:: python
from apsimNGpy.core.weather import daymet_bylocation_nocsv
lonlat = -93.08, 42.014
start_year, end_year = 2000, 2002
wf = daymet_bylocation_nocsv(lonlat, startyear, endyear, filename="mymet.met")
# you may need to first see what file currently exists in the model
mis = apsim.show_met_file_in_simulation()
print(mis)
# change
maize_model.replace_met_file(weather_file=wf)
# check again if you want to
mis = maize_model.show_met_file_in_simulation()
print(mis)
Evaluate Predicted Variables
*********************************************************************************
The 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.
.. code-block:: python
# Start by importing the required libraries
from apsimNGpy.validation.evaluator import validate
import pandas as pd
# Load the data if external. Replace with your own data
df = 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 class
val = 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 all
metrics = 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 metric
RMSE = val.evaluate("RMSE")
print(RMSE)
# If you want to see the available metrics, use the code below
available_metrics = metrics.keys()
print(available_metrics)
# Then select your choice from the list
How to Contribute to apsimNGpy
*********************************************************************************
We welcome contributions from the community, whether they are bug fixes, enhancements, documentation updates, or new features. Here's how you can contribute to ``apsimNGpy``:
Reporting Issues
----------------
.. note::
apsimNGpy is developed and maintained by a dedicated team of volunteers. We kindly ask that you adhere to our community standards when engaging with the project. Please maintain a respectful tone when reporting issues or interacting with community members.
If you find a bug or have a suggestion for improving ``apsimNGpy``, please first check the `Issue Tracker <https://github.com/MAGALA-RICHARD/apsimNGpy/issues>`_ to see if it has already been reported. If it hasn't, feel free to submit a new issue. Please provide as much detail as possible, including steps to reproduce the issue, the expected outcome, and the actual outcome.
Contributing Code
-----------------
We accept code contributions via Pull Requests (PRs). Here are the steps to contribute:
Fork the Repository
^^^^^^^^^^^^^^^^^^^
Start by forking the ``apsimNGpy`` repository on GitHub. This creates a copy of the repo under your GitHub account.
Clone Your Fork
^^^^^^^^^^^^^^^
Clone your fork to your local machine:
.. code-block:: bash
git clone https://github.com/MAGALA-RICHARD/apsimNGpy.git
cd apsimNGpy
Create a New Branch
Create a new branch for your changes:
.. code-block:: bash
git checkout -b your-branch-name
Make Your Changes
Make the necessary changes or additions to the codebase. Please try to adhere to the coding style already in place.
Test Your Changes
Run any existing tests, and add new ones if necessary, to ensure your changes do not break existing functionality.
Commit Your Changes
Commit your changes with a clear commit message that explains what you've done:
.. code-block:: bash
git commit -m "A brief explanation of your changes"
Push to GitHub
Push your changes to your fork on GitHub:
.. code-block:: bash
git push origin your-branch-name
Submit a Pull Request
Go to the ``apsimNGpy`` repository on GitHub, and you'll see a prompt to submit a pull request based on your branch. Click on "Compare & pull request" and describe the changes you've made. Finally, submit the pull request.
Updating Documentation
----------------------
Improvements or updates to documentation are greatly appreciated. You can submit changes to documentation with the same process used for code contributions.
Join the Discussion
-------------------
Feel free to join in discussions on issues or pull requests. Your feedback and insights are valuable to the community!
Version 0.0.27.8 new features
********************************************************************************
Dynamic handling of simulations and their properties
replacements made easier
object oriented factorial experiment set ups and simulations
Acknowledgements
*********************************************************************************
This project, *ApsimNGpy*, greatly appreciates the support and contributions from various organizations and initiatives that have made this research possible. We extend our gratitude to Iowa State University's C-CHANGE Presidential Interdisciplinary Research Initiative, which has played a pivotal role in the development of this project. Additionally, our work has been significantly supported by a generous grant from the USDA-NIFA Sustainable Agricultural Systems program (Grant ID: 2020-68012-31824), underscoring the importance of sustainable agricultural practices and innovations.
We would also like to express our sincere thanks to the APSIM Initiative. Their commitment to quality assurance and the structured innovation program for APSIM's modelling software has been invaluable. APSIM's software, which is available for free for research and development use, represents a cornerstone for agricultural modeling and simulation. For further details on APSIM and its capabilities, please visit `www.apsim.info <http://www.apsim.info>`_.
Our project stands on the shoulders of these partnerships and support systems, and we are deeply thankful for their contribution to advancing agricultural research and development. Please not that that this library is designed as a bridge to APSIM software, and we hope that by using this library, you have the appropriate APSIM license to do so whether free or commercial.
Lastly but not least, ApsimNGpy is not created in isolation but draws inspiration from apsimx, an R package (https://cran.r-project.org/web/packages/apsimx/vignettes/apsimx.html). We acknowledge and appreciate the writers and contributors of apsimx for their foundational work. ApsimNGpy is designed to complement apsimx by offering similar functionalities and capabilities in the Python ecosystem.
# Changelog
******************************************************************************************************
The earlier versions of apsimNGpy were too experimental with a lot of bugs. Therefore tracking started with version 0..29
## [0.29.0] - 2025-01-15
### Added
************************************************************************************
- New logging feature for better debug capability.
- command line interface to run models faster using the command and crop module
- command line interface to change the apsim binary path using the apsim_bin_path module
- more detailed installation documentation
## Fixed
**************************************************************************************
- config module to run on all operating systems
- import of load_default simulations
## [0.3.0] - 2025-01-20
## Fixed
**************************************************************************************
- fixed package to run all latest versions
- handle multiple reports tables in run method, return a concat of the different data frame
## Added
*****************************************************************************
- APSIMNG.run now return pandas data frame consistently
- files named by default are tagged by the corresponding APSIM installed version
Raw data
{
"_id": null,
"home_page": "https://github.com/MAGALA-RICHARD/apsimNGpy.git",
"name": "apsimNGpy",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "python, APSIM Next Generation, pythonnet, crop modeling",
"author": "Richard Magala",
"author_email": "magalarich20@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/a5/96/174076f5090ae2e5c2ca4a35f68df93f340c5cd7ac6caf15fecc1c5db730/apsimngpy-0.31.tar.gz",
"platform": null,
"description": "apsimNGpy: The Next Generation Agroecosytem Simulation Library\r\n\r\n====================================================================\r\n\r\nOur cutting-edge open-source framework, apsimNGpy, empowers advanced agroecosystem modeling through the utilization\r\nof object-oriented principles. It features fast batch file simulation, model prediction, evaluation,\r\napsimx file editing, seamless weather data retrieval, and efficient soil profile development\r\n\r\nRequirements\r\n***********************************************************************************\r\n1. Dotnet, install from https://learn.microsoft.com/en-us/dotnet/core/install/\r\n2. Python3\r\n3. APSIM: 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:\r\n4. Utilize the APSIM installer provided for this purpose.\r\n5. Build APSIM from its source code. This is comming soon\r\n6. Minimum; 8GM RAM, CPU Core i7\r\n\r\n.. _Installation:\r\n\r\nInstallation\r\n\r\n********************************************************************************\r\n\r\nAll versions are currently in development, phase and they can be installed as follows:\r\n\r\n- Method 1. install from PyPI\r\n\r\n.. code:: bash\r\n\r\n pip install apsimNGpy\r\n\r\n- Method 1. clone the current development repository\r\n\r\n.. code:: bash\r\n\r\n git clone https://github.com/MAGALA-RICHARD/apsimNGpy.git\r\n cd apsimNGpy\r\n pip install .\r\n\r\n- Method 2. Use pip straight away and install from github\r\n\r\n.. code:: bash\r\n\r\n pip install git+https://github.com/MAGALA-RICHARD/apsimNGpy.git@dev\r\n\r\n\r\nGETTING STARTED\r\n*****************************\r\n\r\nBefore using apsimNGpy, it is necessary to install APSIM. Please follow the instructions provided at the following link to complete the installation: https://www.apsim.info/download-apsim/downloads/\r\nfor MAcOS or Linux users see: https://apsimnextgeneration.netlify.app/install/\r\nmodel documentation and tutorial are also available via; https://docs.apsim.info/\r\nwe expect that by accepting to use apsimNGpy, you have a basic understanding of APSIM process-based model, therefore, our focus is to make sure you are able to use apsimNGpy\r\n\r\nIn addition, make sure that the APSIM installation binaries folder is added to the system path.\r\nif you run the following code and returns None you need to do something as explained below.\r\n\r\n- 1. Use command line interface\r\n\r\n.. code-block:: bash\r\n\r\n apsim_bin_path -s\r\n\r\n- 2. Use apsimNGpy config module\r\n\r\n.. code-block:: python\r\n\r\n from apsimNGpy.core import config\r\n print(config.get_apsim_bin_path())\r\n\r\nYou can also try to check if automatic search will be successful as follows\r\n\r\n.. code-block:: bash\r\n\r\n apsim_bin_path --auto_search\r\n\r\nThe short cut\r\n\r\n.. code-block:: bash\r\n\r\n apsim_bin_path -a\r\n\r\n\r\nLocating the APSIM Binaries\r\n***************************************************************\r\nBy default the APSIM binaries are located automatically. The process for determining the APSIM binary path is as follows:\r\n\r\nIn apsimNGpy, priority is first given to the user-supplied binary path.\r\nIf no path is supplied, the module searches through the Python global environment\r\nusing the os module. If that fails, it searches through other folders.\r\nIf all approaches are exhausted and no valid path is found, a ValueError will be raised.\r\n\r\n\r\nChanging/setting the APSIM installation binaries path\r\n*********************************************************************************\r\nIf the automatic search fails, please follow one of the steps below to resolve the issue:\r\n\r\n1. Manually configure the APSIM binary path. To do this:\r\n*************************************************************************************\r\n\r\nIn your home folder you could look for folder named apsimNGpy_meta_info './APSIMNGpy_meta_data'\r\n 1. Locate the folder named `APSIMNGpy_meta_info` in your home directory (e.g., `./APSIMNGpy_meta_data`).\r\n 2. Open the file `apsimNGpy_config.ini` within this folder.\r\n 3. Modify the `apsim_location` entry to reflect your desired APSIM binary path.\r\n\r\n2. change based os.environ module\r\n************************************\r\n\r\nAlternatively, you can use the code at the top of your script as follows\r\n\r\n.. code-block:: python\r\n\r\n # Search for the APSIM binary installation path and add it to os.environ as follows:\r\n import os\r\n os.environ['APSIM'] = r'path/to/your/apsim/binary/folder/bin'\r\n\r\n- Note:\r\n\r\nThis approach may not work consistently in all scenarios, but you can try it.\r\nThe above script line should always be placed at the beginning of your simulation script.\r\nHowever, why follow this approach when you can achieve the same result more efficiently? See the approach below:\r\n\r\n3. Use the apsimNGpy config module:\r\n*****************************************************************\r\n\r\n.. code-block:: python\r\n \r\n from apsimNGpy.config import set_apsim_bin_path\r\n\r\n # Set the path to the APSIM binaries:\r\n set_apsim_bin_path(path=r'path/to/your/apsim/binary/folder/bin')\r\n\r\n\r\n4. Use command line interface\r\n*********************************************************************\r\n\r\nAfter installing apsimNGpy, navigate to your terminal and run the following\r\n\r\n.. code-block:: bash\r\n\r\n apsim_bin_path -u 'path/to/your/apsim/binary/folder/bin'\r\n\r\nOr\r\n\r\n.. code-block:: bash\r\n\r\n apsim_bin_path --update 'path/to/your/apsim/binary/folder/bin'\r\n\r\n\r\n# Now that the path is set, you can import any module attached to pythonnet.\r\n*********************************************************************************************\r\n\r\n.. code-block:: python\r\n \r\n # For example, try importing the ApsimModel class:\r\n from apsimNGpy.core.apsim import ApsimModel\r\n\r\n.. _Usage:\r\n\r\nThe above code is also applicable for running different versions of APSIM models.\r\nThe `set_apsim_bin_path` function can be called once and retained unless you uninstall `apsimNGpy`\r\nor the APSIM application itself. This implies that you can switch between apsim versions easily if you have more than one versions installed on your computer\r\n\r\nExamples\r\n********\r\n\r\nThis example demonstrates how to use `apsimNGpy` to load a default simulation, run it, retrieve results, and visualize the output.\r\n\r\n.. code-block:: python\r\n\r\n # Import necessary modules\r\n import apsimNGpy\r\n from apsimNGpy.core.base_data import load_default_simulations\r\n from apsimNGpy.core.apsim import ApsimModel as SoilModel\r\n from pathlib import Path\r\n import os\r\n from apsimNGpy.validation.visual import plot_data\r\n\r\nThe above code imports the necessary modules for running APSIM simulations. This includes `apsimNGpy` modules for loading default simulations and managing results, as well as standard Python libraries for file handling and visualization.\r\n\r\n\r\n.. code-block:: python\r\n\r\n # Load the default simulation\r\n soybean_model = load_default_simulations(crop='soybean') # Case-insensitive crop specification\r\n\r\nThe `load_default_simulations` function loads a default APSIM simulation for the specified crop. In this example, the crop is set to soybean, but you can specify other crops as needed.\r\n\r\n.. code:: python\r\n\r\n # Load the simulation path without initializing the object\r\n soybean_path_model = load_default_simulations(crop='soybean', simulation_object=False)\r\n\r\nIf you prefer not to initialize the simulation object immediately, you can load only the simulation path by setting `simulation_object=False`.\r\n\r\n.. code-block:: python\r\n\r\n # Initialize the APSIM model with the simulation file path\r\n apsim = SoilModel(soybean_path_model)\r\n\r\nThis code initializes the APSIM model using the previously loaded simulation file path.\r\n\r\n.. code-block:: python\r\n\r\n # Run the simulation\r\n apsim.run(report_name='Report')\r\n\r\nThe `run` method executes the simulation. The `report_name` parameter specifies which data table from the simulation will be used for results.\r\n\r\n.. note::\r\n report_name accepts a list of simulation data tables and hence can return a list of pandas data frame for each data table and if get_dict = True, a dictionary is returned\r\n with each data table name as the key and data frame as the values\r\n\r\n.. code-block:: python\r\n\r\n # Retrieve and save the results\r\n df = apsim.results\r\n df.to_csv('apsim_df_res.csv') # Save the results to a CSV file\r\n print(apsim.results) # Print all DataFrames in the storage domain\r\n\r\nAfter the simulation runs, results are stored in the `apsim.results` attribute as pandas DataFrames. Please see note above. These results can be saved to a CSV file or printed to the console.\r\n\r\nThe code below retrieves the names of simulations from the APSIM model and examines the management modules used in the specified simulations.\r\n\r\n.. code-block:: python\r\n\r\n # Examine management modules in the simulation\r\n sim_name = apsim.simulation_names # Retrieve simulation names\r\n apsim.examine_management_info(simulations=sim_name)\r\n\r\n\r\nYou can preview the current simulation in the APSIM graphical user interface (GUI) using the `preview_simulation` method.\r\n\r\n\r\n.. code-block:: python\r\n\r\n # Preview the current simulation in the APSIM GUI\r\n apsim.preview_simulation()\r\n\r\n.. note::\r\n apsimNGpy clones a every simulation file before passing it it dotnet runner, however, when you open it in GUI, take note of the version it will be difficult to re-open\r\n it in the lower versions after opening it in the higher versions of apsim\r\n\r\nVisualise the results. please note that python provide very many plotting libraries below is just a basic description of your results\r\n\r\n.. code-block:: python\r\n\r\n # Visualize the simulation results\r\n res = apsim.results['MaizeR'] # Replace with the appropriate report name\r\n plot_data(df['Clock.Today'], df.Yield, xlabel='Date', ylabel='Soybean Yield (kg/ha)')\r\n\r\nFinally, the `plot_data` function is used to visualize the simulation results. Replace 'df['Clock.Today']' and `df.Yield` with the appropriate report name and column from your simulation results.\r\n\r\nA graph similar to the example below should appear\r\n\r\n\r\nCongratulations you have successfully used apsimNGpy package\r\n*********************************************************************************\r\n.. image:: ./apsimNGpy/examples/Figure_1.png\r\n :alt: /examples/Figure_1.png\r\n\r\nChange APSIM simulation dates \r\n*********************************************************************************\r\n.. code-block:: python\r\n\r\n import apsimNGpy\r\n from apsimNGpy.core.base_data import load_default_simulations\r\n from apsimNGpy.core.apsim import ApsimModel as SoilModel\r\n from pathlib import Path\r\n import os\r\n from apsimNGpy.validation.visual import plot_data\r\n cwd = Path.cwd().home() # sending this to your home folder\r\n wd = cwd.joinpath(\"apsimNGpy_demo\")\r\n if not wd.exists():\r\n os.mkdir(wd)\r\n # change directory\r\n os.chdir(wd)\r\n # Get maize model\r\n maize_model = load_default_simulations(crop = 'maize')\r\n\r\n maize_model.change_simulation_dates(start_date='01/01/1998', end_date='12/31/2010')\r\n\r\nChange APSIM model management decisions\r\n*********************************************************************************\r\n.. code-block:: python\r\n\r\n # First, examine the manager scripts in the simulation node\r\n apsim.examine_management_info()\r\n # now create dictionary holding the parameters. the key to this is that the name of the script manage must be\r\n passed in the dictionary.\r\n\r\n # in this node we if have a script named the Simple Rotation,we want to change the rotation to maybe Maize, Wheat or\r\n something else\r\n rotation = {'Name': \"Simple Rotation\", \"Crops\": 'Maize, Wheat, Soybean'}, # the crops must be seperated my commas\r\n apsim.update_mgt(management = rotation)\r\n # now you cans see we passed rotation as a tuple. That means you can add other scripts as your needs suggest. They will all be changed at the\r\n #same time\r\n\r\nPopulating the APSIM model with new weather data\r\n*********************************************************************************\r\n.. code-block:: python\r\n\r\n from apsimNGpy.core.weather import daymet_bylocation_nocsv\r\n lonlat = -93.08, 42.014\r\n start_year, end_year = 2000, 2002\r\n wf = daymet_bylocation_nocsv(lonlat, startyear, endyear, filename=\"mymet.met\")\r\n # you may need to first see what file currently exists in the model\r\n mis = apsim.show_met_file_in_simulation()\r\n print(mis)\r\n # change\r\n maize_model.replace_met_file(weather_file=wf)\r\n # check again if you want to\r\n mis = maize_model.show_met_file_in_simulation()\r\n print(mis)\r\n\r\nEvaluate Predicted Variables\r\n*********************************************************************************\r\nThe apsimNGpy Python package provides a convenient way to validate model simulations against measured data. Below \r\nis a step-by-step guide on how to use the validation.evaluator module from apsimNGpy.\r\n\r\n.. code-block:: python\r\n\r\n # Start by importing the required libraries\r\n from apsimNGpy.validation.evaluator import validate\r\n import pandas as pd\r\n\r\n # Load the data if external. Replace with your own data\r\n df = pd.read_csv('evaluation.csv')\r\n apsim_results = apsim.results # Assuming 'apsim' is a predefined object from aopsimNGpy.core.core.APSIMN class and contains your simualted results\r\n\r\n # Preparing Data for Validation\r\n # Extract the relevant columns from your DataFrame for comparison. In this example, we use\r\n # 'Measured' for observed values and compare them with different model outputs:\r\n measured = df['Measured']\r\n predicted = apsim_results['MaizeR'].Yield\r\n\r\n # Now we need to pass both the measured and the observed in the validate class\r\n val = validate(measured, predicted)\r\n\r\n # Both variables should be the same length, and here we are assuming that they are sorted in the corresponding order\r\n\r\n # There are two options:\r\n # 1. Evaluate all\r\n metrics = val.evaluate_all(verbose=True)\r\n # Setting verbose=True prints all the results on the go; otherwise, a dictionary is returned with the value for each metric\r\n\r\n # 2. Select or pass your desired metric\r\n RMSE = val.evaluate(\"RMSE\")\r\n print(RMSE)\r\n\r\n # If you want to see the available metrics, use the code below\r\n available_metrics = metrics.keys()\r\n print(available_metrics)\r\n # Then select your choice from the list\r\n\r\nHow to Contribute to apsimNGpy\r\n*********************************************************************************\r\nWe welcome contributions from the community, whether they are bug fixes, enhancements, documentation updates, or new features. Here's how you can contribute to ``apsimNGpy``:\r\n\r\nReporting Issues\r\n----------------\r\n.. note::\r\n apsimNGpy is developed and maintained by a dedicated team of volunteers. We kindly ask that you adhere to our community standards when engaging with the project. Please maintain a respectful tone when reporting issues or interacting with community members.\r\n\r\nIf you find a bug or have a suggestion for improving ``apsimNGpy``, please first check the `Issue Tracker <https://github.com/MAGALA-RICHARD/apsimNGpy/issues>`_ to see if it has already been reported. If it hasn't, feel free to submit a new issue. Please provide as much detail as possible, including steps to reproduce the issue, the expected outcome, and the actual outcome.\r\n\r\nContributing Code\r\n-----------------\r\n\r\n\r\nWe accept code contributions via Pull Requests (PRs). Here are the steps to contribute:\r\n\r\nFork the Repository\r\n^^^^^^^^^^^^^^^^^^^\r\n\r\nStart by forking the ``apsimNGpy`` repository on GitHub. This creates a copy of the repo under your GitHub account.\r\n\r\nClone Your Fork\r\n^^^^^^^^^^^^^^^\r\n\r\nClone your fork to your local machine:\r\n\r\n .. code-block:: bash\r\n\r\n git clone https://github.com/MAGALA-RICHARD/apsimNGpy.git\r\n cd apsimNGpy\r\n\r\nCreate a New Branch\r\n Create a new branch for your changes:\r\n\r\n .. code-block:: bash\r\n\r\n git checkout -b your-branch-name\r\n\r\nMake Your Changes\r\n Make the necessary changes or additions to the codebase. Please try to adhere to the coding style already in place.\r\n\r\nTest Your Changes\r\n Run any existing tests, and add new ones if necessary, to ensure your changes do not break existing functionality.\r\n\r\nCommit Your Changes\r\n Commit your changes with a clear commit message that explains what you've done:\r\n\r\n .. code-block:: bash\r\n\r\n git commit -m \"A brief explanation of your changes\"\r\n\r\nPush to GitHub\r\n Push your changes to your fork on GitHub:\r\n\r\n .. code-block:: bash\r\n\r\n git push origin your-branch-name\r\n\r\nSubmit a Pull Request\r\n Go to the ``apsimNGpy`` repository on GitHub, and you'll see a prompt to submit a pull request based on your branch. Click on \"Compare & pull request\" and describe the changes you've made. Finally, submit the pull request.\r\n\r\nUpdating Documentation\r\n----------------------\r\n\r\nImprovements or updates to documentation are greatly appreciated. You can submit changes to documentation with the same process used for code contributions.\r\n\r\nJoin the Discussion\r\n-------------------\r\n\r\nFeel free to join in discussions on issues or pull requests. Your feedback and insights are valuable to the community!\r\n\r\nVersion 0.0.27.8 new features\r\n********************************************************************************\r\nDynamic handling of simulations and their properties\r\n\r\nreplacements made easier\r\n\r\nobject oriented factorial experiment set ups and simulations\r\n\r\nAcknowledgements\r\n*********************************************************************************\r\nThis project, *ApsimNGpy*, greatly appreciates the support and contributions from various organizations and initiatives that have made this research possible. We extend our gratitude to Iowa State University's C-CHANGE Presidential Interdisciplinary Research Initiative, which has played a pivotal role in the development of this project. Additionally, our work has been significantly supported by a generous grant from the USDA-NIFA Sustainable Agricultural Systems program (Grant ID: 2020-68012-31824), underscoring the importance of sustainable agricultural practices and innovations.\r\n\r\nWe would also like to express our sincere thanks to the APSIM Initiative. Their commitment to quality assurance and the structured innovation program for APSIM's modelling software has been invaluable. APSIM's software, which is available for free for research and development use, represents a cornerstone for agricultural modeling and simulation. For further details on APSIM and its capabilities, please visit `www.apsim.info <http://www.apsim.info>`_.\r\n\r\nOur project stands on the shoulders of these partnerships and support systems, and we are deeply thankful for their contribution to advancing agricultural research and development. Please not that that this library is designed as a bridge to APSIM software, and we hope that by using this library, you have the appropriate APSIM license to do so whether free or commercial.\r\n\r\nLastly but not least, ApsimNGpy is not created in isolation but draws inspiration from apsimx, an R package (https://cran.r-project.org/web/packages/apsimx/vignettes/apsimx.html). We acknowledge and appreciate the writers and contributors of apsimx for their foundational work. ApsimNGpy is designed to complement apsimx by offering similar functionalities and capabilities in the Python ecosystem.\r\n\r\n\r\n# Changelog\r\n******************************************************************************************************\r\n\r\nThe earlier versions of apsimNGpy were too experimental with a lot of bugs. Therefore tracking started with version 0..29\r\n## [0.29.0] - 2025-01-15\r\n\r\n### Added\r\n************************************************************************************\r\n\r\n- New logging feature for better debug capability.\r\n- command line interface to run models faster using the command and crop module\r\n- command line interface to change the apsim binary path using the apsim_bin_path module\r\n- more detailed installation documentation\r\n\r\n## Fixed\r\n**************************************************************************************\r\n\r\n- config module to run on all operating systems\r\n- import of load_default simulations\r\n\r\n\r\n## [0.3.0] - 2025-01-20\r\n## Fixed\r\n**************************************************************************************\r\n\r\n- fixed package to run all latest versions\r\n- handle multiple reports tables in run method, return a concat of the different data frame\r\n\r\n## Added\r\n*****************************************************************************\r\n\r\n- APSIMNG.run now return pandas data frame consistently\r\n- files named by default are tagged by the corresponding APSIM installed version\r\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "apsimx next generation package interface",
"version": "0.31",
"project_urls": {
"Homepage": "https://github.com/MAGALA-RICHARD/apsimNGpy.git"
},
"split_keywords": [
"python",
" apsim next generation",
" pythonnet",
" crop modeling"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "43ed4ec7663dc14603a80b6c4f87d2ad1d2f24e832ceb6ddc645aa4fc08dd942",
"md5": "a53ecc3c536eba551e9dd92c6f0a4e6a",
"sha256": "3769a10f91fb1a4371f549435a7447509bf8812e8cbde8bdfbf76434f9e973ba"
},
"downloads": -1,
"filename": "apsimNGpy-0.31-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a53ecc3c536eba551e9dd92c6f0a4e6a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 1684753,
"upload_time": "2025-02-21T00:22:01",
"upload_time_iso_8601": "2025-02-21T00:22:01.198795Z",
"url": "https://files.pythonhosted.org/packages/43/ed/4ec7663dc14603a80b6c4f87d2ad1d2f24e832ceb6ddc645aa4fc08dd942/apsimNGpy-0.31-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "a596174076f5090ae2e5c2ca4a35f68df93f340c5cd7ac6caf15fecc1c5db730",
"md5": "065299c0283383e410019480b61c4905",
"sha256": "33cc837ae79396854d3530cfe260594cf4bcf91a68f40325a691be792d51ae46"
},
"downloads": -1,
"filename": "apsimngpy-0.31.tar.gz",
"has_sig": false,
"md5_digest": "065299c0283383e410019480b61c4905",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 1582541,
"upload_time": "2025-02-21T00:22:03",
"upload_time_iso_8601": "2025-02-21T00:22:03.336935Z",
"url": "https://files.pythonhosted.org/packages/a5/96/174076f5090ae2e5c2ca4a35f68df93f340c5cd7ac6caf15fecc1c5db730/apsimngpy-0.31.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-21 00:22:03",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "MAGALA-RICHARD",
"github_project": "apsimNGpy",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "apsimngpy"
}