### Inspect Clock Model Parameters Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/inspect_model_parameters.md This example demonstrates inspecting the 'Clock' model to retrieve its start and end simulation times. It shows how to get the full datetime objects. ```python model_instance.inspect_model_parameters('Clock', simulations='Simulation', model_name='Clock') ``` -------------------------------- ### Install and Launch Jupyter Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/README.rst Instructions for setting up a Python environment, installing necessary libraries, and launching Jupyter Lab or Notebook. ```bash python -m venv .venv .venv\Scripts\activate pip install apsimNGpy jupyter pandas matplotlib seaborn jupyter lab # or jupyter notebook ``` -------------------------------- ### Install Prerequisites for apsimNGpy Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/manage_env.md Installs necessary packages and initializes a new project environment for apsimNGpy. ```bash pip install python-dotenv pip install uv mkdir my_project cd my_project uv venv # activate as required uv init uv pip install apsimNGpy ``` -------------------------------- ### Install apsimNGpy with uv Source: https://github.com/magala-richard/apsimngpy/blob/main/README.rst Install the apsimNGpy library using the uv virtual environment manager. ```bash uv pip install apsimNGpy ``` -------------------------------- ### Install apsimNGpy from Development Repository Source: https://github.com/magala-richard/apsimngpy/blob/main/README.rst Clone the apsimNGpy repository and install it locally. ```bash git clone https://github.com/MAGALA-RICHARD/apsimNGpy.git cd apsimNGpy pip install . ``` -------------------------------- ### setup Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Sets up the simulation environment. ```APIDOC ## setup() ### Description Sets up the simulation environment. ### Method Not specified (likely a method call within the library). ### Endpoint N/A (Library method) ### Parameters N/A (Method specific, details not provided in source) ### Request Example N/A ### Response N/A ``` -------------------------------- ### Install apsimNGpy Directly from GitHub Source: https://github.com/magala-richard/apsimngpy/blob/main/README.rst Install the apsimNGpy library directly from its GitHub repository. ```bash pip install git+https://github.com/MAGALA-RICHARD/apsimNGpy.git ``` -------------------------------- ### Define Multiple Soil Parameters Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/calibrate.md Example demonstrating how to optimize multiple parameters within the same APSIM node path. It includes multiple variable types, starting values, and candidate parameters. ```python soil_param = { "path": ".Simulations.Simulation.Field.Soil.Organic", "vtype": [UniformVar(1, 200), UniformVar(1, 3)], "start_value": [1, 2], "candidate_param": ["FOM", 'Carbon'], "other_params": {"FBiom": 0.04, }, } ``` -------------------------------- ### Load Crop from Disk Example Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Demonstrates loading a crop from disk with a custom output path. The function returns the path to the copied APSIM file. ```python >>> load_crop_from_disk("Maize", out ='my_maize_example.apsimx') 'C:/path/to/temp_uuid_Maize.apsimx' ``` -------------------------------- ### Install apsimNGpy from PyPI Source: https://github.com/magala-richard/apsimngpy/blob/main/README.rst Install the stable version of the apsimNGpy library using pip. ```bash pip install apsimNGpy ``` -------------------------------- ### Install APSIMNGPY and Pandas Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/un_repaired/generating_descriptics.ipynb Installs the necessary libraries for running APSIMNGPY simulations and data manipulation with Pandas. Tabulate is optional for pretty printing. ```bash pip install apsimNGpy pandas # optional pretty printing (used later) pip install tabulate ``` -------------------------------- ### Install apsimNGpy in Editable Mode (Command Line) Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/contribute.md Navigates to the project root directory and installs apsimNGpy in editable mode using the command line. This is a prerequisite for command-line testing. ```bash cd apsimNGpy pip install -e . ``` -------------------------------- ### Finalize and Run Sensitivity Experiment Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Complete the setup of the sensitivity analysis by finalizing the experiment with the chosen method and aggregation column, then execute the analysis. ```python exp.finalize(method='Morris', aggregation_column_name='Clock.Today') exp.run() ``` -------------------------------- ### Initialize ExperimentManager and Add Factors Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/un_repaired/generating_descriptics.ipynb Initializes the ExperimentManager with a specified model and adds varying factors for simulation. This is the setup phase before running the experiment. ```python from apsimNGpy.core.experimentmanager import ExperimentManager experiment = ExperimentManager(model ='Maize') # init the experiment experiment.init_experiment(permutation=True) ``` ```python # add factors # Population experiment.add_factor(specification='[Sow using a variable rule].Script.Population = 4, 6, 8, 10') # Nitrogen fertilizers experiment.add_factor(specification='[Fertilise at sowing].Script.Amount= 0, 100,150, 200, 250') ``` -------------------------------- ### Inspect Crop Model using Full Namespace String Path Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/model inspection.md Get the path to the crop model by providing its full namespace as a string. ```python model.inspect_model('Models.Core.IPlant') ``` -------------------------------- ### Run Simulation and Get Results Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Instantiate an ApsimModel, run the simulation, and access the results. This is useful for a basic simulation run and initial data inspection. ```python >>> from apsimNGpy.core.apsim import ApsimModel # create an instance of ApsimModel class >>> model = ApsimModel("Maize", out_path="my_maize_model.apsimx") # run the simulation >>> model.run() # get the results >>> df = model.results # do something with the results e.g. get the mean of numeric columns >>> df.mean(numeric_only=True) Out[12]: CheckpointID 1.000000 SimulationID 1.000000 Maize.AboveGround.Wt 1225.099950 Maize.AboveGround.N 12.381196 Yield 5636.529504 Maize.Grain.Wt 563.652950 Maize.Grain.Size 0.284941 Maize.Grain.NumberFunction 1986.770519 Maize.Grain.N 7.459296 Maize.Total.Wt 1340.837427 ``` -------------------------------- ### Access Clock Start Year Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Accesses the 'year' component of the 'Start' parameter for the Clock model. Use this to get the simulation's start year. ```python model_instance.inspect_model_parameters('Clock', simulations='Simulation', model_name='Clock', parameters='Start').year # gets the start year only ``` -------------------------------- ### Extract Year from Clock Start Parameter Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/inspect_model_parameters.md This example demonstrates how to extract just the year from the 'Start' parameter of the 'Clock' model. ```python model_instance.inspect_model_parameters('Clock', simulations='Simulation', model_name='Clock', parameters='Start').year ``` -------------------------------- ### Initialize MultiCoreManager Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/batch_simulations.ipynb Set up the MultiCoreManager with a database path, aggregation function, and table prefix for simulation results. ```python db = Path.home() / 'jupiter_example.db' Parallel = MultiCoreManager(db_path=db, agg_func='sum', table_prefix='jupter_example',) ``` -------------------------------- ### Import necessary libraries and set up output directory Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/un_repaired/data_plotting_and_visualization.ipynb Imports ExperimentManager, pyplot, and Path. It also creates a directory for saving images if it doesn't exist. ```python from apsimNGpy.core.experimentmanager import ExperimentManager from matplotlib import pyplot as plt from pathlib import Path dir_p = Path.cwd().parent.parent/'images' dir_p.mkdir(exist_ok=True) ``` -------------------------------- ### Set Up Workspace Directories Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/app_multi_process.md Defines and creates necessary directories for plots and simulation outputs using pathlib. ```python Base_DIR = Path(__file__).parent plots = Base_DIR / 'Plots' plots.mkdir(exist_ok=True) out_apsimx = Base_DIR / 'output' out_apsimx.mkdir(exist_ok=True) ``` -------------------------------- ### Define Soil Organic Factor Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/calibrate.md Example of defining a factor for soil organic parameters. It specifies the model path, variable type (UniformVar), starting value, candidate parameter, and other fixed parameters. ```python soil_param = { "path": ".Simulations.Simulation.Field.Soil.Organic", "vtype": [UniformVar(1, 200)], "start_value": [1], "candidate_param": ["FOM"], "other_params": {"FBiom": 0.04, "Carbon": 1.89}, } ``` -------------------------------- ### Add continuous control variables to the problem Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/OPT.md Use `add_control` to specify decision variables, including their path within the APSIM model, bounds, data type, and starting values. This example adds fertilization amount and sowing population. ```python problem.add_control( path='.Simulations.Simulation.Field.Fertilise at sowing', Amount="?", bounds=[50, 300], v_type='int', start_value=150 ) problem.add_control( path='.Simulations.Simulation.Field.Sow using a variable rule', Population="?", v_type='int', bounds=[4, 14], start_value=8 ) ``` -------------------------------- ### Initialize and Run Jobs (C# Engine with Table Prefix) Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md This example shows how to initialize MultiCoreManager with a specific database path, aggregation function, and table prefix. It then runs jobs using the C# engine, specifying the number of cores and threads. The results are stored in the 'results' attribute. ```python from apsimNGpy.core.mult_cores import MultiCoreManager from pathlib import Path db= (Path.home()"/test_agg.db").resolve() if __name__ == '__main__': workspace = Path.home() Parallel = MultiCoreManager(db_path=db, agg_func='sum', table_prefix='di') jobs = ({'model': 'Maize', 'ID': i, 'inputs': [{'path': '.Simulations.Simulation.Field.Fertilise at sowing', 'Amount': i}]} for i in range(200)) Parallel.run_all_jobs(jobs=jobs, n_cores=8, engine='csharp', threads=False,) dff = Parallel.results print(dff.shape) ``` -------------------------------- ### Instantiate ApsimModel and Get Weather from Web Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/weather.md Instantiates an ApsimModel and retrieves weather data from the web using specified coordinates and date range. Ensure the simulation's start and end dates match the retrieved data to avoid errors. ```python from apsimNGpy.core.apsim import ApsimModel maize_model = ApsimModel(model='Maize') # replace maize with your apsim template file # replace the weather with lonlat specification as follows; maize_model.get_weather_from_web(lonlat = (-93.885490, 42.060650), start = 1990, end =2001) ``` -------------------------------- ### Initializing ApsimModel and Running Simulation Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Demonstrates how to initialize an ApsimModel and run a simulation, which is a prerequisite for plotting results using functions like series_plot. ```python from apsimNGpy.core.apsim import ApsimModel model = ApsimModel(model= 'Maize') # run the results model.run(report_names='Report') ``` -------------------------------- ### Custom parallel processing setup Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/tests/demos/mult_core.rst Demonstrates building a custom parallel processing pipeline using ApsimModel, database utilities, and SQLAlchemy for direct database interaction. ```python from pathlib import Path from apsimNGpy.core.apsim import ApsimModel from apsimNGpy.core_utils.database_utils import read_db_table from apsimNGpy.parallel.process import custom_parallel import pandas as pd from sqlalchemy import create_engine DATABAse = str(Path('test_custom.db').resolve()) # define function to insert insert results def insert_results(db_path, results, table_name): """ Insert a pandas DataFrame into a SQLite table. Parameters ---------- db_path : str or Path Path to the SQLite database file. results : pandas.DataFrame DataFrame to insert into the database. table_name : str Name of the table to insert the data into. """ if not isinstance(results, pd.DataFrame): raise TypeError("`results` must be a pandas DataFrame") engine = create_engine(f"sqlite:///{db_path}") results.to_sql(table_name, con=engine, if_exists='append', index=False) def worker(nitrogen_rate, model): out_path = Path(f"_{nitrogen_rate}.apsimx").resolve() model = ApsimModel(model, out_path=out_path) model.edit_model("Models.Manager", model_name='Fertilise at sowing', Amount=nitrogen_rate) model.run(report_name="Report") df = model.results # we can even create column for each simulation ``` -------------------------------- ### Inspect Model and Get Simulated Output Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Inspects the model for report names and retrieves simulated output for specified variables. Use `axis=0` to get results as rows and `axis=1` to get results as columns. ```python >>> model.inspect_model('Models.Report', fullpath=False) ['Report', 'soc'] >>> model.run() >>> model.get_simulated_output(["soc", "Report"], axis=0) CheckpointID SimulationID ... Maize.Grain.N Maize.Total.Wt 0 1 1 ... NaN NaN 1 1 1 ... NaN NaN 2 1 1 ... NaN NaN 3 1 1 ... NaN NaN 4 1 1 ... NaN NaN 5 1 1 ... NaN NaN 6 1 1 ... NaN NaN 7 1 1 ... NaN NaN 8 1 1 ... NaN NaN 9 1 1 ... NaN NaN 10 1 1 ... NaN NaN 11 1 1 ... 11.178291 1728.427114 12 1 1 ... 6.226327 922.393712 13 1 1 ... 0.752357 204.108770 14 1 1 ... 4.886844 869.242545 15 1 1 ... 10.463854 1665.483701 16 1 1 ... 11.253916 2124.739830 17 1 1 ... 5.044417 1261.674967 18 1 1 ... 3.955080 951.303260 19 1 1 ... 11.080878 1987.106980 20 1 1 ... 9.751001 1693.893386 [21 rows x 17 columns] ``` ```python >>> model.get_simulated_output(['soc', 'Report'], axis=1) CheckpointID SimulationID ... Maize.Grain.N Maize.Total.Wt 0 1 1 ... 11.178291 1728.427114 1 1 1 ... 6.226327 922.393712 2 1 1 ... 0.752357 204.108770 3 1 1 ... 4.886844 869.242545 4 1 1 ... 10.463854 1665.483701 5 1 1 ... 11.253916 2124.739830 6 1 1 ... 5.044417 1261.674967 7 1 1 ... 3.955080 951.303260 8 1 1 ... 11.080878 1987.106980 9 1 1 ... 9.751001 1693.893386 10 1 1 ... NaN NaN [11 rows x 19 columns] ``` -------------------------------- ### Initializing Sobol Sensitivity Analysis Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/sens.md Shows how to initialize the SensitivityManager for a Sobol analysis. Specify the model name and an output path for the simulation results. ```python sobol = SensitivityManager("Maize", out_path='sob.apsimx') ``` -------------------------------- ### Edit Clock Start and End Dates Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Edits the start and end dates for the simulation clock. ```APIDOC ## edit_model (Clock) ### Description Edits the start and end dates for the simulation clock. ### Method model.edit_model ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model_type** (string) - Required - Type of the model to edit, e.g., 'Clock'. - **simulations** (string) - Required - The name of the simulation. - **model_name** (string) - Required - The name of the clock model. - **Start** (string) - Required - The simulation start date in 'YYYY-MM-DD' format. - **End** (string) - Required - The simulation end date in 'YYYY-MM-DD' format. ``` -------------------------------- ### Run APSIM Simulation using .env file and Binary Path Key Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/getting started.md Initialize APSIM using a .env file to specify the binary path. Assumes the .env file is located in a 'config' directory. ```python from apsimNGpy import Apsim with Apsim(dotenv_path = './config/.env', bin_key ='APSIM_BIN') as apsim: # assumes that .env is in the config directory with apsim.ApsimModel('Wheat') as model: model.run() df= model.results ``` -------------------------------- ### apsimNGpy.config.Configuration.__init__ Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Initializes the Configuration object, optionally setting the APSIM binary path. ```APIDOC ## apsimNGpy.config.Configuration.__init__ ### Description Initializes the Configuration object. In the future, this module will contain all the constants required by the package. Users will be able to override these values if needed by importing this module before running any simulations. ### Parameters - **bin_path** (str or Path, optional) - The path to the APSIM binary directory. - **_bin_path** (str, Path, or None, optional) - Internal parameter, likely for managing binary paths. ``` -------------------------------- ### Example Total-Order Sensitivity Index Output Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/sensitivity/Tutorial.rst Example output of the total-order sensitivity index for a specific model output. ```python array([0.44579877, 0.91875446]) ``` -------------------------------- ### Example First-Order Sensitivity Index Output Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/sensitivity/Tutorial.rst Example output of the first-order sensitivity index for a specific model output. ```none array([0.43932783, 0.84502346]) ``` -------------------------------- ### Calculate RMSE and Evaluate All Metrics Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Demonstrates how to initialize the Validate class with observed and predicted data, calculate the Root Mean Square Error (RMSE), and evaluate all available performance metrics. ```python from apsimNGpy.optimizer.problems.validation import Validate import numpy as np obs = np.array([1.2, 2.4, 3.6, 4.8, 5.0]) pred = np.array([2.0, 3.5, 4.2, 5.7, 6.0]) val = Validate(obs, pred) print(val.RMSE()) print(val.evaluate_all(verbose=True)) ``` -------------------------------- ### Editable Installation for Developers Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/getting started.md Install apsimNGpy in editable mode, allowing for direct code changes to be reflected without reinstallation. ```console git clone https://github.com/MAGALA-RICHARD/apsimNGpy.git cd apsimNGpy pip install -e . ``` -------------------------------- ### Create Nested Directories and Write CSV using os Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Demonstrates creating nested directories using `os.makedirs` with `exist_ok=True` to ensure the directory structure exists before writing a CSV file. ```pycon >>> import os >>> os.makedirs('folder/subfolder', exist_ok=True) >>> df.to_csv('folder/subfolder/out.csv') ``` -------------------------------- ### Example Second-Order Sensitivity Index Output Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/sensitivity/Tutorial.rst Example output of a second-order sensitivity index, showing the interaction effect between two parameters. ```none np.float64(0.025099857475360032) ``` -------------------------------- ### Importing necessary libraries Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/evaluate.md Import the `obs` object for observed data and the `ApsimModel` class for running simulations. ```python from apsimNGpy.tests.unittests.test_factory import obs from apsimNGpy.core.apsim import ApsimModel ``` -------------------------------- ### Initialize Apsim with .env and Custom Key Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Initialize the Apsim context using a .env file for configuration and a custom key to specify the APSIM bin path. This allows for flexible configuration management, especially in projects with multiple APSIM versions. ```python from pathlib import Path with Apsim(dotenv_path=Path(".env", bin_key="APSIM_BIN_PATH") as apsim: model =apsim.ApsimModel('Wheat") ``` -------------------------------- ### Load Crop Simulation File Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Load a default APSIM crop simulation file (e.g., .apsimx) from the /Examples directory. This is useful for programmatically running standard crop simulations without manual GUI interaction. ```python load_crop_from_disk(crop='Wheat', out='.', bin_path=None, cache_path=True, suffix='.apsimx') ``` -------------------------------- ### Get Available Variables List Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/sens.md Access the column names of the statistics DataFrame to get a list of all available variables and metrics computed during the sensitivity analysis. ```python morris.statistics.columns ``` -------------------------------- ### Edit Clock Start and End Dates Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/edit.md Modify the simulation's start and end dates by editing the 'Clock' module. Ensure the date format is correct. ```python model = ApsimModel(model='Maize') model.edit_model( model_type='Clock', simulations='Simulation', model_name='Clock', Start='2021-01-01', End='2021-01-12') ``` -------------------------------- ### Initializing and running simulations with MultiCoreManager Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/tests/demos/mult_core.rst Initialize the MultiCoreManager with a database path and run all generated jobs using a specified number of cores. Results can then be retrieved as a DataFrame. ```python if __name__ == '__main__': # a guard is required # initialize task_manager = MultiCoreManager(db_path=Path('test.db').resolve(), agg_func=None) # Run all the jobs task_manager.run_all_jobs(create_jobs, n_cores=16, threads=False, clear_db=True) # this the progress info Processing all jobs. Please wait!: : |██████████| 100.0%| [100/100]| Complete | 1.07s/iteration | Elapsed time: 00:01:46.850 # get the results df = task_manager.get_simulated_output(axis=0) # same as data = task_manager.results # defaults is axis =0 ``` -------------------------------- ### Scoped Runtime Control with ApsimModel Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/change_logs.md This example demonstrates using the 'with' keyword for scoped runtime control, managing APSIM versions and running simulations within a defined context. It also shows how to summarize numeric outputs. ```python from apsimNGpy import Apsim with Apsim("path/to/apsim/bin") as apsim: with apsim.ApsimModel("Maize") as model: model.run() print(model.summarize_numeric()) ``` -------------------------------- ### Example Report Variable Structure Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md This is an example output from inspecting a report. It shows the structure of a report, including 'EventNames' and 'VariableNames', illustrating how variables are organized and triggered. ```none {'EventNames': ['[Maize].Harvesting'], 'VariableNames': ['[Clock].Today', '[Maize].Phenology.CurrentStageName', '[Maize].AboveGround.Wt', '[Maize].AboveGround.N', '[Maize].Grain.Total.Wt*10 as Yield', '[Maize].Grain.Wt', '[Maize].Grain.Size', '[Maize].Grain.NumberFunction', '[Maize].Grain.Total.Wt', '[Maize].Grain.N', '[Maize].Total.Wt', '[Clock].Today as Date']} ``` -------------------------------- ### Initializing the Sensitivity Analysis Problem Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/senstivity_analysis.py.ipynb Initializes the sensitivity analysis problem configuration using `ConfigProblem`, specifying the base model, parameters, and desired outputs. ```python runner = ConfigProblem( base_model="Maize", params=params, outputs=["Yield", "Maize.AboveGround.N"], ) ``` -------------------------------- ### Example Total Sensitivity DataFrame Output Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/sensitivity/Tutorial.rst Example output of a pandas DataFrame showing total sensitivity indices (ST) and their confidence intervals for different parameters. ```python ST ST_conf Population 0.445799 0.447337 Amount 0.918754 0.492323 ``` -------------------------------- ### SensitivityManager Initialization and Setup Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Initializes the SensitivityManager and sets up the sensitivity analysis experiment structure. It allows specifying the aggregation column, method, table name, base simulation, and parameters for the Morris method. ```APIDOC ## SensitivityManager Setup ### Description Initializes the sensitivity analysis experiment structure within the APSIM file. Allows configuration of aggregation column, sensitivity method, table name, base simulation, and method-specific parameters like jumps and intervals for the Morris method. ### Method `setup(self, agg_col_name: str, method: str = 'Morris', table_name: str = 'Report', base_simulation: str = None, num_paths=None, jumps=10, intervals=20)` ### Parameters #### Query Parameters - **agg_col_name** (str) - Required - Name of the column in the database table used for aggregating values. - **method** (str) - Optional - Sensitivity method to use. Supported options are `'morris'` and `'sobol'`. Default is `'Morris'`. - **table_name** (str) - Optional - Name of the table where sensitivity results will be stored. Default is `'Report'`. - **base_simulation** (str) - Optional - Name of the base simulation to use for constructing the experiment. If `None`, the first available simulation is used as the base. - **num_paths** (int) - Optional - Number of parameter paths for the Morris method. If `None`, a default value is computed based on the number of decision variables. - **jumps** (int) - Optional - Applicable only to the Morris method. Determines the number of discrete steps each parameter is allowed to move. If omitted, a reasonable default based on the number of decision variables is used. - **intervals** (int) - Optional - Applicable only to the Morris method. Specifies the number of levels into which the range of each parameter is discretized. When not provided, a default value is chosen according to recommended Morris design practices. ### Side Effects - If a Replacements folder is present, it is moved or retained under the `Simulations` node as appropriate. - A new sensitivity experiment (Morris or Sobol) is added under `Simulations`. ### Example ```python from apsimNGpy.core.senstivitymanager import SensitivityManager exp = SensitivityManager("Maize", out_path="dtb.apsimx") exp.setup(agg_col_name='Clock.Today', method='Morris', table_name='SensitivityReport') ``` ``` -------------------------------- ### Running Apsim Model and Plotting a Series Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md This example demonstrates initializing an ApsimModel, running a simulation, and then plotting a specific variable ('Yield') against another ('Maize.Grain.Size') from the 'Report' table. It also shows how to customize plot labels. ```python >>> from apsimNGpy.core.apsim import ApsimModel >>> model = ApsimModel(model= 'Maize') # run the results >>> model.run(report_names='Report') >>>model.series_plot(x='Maize.Grain.Size', y='Yield', table='Report') >>>model.render_plot(show=True, ylabel = 'Maize yield', xlabel ='Maize grain size') ``` -------------------------------- ### Example APSIMNGpy C# Engine Results Table Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/mult_core.md This is an example of the tabular output format for results obtained when running APSIMNGpy simulations with the C# engine, displaying yield and other parameters. ```text Yield source_table ID Amount MetaProcessID 80 1747.866065 Report 0 0 63672 81 1773.798050 Report 1 1 62028 40 1792.630425 Report 2 2 60976 3 1822.193813 Report 3 3 36152 184 1854.471650 Report 4 4 13056 .. ... ... ... ... ... 103 5602.499247 Report 195 195 57804 94 5601.896106 Report 196 196 61980 93 5601.294697 Report 197 197 69492 130 5600.687519 Report 198 198 64844 101 5600.078263 Report 199 199 66580 [200 rows x 5 columns] ``` -------------------------------- ### Create and Configure an Experiment Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/examples/tutorials/running_experiments.ipynb Initiates an experiment, allowing for permutations and controlling verbosity. Adds numerical and categorical factors to define simulation variations. ```python apsimC.create_experiment(permutation=True, verbose=False) # by default it is a permutation experiment apsimC.add_factor(specification="[Fertilise at sowing].Script.Amount = 0 to 200 step 20", factor_name='Nitrogen') # use categories apsimC.add_factor(specification="[Sow using a variable rule].Script.Population =4, 10, 2, 7, 6", factor_name='Population') ``` -------------------------------- ### Install APSIMNGpy in Editable Mode Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/tests/readme.rst Installs the APSIMNGpy package in editable mode, allowing direct imports and reflecting code changes without re-installation. Run this command in your terminal from the repository root. ```bash pip install -e . ``` -------------------------------- ### View apsimNGpy version Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/cheat.md Check the installed version of the apsimNGpy library. ```python import apsimNGpy apsimNGpy.__version__ ``` -------------------------------- ### Define a Test Case for Module Additions Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/tests/readme.rst Sets up a test case class inheriting from unittest.TestCase. The setUp method initializes the model and output file, while test_add_crop_replacement defines a specific test for adding crop replacements. ```python class TestCaseAddModule(unittest.TestCase): # Set up the model to use def setUp(self): self.model = load_default_simulations('Maize') self.out = 'test_edit_model.apsimx' # Add test case def test_add_crop_replacement(self): """+++test adding crop replacement+++""" self.model.add_crop_replacements(_crop='Maize') # test logic goes here ``` -------------------------------- ### submit_all Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Submits all defined factors for optimization. This is typically called before starting the optimization process. ```APIDOC ## MixedProblem.submit_all ### Description Submits all defined factors for optimization. This is typically called before starting the optimization process. ### Method `submit_all()` ``` -------------------------------- ### Initialize ExperimentManager Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/new_experiment.md Create an ExperimentManager object by loading a base model. This sets up the experiment with a specified output path. ```python from apsimNGpy.core.experiment import ExperimentManager exp = ExperimentManager("Maize", out_path="Maize_experiment.apsimx") ``` -------------------------------- ### Get simulation names Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/cheat.md Retrieve the names of all simulations defined within the loaded APSIM file. ```python model.inspect_model('Models.Core.Simulation', fullpath=False) # Output ['Simulation'] ``` -------------------------------- ### Inspect Clock Model using String Path Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/model inspection.md Get the path to the Clock model by providing its name as a string. ```python model.inspect_model('Clock') ``` -------------------------------- ### Initialize ApsimModel without Context Manager Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/soil_refill.md Demonstrates an alternative way to initialize an ApsimModel instance directly, without using a 'with' block. ```python model = ApsimModel("Maize") ``` -------------------------------- ### Preview Simulation Output Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/cheat.md Inspect the initial state of a simulation model. ```python model.preview_simulation() ``` -------------------------------- ### Extract Year from Clock End Parameter Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/inspect_model_parameters.md This example demonstrates how to extract just the year from the 'End' parameter of the 'Clock' model. ```python model_instance.inspect_model_parameters('Clock', simulations='Simulation', model_name='Clock', parameters='End').year ``` -------------------------------- ### Initialize Apsim with Explicit Path Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Use this snippet to initialize the Apsim context by providing an explicit path to the APSIM bin directory. This is useful when the APSIM installation path is known and needs to be directly specified. ```python with Apsim(r"C:/APSIM/2025.05.1234/bin") as apsim: model = apsim.ApsimModel("Wheat") ``` -------------------------------- ### Add Factors to Experiment Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/descriptive_stats.ipynb Adds varying factors such as population density and nitrogen fertilizer amounts to the experiment setup. ```python # add factors # Population experiment.add_factor(specification='[Sow using a variable rule].Script.Population = 4, 10') # Nitrogen fertilizers experiment.add_factor(specification='[Fertilise at sowing].Script.Amount= 0, 100, 250') ``` -------------------------------- ### Initialize ApsimModel for Optimization Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/cheat.md Load an APSIM model for calibration or optimization. Replace the placeholder path with your actual model file. ```python maize_model = ApsimModel("Maize") # replace with the template path obs = [ 7000.0, 5000.505, 1000.047, 3504.000, 7820.075, 7000.517, 3587.101, 4000.152, 8379.435, 4000.301 ] ``` -------------------------------- ### Displaying apsimNGpy and APSIM Versions Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/method_chain.ipynb Prints the installed versions of apsimNGpy and the APSIM core. This is helpful for environment verification and debugging. ```python from apsimNGpy.core.config import apsim_version from apsimNGpy import version from apsimNGpy.settings import logger print(f"Notebook generated by;\n APSIM version: `{apsim_version()}`\n apsimNGpy version {version.version}") ``` -------------------------------- ### Configure Optimizer Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/calibrate.md Initialize the MixedVariableOptimizer with a defined problem. This sets up the optimizer for calibration tasks. ```python minim = MixedVariableOptimizer(problem=mp) ``` -------------------------------- ### Inspect Crop Model Name Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/model inspection.md Get the name of the crop model (e.g., Maize) using the Models.Core.IPlant namespace with fullpath=False. ```python model.inspect_model(Models.Core.IPlant, fullpath=False) ``` -------------------------------- ### Inspect Clock Model path Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/model inspection.md Get the full path to the Clock model within the simulation using the Models.Clock namespace. ```python model.inspect_model(Models.Clock) ``` -------------------------------- ### Initialize and Run ApsimModel Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Demonstrates how to initialize an ApsimModel instance with a specific simulation name and output path, then run the simulation and retrieve results. The default report table name is 'Report'. ```python from pathlib import Path from apsimNGpy.core.apsim import ApsimModel # Initialize a model model = ApsimModel( 'Maize', out_path=Path.home() / 'apsim_model_example.apsimx' ) # Run the model model.run(report_name='Report') # 'Report' is the default table name; adjust if needed # Get all results res = model.results # Or fetch a specific report table from the APSIM database report_df = model.get_simulated_output('Report') ``` -------------------------------- ### Run Experiment and Get Output Source: https://github.com/magala-richard/apsimngpy/blob/main/apsimNGpy/example_jupiter_notebooks/descriptive_stats.ipynb Executes the experiment simulations and retrieves the simulated output, sorting it by specified grouping columns. ```python # run the model experiment.run() ``` ```python # Pick one or more grouping columns that exist in your Report table df = experiment.get_simulated_output('Report') df.sort_values(by =['Amount', 'Population'], inplace=True, ascending=True) possible_groups = ['Population', 'Amount'] # drop some useless columns at this moment fd = df.drop(columns=['CheckpointID', 'SimulationID', 'Maize.Phenology.CurrentStageName', 'Maize.Grain.NumberFunction']) ``` -------------------------------- ### ConfigProblem Initialization Source: https://github.com/magala-richard/apsimngpy/blob/main/doc/api.md Initialize the core engine for APSIM–SALib sensitivity analysis. This class is used for problem configurations. ```python ConfigProblem(base_model: 'str | Path', params: 'Mapping[str, tuple[float, float]]', outputs: 'list[str]', names: 'Iterable[str] | None' = None, dist: 'list[str] | None' = None, groups: 'list[int] | None' = None, index_id: 'str' = 'ID') ```