py_champ.models package

Submodules

py_champ.models.particle_swarm module

class py_champ.models.particle_swarm.GlobalBestPSO(n_particles, dimensions, options, bounds=None, oh_strategy=None, bh_strategy='periodic', velocity_clamp=None, vh_strategy='unmodified', center=1.0, ftol=-inf, ftol_iter=1, init_pos=None, wd=None, load_dict=None)

Bases: SwarmOptimizer

to_dict()
optimize(objective_func, iters, n_processes=None, verbose=60, **kwargs)

Optimize the swarm for a number of iterations.

Performs the optimization to evaluate the objective function f for a number of iterations iter.

Parameters:
  • objective_func (callable) – objective function to be evaluated

  • iters (int) – number of iterations

  • n_processes (int) – number of processes to use for parallel particle evaluation (default: None = no parallelization)

  • verbose (bool) – enable or disable the logs and progress bar (default: True = enable logs)

  • kwargs (dict) – arguments for the objective function

Returns:

the global best cost and the global best position.

Return type:

tuple

py_champ.models.sd6_model module

class py_champ.models.sd6_model.SD6Model(*args: Any, **kwargs: Any)

Bases: Model

A Mesa model representing the SD6 simulation for agricultural and environmental systems.

This model includes various agents like fields, wells, behaviors, and aquifers. It simulates interactions and decisions of these agents over a specified time period.

Parameters:
  • pars (dict) –

    Parameters used for model calibration and setup.

    >>> settings = {
    >>>     "perceived_risk": 0.52,
    >>>     "forecast_trust": 0.70,
    >>>     "sa_thre": 0.11,
    >>>     "un_thre": 0.11,
    

  • crop_options (list) – List of available crop options for the simulation.

  • tech_options (list) – List of available technology options for irrigation and farming.

  • area_split (int) – The number of splits or divisions within each field area.

  • aquifers_dict (dict) – Settings about the aquifers in the model, mapped by their IDs.

  • fields_dict (dict) – Settings about the fields in the model, mapped by their IDs.

  • wells_dict (dict) – Settings about the wells in the model, mapped by their IDs.

  • finances_dict (dict) – Settings about the finance in the model, mapped by their IDs.

  • behaviors_dict (dict) – Settings about the behaviors in the model, mapped by their IDs.

  • prec_aw_step (dict) –

    Time-series data for available precipitation.

    >>> prec_aw_step = {
    >>> "<prec_aw1>": {
    >>>     "<year>": {
    >>>         "<crop1>": "[cm]",
    >>>         "<crop2>": "[cm]",
    >>>         }
    >>>     }
    >>> }
    

  • init_year (int, optional) – The initial year of the simulation (a year before the start year).

  • end_year (int, optional) – The final year of the simulation.

  • lema_options (tuple, optional) – The option to turn on water rights for Local Enhanced Management Areas (LEMA). (bool: flag to indicate whether LEMA regulations are in effect, str: water right id, int: year LEMA begin). Default is (True, ‘wr_LEMA_5yr’, 2013).

  • fix_state (str, optional) – A fixed state for testing or specific scenarios.

  • lema (bool, optional) – Flag to indicate whether LEMA regulations are in effect.

  • show_step (bool, optional) – Flag to control the display of step information during simulation.

  • seed (int, optional) – Seed for random number generation for reproducibility.

  • shared_config (dict, optional) – Shared configuration settings. If given, the information provided will be used to overwrite aquifers_dict, fields_dict, wells_dict, finances_dict, and behaviors_dict at the first nested level. E.g., We cannot just overwrite the sub-water_rights settings in a behaviors_dict. The entire “water_rights” nested dictionary in a behaviors_dict will be overwritten if “water_rights” exists in a shared_config.

  • **kwargs (dict) – Additional keyword arguments including time-step data like crop price, type, irrigation depth, etc. - ‘crop_price_step’: crop_price_step

schedule

The scheduler used to activate agents in the model.

Type:

BaseSchedulerByTypeFiltered

datacollector

Collects and stores data from agents and the model during the simulation.

Type:

mesa.DataCollector

(other attributes are initialized within the __init__ method)

Notes

The model is highly configurable with various parameters affecting the behavior of agents and their interactions within the simulated environment. It can be used to study the impacts of different agricultural practices and environmental policies.

step()

Advance the model by one step.

This method progresses the simulation by one year. It involves updating crop prices, deciding field types based on agent behavior, applying LEMA policy, and executing the step functions of all agents. Finally, it collects data and updates the model’s state.

The method controls the flow of the simulation, ensuring that each agent and component of the model acts according to the current time step and the state of the environment.

end()

Depose the Gurobi environment, ensuring that it is executed only when the instance is no longer needed.

static get_dfs(model)

Extract dataframes for behaviors, fields, wells, and aquifers from the model.

Parameters:

model (SD6Model) – The instance of the SD6Model.

Returns:

  • tuple of pd.DataFrame – Dataframes for behaviors, fields, wells, and aquifers.

  • This method processes the collected data to create structured dataframes, making it

  • easier to analyze and visualize the simulation results.

static get_df_sys(model, df_behaviors, df_fields, df_wells, df_aquifers)

Compile a system-level dataframe from individual agent data.

Parameters:
  • model (SD6Model) – The instance of the SD6Model.

  • df_behaviors (pd.DataFrame) – The dataframe containing data from behavior agents.

  • df_fields (pd.DataFrame) – The dataframe containing data from field agents.

  • df_wells (pd.DataFrame) – The dataframe containing data from well agents.

  • df_aquifers (pd.DataFrame) – The dataframe containing data from aquifer agents.

Returns:

  • pd.DataFrame – A dataframe representing system-level aggregated data.

  • This method aggregates data from various agents to provide a system-wide view of the model,

  • useful for analyzing overall trends and impacts.

static get_metrices(df_sys, data, targets=None, indicators_list=None)

Calculate various metrics based on system-level data and specified targets.

Parameters:
  • df_sys (pd.DataFrame) – The system-level dataframe.

  • data (dict or pd.DataFrame) – The reference or observed data for comparison.

  • targets (list) – List of targets or variables for which metrics are calculated.

  • indicators_list (list) – List of indicators to calculate, such as ‘r’, ‘rmse’, ‘kge’.

Returns:

  • pd.DataFrame – A dataframe containing calculated metrics for each target.

  • This method is useful for evaluating the performance of the model against real-world data

  • or specific objectives, providing insights into the accuracy and reliability of the simulation.

class py_champ.models.sd6_model.SD6Model_input_templates

Bases: object

py_champ.models.sd6_model_1f1w module

class py_champ.models.sd6_model_1f1w.SD6Model4SingleFieldAndWell(*args: Any, **kwargs: Any)

Bases: Model

The SD6Model_1f1w class is a simplified SD6Model that targets a single field and well owned by a farmer agent.

step()

Advance the model by one step.

This method progresses the simulation by one year. It involves updating crop prices, deciding field types based on agent behavior, applying LEMA policy, and executing the step functions of all agents. Finally, it collects data and updates the model’s state.

The method controls the flow of the simulation, ensuring that each agent and component of the model acts according to the current time step and the state of the environment.

end()

Depose the Gurobi environment, ensuring that it is executed only when the instance is no longer needed.

static get_dfs(model)
static get_metrices(df_sys, data, targets=None, indicators_list=None)

Calculate various metrics based on system-level data and specified targets.

Parameters:
  • df_sys (pd.DataFrame) – The system-level dataframe.

  • data (dict or pd.DataFrame) – The reference or observed data for comparison.

  • targets (list) – List of targets or variables for which metrics are calculated.

  • indicators_list (list) – List of indicators to calculate, such as ‘r’, ‘rmse’, ‘kge’.

Returns:

  • pd.DataFrame – A dataframe containing calculated metrics for each target.

  • This method is useful for evaluating the performance of the model against

  • real-world data or specific objectives, providing insights into the accuracy

  • and reliability of the simulation.

py_champ.models.sd6_model_1f1w_ci module

class py_champ.models.sd6_model_1f1w_ci.SD6Model_1f1w_ci(*args: Any, **kwargs: Any)

Bases: Model

A Mesa model representing the SD6 simulation for agricultural and environmental systems.

This model includes various agents like fields, wells, behaviors, and aquifers. It simulates interactions and decisions of these agents over a specified time period.

Parameters:
  • pars (dict) –

    Parameters used for model calibration and setup.

    >>> settings = {
    >>>     "perceived_risk": 0.52,
    >>>     "forecast_trust": 0.70,
    >>>     "sa_thre": 0.11,
    >>>     "un_thre": 0.11,
    

  • crop_options (list) – List of available crop options for the simulation.

  • tech_options (list) – List of available technology options for irrigation and farming.

  • area_split (int) – The number of splits or divisions within each field area.

  • aquifers_dict (dict) – Settings about the aquifers in the model, mapped by their IDs.

  • fields_dict (dict) – Settings about the fields in the model, mapped by their IDs.

  • wells_dict (dict) – Settings about the wells in the model, mapped by their IDs.

  • finances_dict (dict) – Settings about the finance in the model, mapped by their IDs.

  • behaviors_dict (dict) – Settings about the behaviors in the model, mapped by their IDs.

  • prec_aw_step (dict) –

    Time-series data for available precipitation.

    >>> prec_aw_step = {
    >>> "<prec_aw1>": {
    >>>     "<year>": {
    >>>         "<crop1>": "[cm]",
    >>>         "<crop2>": "[cm]",
    >>>         }
    >>>     }
    >>> }
    

  • init_year (int, optional) – The initial year of the simulation (a year before the start year).

  • end_year (int, optional) – The final year of the simulation.

  • lema_options (tuple, optional) – The option to turn on water rights for Local Enhanced Management Areas (LEMA). (bool: flag to indicate whether LEMA regulations are in effect, str: water right id, int: year LEMA begin). Default is (True, ‘wr_LEMA_5yr’, 2013).

  • fix_state (str, optional) – A fixed state for testing or specific scenarios.

  • lema (bool, optional) – Flag to indicate whether LEMA regulations are in effect.

  • show_step (bool, optional) – Flag to control the display of step information during simulation.

  • seed (int, optional) – Seed for random number generation for reproducibility.

  • **kwargs (dict) – Additional keyword arguments including time-step data like crop price, type, irrigation depth, etc. - ‘crop_price_step’: crop_price_step

schedule

The scheduler used to activate agents in the model.

Type:

BaseSchedulerByTypeFiltered

datacollector

Collects and stores data from agents and the model during the simulation.

Type:

mesa.DataCollector

(other attributes are initialized within the __init__ method)

Notes

The model is highly configurable with various parameters affecting the behavior of agents and their interactions within the simulated environment. It can be used to study the impacts of different agricultural practices and environmental policies.

step()

Advance the model by one step.

This method progresses the simulation by one year. It involves updating crop prices, deciding field types based on agent behavior, applying LEMA policy, and executing the step functions of all agents. Finally, it collects data and updates the model’s state.

The method controls the flow of the simulation, ensuring that each agent and component of the model acts according to the current time step and the state of the environment.

end()

Depose the Gurobi environment, ensuring that it is executed only when the instance is no longer needed.

get_datacollector_output()
static get_dfs(model)
static get_metrices(df_sys, data, targets=None, indicators_list=None)

Calculate various metrics based on system-level data and specified targets.

Parameters:
  • df_sys (pd.DataFrame) – The system-level dataframe.

  • data (dict or pd.DataFrame) – The reference or observed data for comparison.

  • targets (list) – List of targets or variables for which metrics are calculated.

  • indicators_list (list) – List of indicators to calculate, such as ‘r’, ‘rmse’, ‘KGE’.

Returns:

  • pd.DataFrame – A dataframe containing calculated metrics for each target.

  • This method is useful for evaluating the performance of the model against real-world data

  • or specific objectives, providing insights into the accuracy and reliability of the simulation.

Module contents

This is the model subpackage of PyCHAMP.