py_champ.components package
Submodules
py_champ.components.aquifer module
- class py_champ.components.aquifer.Aquifer(unique_id, model, settings: dict)
Bases:
AgentA class to represent the aquifer component in PyCHAMP based on the KGS-WBM model.
- Parameters:
unique_id (str or int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing the settings for the aquifer. Expected keys: ‘aq_a’, ‘aq_b’, ‘area’, ‘sy’, and ‘init’.
’aq_a’ and ‘aq_b’ are coefficients used in the static inflow calculation (inflow = None in step()).
’area’ is the area of the aquifer [ha]
’sy’ is the specific yield of the underlying aquifer and is used in the dynamic inflow calculation (inflow = float in step()) [-].
’init’ is a dictionary containing initial conditions such as the saturated thickness (st [m]) and initial water level change (dwl [m]).
>>> # A sample settings dictionary >>> settings = { >>> "aq_a": None, >>> "aq_b": None, >>> "area": None, >>> "sy": None, >>> "init": { >>> "st": None, >>> "dwl": None >>> } >>> }
Notes
The unit of water level is meters [m]. The area is expected in hectares [ha].
For more details on the KGS-WBM model, refer to:
Butler, J. J., Whittemore, D. O., Wilson, B. B., & Bohling, G. C. (2018). Sustainability of aquifers supporting irrigated agriculture: A case study of the High Plains aquifer in Kansas. Water International, 43(6), 815-828. https://doi.org/10.1080/02508060.2018.1515566
- load_settings(settings: dict)
Load settings for the aquifer simulation from a provided dictionary.
- Parameters:
settings (dict) – The dictionary containing the settings for the aquifer as defined above.
- step(withdrawal: float, inflow: float | None = None) float
Perform a single step of the aquifer simulation.
- Parameters:
- Returns:
The change in water level in the aquifer in this step [m].
- Return type:
Notes
The method calculates the change in water level either based on static inflow, using ‘aq_a’ and ‘aq_b’ coefficients or dynamic inflow, applying ‘sy’ and ‘area’ of the aquifer.
py_champ.components.behavior module
- class py_champ.components.behavior.Behavior(unique_id, model, settings: dict, pars: dict, fields: dict, wells: dict, finance, aquifers: dict, optimization_class: object, **kwargs)
Bases:
AgentThis module is a farmer’s behavior simulator.
- Parameters:
unique_id (int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing behavior-related settings, which includes assets, decision-making parameters, and gurobi settings.
’behavior_ids_in_network’: IDs of other behavior agents in the agent’s social network.
’field_ids’: IDs of fields managed by the agent.
’well_ids’: IDs of wells managed by the agent.
’finance_id’: ID of the finance agent associated with this behavior agent.
’decision_making’: Settings and parameters for the decision-making process.
’consumat’: Parameters related to the CONSUMAT model, including sensitivities and scales.
’water_rights’: Information about water rights, including depth [cm] and fields to which the constraint is applied.
’gurobi’: Settings for the Gurobi optimizer, such as logging and output controls.
>>> # A sample settings dictionary >>> settings = { >>> "field_ids": ["f1", "f2"], >>> "well_ids": ["w1"], >>> "finance_id": "finance", >>> "behavior_ids_in_network": ["behavior2", "behavior3"], >>> "decision_making": { >>> "target": "profit", >>> "horizon": 5, # [yr] >>> "n_dwl": 5, >>> "keep_gp_model": False, >>> "keep_gp_output": False, >>> "display_summary": False, >>> "display_report": False >>> }, >>> "water_rights": { >>> "<name>": { >>> "wr_depth": None, >>> "applied_field_ids": ["f1_"], # Will automatically update to "f1_" >>> "time_window": 1, >>> "remaining_tw": None, >>> "remaining_wr": None, >>> "tail_method": "proportion", # tail_method can be "proportion" or "all" or float >>> "status": True >>> } >>> }, >>> "consumat": { >>> "alpha": { # [0-1] Sensitivity factor for the "satisfaction" calculation. >>> "profit": 1, >>> "yield_rate": 1 >>> }, >>> "scale": { # Normalize "need" for "satisfaction" calculation. >>> "profit": 1000, >>> "yield_rate": 1 >>> }, >>> }, >>> "gurobi": { >>> "LogToConsole": 1, # 0: no console output; 1: with console output. >>> "Presolve": -1 # Options are Auto (-1; default), Aggressive (2), Conservative (1), Automatic (-1), or None (0). >>> } >>> }
pars (dict) –
Parameters defining satisfaction and uncertainty thresholds for CONSUMAT and the agent’s perception of risk and trust in forecasts. All four parameters are in the range 0 to 1.
>>> # A sample pars dictionary >>> settings = { >>> 'perceived_risk': 0.5, >>> 'forecast_trust': 0.5, >>> 'sa_thre': 0.5, >>> 'un_thre': 0.5 >>> }
fields (dict) – A dictionary of Field agents with their unique IDs as keys.
wells (dict) – A dictionary of Well agents with their unique IDs as keys.
finance (Finance) – A Finance agent instance associated with the behavior agent.
aquifers (dict) – A dictionary of Aquifer agents with their unique IDs as keys.
**kwargs – Additional keyword arguments that can be dynamically set as agent attributes.
Notes
This method also initializes various attributes related to the agent’s perception of risks, precipitation, profit, yield rate, and decision-making solutions. It calculates initial perceived risks and precipitation availability as well.
- load_settings(settings: dict)
Load the behavior settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings related to the behavior agent. Expected keys include ‘behavior_ids_in_network’, ‘field_ids’, ‘well_ids’, ‘finance_id’, ‘decision_making’, ‘consumat’, ‘water_rights’, and ‘gurobi’.
- process_percieved_risks(par_perceived_risk)
Compute perceived risks for each field and crop.
- Parameters:
par_perceived_risk (float) – The quantile used in an inverse cumulative distribution function.
Notes
This method calculates the perceived risks based on the truncated normal distribution parameters for each crop. The calculated values are stored in the percieved_risks attribute.
- update_perceived_prec_aw(par_forecast_confidence, year=None)
Update the perceived precipitation available water based on forecast trust.
- Parameters:
Notes
This method updates the perceived_prec_aw attribute based on the agent’s trust in the weather forecast and the perceived risks. It adjusts the available precipitation for each crop in each field accordingly.
- step()
Perform a single step of the behavior agent’s actions.
Notes
This method involves several key processes:
Updating agents in the agent’s social network.
Making decisions based on the current CONSUMAT state (Imitation, Social Comparison, Repetition, Deliberation).
Running simulations based on these decisions.
Updating various attributes like profit, yield rate, satisfaction, and uncertainty.
- run_simulation()
Run the simulation for the Behavior agent for one time step.
This method performs several key operations:
Simulates the fields based on decision-making solutions.
Simulates the wells for energy consumption.
Updates the financial status based on the field and well simulations.
Calculates satisfaction and uncertainty based on CONSUMAT theory.
Updates the CONSUMAT state of the agent.
Notes
The method uses the dm_sols attribute, which contains the decision-making solutions, to guide the simulation of fields and wells. It then updates various attributes of the agent, including profit, yield rate, satisfaction, uncertainty, and the CONSUMAT state.
- make_dm(state, dm_sols, neighbor=None, init=False)
Create and solve an optimization model for decision-making based on the agent’s current state.
- Parameters:
state (str or None) – The current CONSUMAT state of the agent, which influences the optimization process.
dm_sols (dict) – The previous decision-making solutions, used as inputs for the optimization model.
neighbor (dict, optional) – A neighboring agent object, used in states, ‘Imitation’ and “Social comparison”.
init (bool, optional) – A flag indicating if it is the initial setup of the optimization model.
- Returns:
Updated decision-making solutions after solving the optimization model.
- Return type:
Notes
This method sets up and solves an optimization model based on various inputs, including field data, well data, water rights, and financial considerations. The type of optimization and constraints applied depend on the agent’s current state, as defined by the CONSUMAT theory. The method returns updated decision-making solutions that guide the agent’s actions in subsequent steps.
- make_dm_deliberation()
Make decision under the “Deliberation” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Deliberation”.
- make_dm_repetition()
Make decision under the “Repetition” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Repetition”.
- make_dm_social_comparison()
Make decision under the “Social comparison” CONSUMAT state.
- Return type:
None
Notes
This method performs several key steps:
Evaluates comparable decision-making solutions from agents in the network.
Selects the agent with the best objective value.
Compares the agent’s original choice with the selected agent’s choice.
Updates the dm_sols attribute based on the comparison.
- make_dm_imitation()
Make decision under the “Imitation” CONSUMAT state.
- Return type:
None
Notes
This method performs the following key steps:
Selects an agent based on memory from previous social comparison from the network for imitation.
Updates the dm_sols attribute by calling the make_dm method with the current state set to “Imitation” and using the selected agent’s solutions.
- class py_champ.components.behavior.Behavior4SingleFieldAndWell(unique_id, model, settings: dict, pars: dict, fields: dict, wells: dict, finance, aquifers: dict, optimization_class: object, **kwargs)
Bases:
AgentSimulate a farmer’s behavior.
- load_settings(settings: dict)
Load the behavior settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings related to the behavior agent. Expected keys include ‘behavior_ids_in_network’, ‘field_ids’, ‘well_ids’, ‘finance_id’, ‘decision_making’, ‘consumat’, and ‘water_rights’.
- process_percieved_risks(par_perceived_risk)
Compute perceived risks for each field and crop.
- Parameters:
par_perceived_risk (float) – The quantile used in an inverse cumulative distribution function.
Notes
This method calculates the perceived risks based on the truncated normal distribution parameters for each crop. The calculated values are stored in the percieved_risks attribute.
- update_perceived_prec_aw(par_forecast_confidence, year=None)
Update the perceived precipitation available water based on forecast trust.
- Parameters:
Notes
This method updates the perceived_prec_aw attribute based on the agent’s trust in the weather forecast and the perceived risks. It adjusts the available precipitation for each crop in each field accordingly.
- step()
Perform a single step of the behavior agent’s actions.
Notes
This method involves several key processes:
Updating agents in the agent’s social network.
Making decisions based on the current CONSUMAT state (Imitation, Social Comparison, Repetition, Deliberation).
Running simulations based on these decisions.
Updating various attributes like profit, yield rate, satisfaction, and uncertainty.
- run_simulation()
Run the simulation for the Behavior agent for one time step.
This method performs several key operations:
Simulates the fields based on decision-making solutions.
Simulates the wells for energy consumption.
Updates the financial status based on the field and well simulations.
Calculates satisfaction and uncertainty based on CONSUMAT theory.
Updates the CONSUMAT state of the agent.
Notes
The method uses the dm_sols attribute, which contains the decision-making solutions, to guide the simulation of fields and wells. It then updates various attributes of the agent, including profit, yield rate, satisfaction, uncertainty, and the CONSUMAT state.
- make_dm(state, dm_sols, neighbor=None, init=False)
Create and solve an optimization model for decision-making based on the agent’s current state.
- Parameters:
state (str or None) – The current CONSUMAT state of the agent, which influences the optimization process.
dm_sols (dict) – The previous decision-making solutions, used as inputs for the optimization model.
neighbor (dict, optional) – A neighboring agent object, used in states, ‘Imitation’ and “Social comparison”.
init (bool, optional) – A flag indicating if it is the initial setup of the optimization model.
- Returns:
Updated decision-making solutions after solving the optimization model.
- Return type:
Notes
This method sets up and solves an optimization model based on various inputs, including field data, well data, water rights, and financial considerations. The type of optimization and constraints applied depend on the agent’s current state, as defined by the CONSUMAT theory. The method returns updated decision-making solutions that guide the agent’s actions in subsequent steps.
- make_dm_deliberation()
Make decision under the “Deliberation” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Deliberation”.
- make_dm_repetition()
Make decision under the “Repetition” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Repetition”.
- make_dm_social_comparison()
Make decision under the “Social comparison” CONSUMAT state.
- Return type:
None
Notes
This method performs several key steps:
Evaluates comparable decision-making solutions from agents in the network.
Selects the agent with the best objective value.
Compares the agent’s original choice with the selected agent’s choice.
Updates the dm_sols attribute based on the comparison.
- make_dm_imitation()
Make decision under the “Imitation” CONSUMAT state.
- Return type:
None
Notes
This method performs the following key steps:
Selects an agent based on memory from previous social comparison from the network for imitation.
Updates the dm_sols attribute by calling the make_dm method with the current state set to “Imitation” and using the selected agent’s solutions.
- class py_champ.components.behavior.Behavior4SingleFieldAndWell_simCJ(unique_id, model, settings: dict, pars: dict, fields: dict, wells: dict, finance, aquifers: dict, optimization_class: object, **kwargs)
Bases:
AgentSimulate a farmer’s behavior.
- load_settings(settings: dict)
Load the behavior settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings related to the behavior agent. Expected keys include ‘behavior_ids_in_network’, ‘field_ids’, ‘well_ids’, ‘finance_id’, ‘decision_making’, ‘consumat’, and ‘water_rights’.
- process_percieved_risks(par_perceived_risk)
Compute perceived risks for each field and crop.
- Parameters:
par_perceived_risk (float) – The quantile used in an inverse cumulative distribution function.
Notes
This method calculates the perceived risks based on the truncated normal distribution parameters for each crop. The calculated values are stored in the percieved_risks attribute.
- update_perceived_prec_aw(par_forecast_confidence, year=None)
Update the perceived precipitation available water based on forecast trust.
- Parameters:
Notes
This method updates the perceived_prec_aw attribute based on the agent’s trust in the weather forecast and the perceived risks. It adjusts the available precipitation for each crop in each field accordingly.
- step()
Perform a single step of the behavior agent’s actions.
Notes
This method involves several key processes:
Updating agents in the agent’s social network.
Making decisions based on the current CONSUMAT state (Imitation, Social Comparison, Repetition, Deliberation).
Running simulations based on these decisions.
Updating various attributes like profit, yield rate, satisfaction, and uncertainty.
- run_simulation()
Run the simulation for the Behavior agent for one time step.
This method performs several key operations:
Simulates the fields based on decision-making solutions.
Simulates the wells for energy consumption.
Updates the financial status based on the field and well simulations.
Calculates satisfaction and uncertainty based on CONSUMAT theory.
Updates the CONSUMAT state of the agent.
Notes
The method uses the dm_sols attribute, which contains the decision-making solutions, to guide the simulation of fields and wells. It then updates various attributes of the agent, including profit, yield rate, satisfaction, uncertainty, and the CONSUMAT state.
- make_dm(state, dm_sols, neighbor=None, init=False)
Create and solve an optimization model for decision-making based on the agent’s current state.
- Parameters:
state (str or None) – The current CONSUMAT state of the agent, which influences the optimization process.
dm_sols (dict) – The previous decision-making solutions, used as inputs for the optimization model.
neighbor (dict, optional) – A neighboring agent object, used in states, ‘Imitation’ and “Social comparison”.
init (bool, optional) – A flag indicating if it is the initial setup of the optimization model.
- Returns:
Updated decision-making solutions after solving the optimization model.
- Return type:
Notes
This method sets up and solves an optimization model based on various inputs, including field data, well data, water rights, and financial considerations. The type of optimization and constraints applied depend on the agent’s current state, as defined by the CONSUMAT theory. The method returns updated decision-making solutions that guide the agent’s actions in subsequent steps.
- make_dm_deliberation()
Make decision under the “Deliberation” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Deliberation”.
- make_dm_repetition()
Make decision under the “Repetition” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Repetition”.
- make_dm_social_comparison()
Make decision under the “Social comparison” CONSUMAT state.
- Return type:
None
Notes
This method performs several key steps:
Evaluates comparable decision-making solutions from agents in the network.
Selects the agent with the best objective value.
Compares the agent’s original choice with the selected agent’s choice.
Updates the dm_sols attribute based on the comparison.
- make_dm_imitation()
Make decision under the “Imitation” CONSUMAT state.
- Return type:
None
Notes
This method performs the following key steps:
Selects an agent based on memory from previous social comparison from the network for imitation.
Updates the dm_sols attribute by calling the make_dm method with the current state set to “Imitation” and using the selected agent’s solutions.
- class py_champ.components.behavior.Behavior4SingleFieldAndWell_ogCJ(unique_id, model, settings: dict, pars: dict, fields: dict, wells: dict, finance, aquifers: dict, optimization_class: object, **kwargs)
Bases:
AgentSimulate a farmer’s behavior.
- load_settings(settings: dict)
Load the behavior settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings related to the behavior agent. Expected keys include ‘behavior_ids_in_network’, ‘field_ids’, ‘well_ids’, ‘finance_id’, ‘decision_making’, ‘consumat’, and ‘water_rights’.
- process_percieved_risks(par_perceived_risk)
Compute perceived risks for each field and crop.
- Parameters:
par_perceived_risk (float) – The quantile used in an inverse cumulative distribution function.
Notes
This method calculates the perceived risks based on the truncated normal distribution parameters for each crop. The calculated values are stored in the percieved_risks attribute.
- update_perceived_prec_aw(par_forecast_confidence, year=None)
Update the perceived precipitation available water based on forecast trust.
- Parameters:
Notes
This method updates the perceived_prec_aw attribute based on the agent’s trust in the weather forecast and the perceived risks. It adjusts the available precipitation for each crop in each field accordingly.
- step()
Perform a single step of the behavior agent’s actions.
Notes
This method involves several key processes:
Updating agents in the agent’s social network.
Making decisions based on the current CONSUMAT state (Imitation, Social Comparison, Repetition, Deliberation).
Running simulations based on these decisions.
Updating various attributes like profit, yield rate, satisfaction, and uncertainty.
- run_simulation()
Run the simulation for the Behavior agent for one time step.
This method performs several key operations:
Simulates the fields based on decision-making solutions.
Simulates the wells for energy consumption.
Updates the financial status based on the field and well simulations.
Calculates satisfaction and uncertainty based on CONSUMAT theory.
Updates the CONSUMAT state of the agent.
Notes
The method uses the dm_sols attribute, which contains the decision-making solutions, to guide the simulation of fields and wells. It then updates various attributes of the agent, including profit, yield rate, satisfaction, uncertainty, and the CONSUMAT state.
- make_dm(state, dm_sols, neighbor=None, init=False)
Create and solve an optimization model for decision-making based on the agent’s current state.
- Parameters:
state (str or None) – The current CONSUMAT state of the agent, which influences the optimization process.
dm_sols (dict) – The previous decision-making solutions, used as inputs for the optimization model.
neighbor (dict, optional) – A neighboring agent object, used in states, ‘Imitation’ and “Social comparison”.
init (bool, optional) – A flag indicating if it is the initial setup of the optimization model.
- Returns:
Updated decision-making solutions after solving the optimization model.
- Return type:
Notes
This method sets up and solves an optimization model based on various inputs, including field data, well data, water rights, and financial considerations. The type of optimization and constraints applied depend on the agent’s current state, as defined by the CONSUMAT theory. The method returns updated decision-making solutions that guide the agent’s actions in subsequent steps.
- make_dm_deliberation()
Make decision under the “Deliberation” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Deliberation”.
- make_dm_repetition()
Make decision under the “Repetition” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Repetition”.
- make_dm_social_comparison()
Make decision under the “Social comparison” CONSUMAT state.
- Return type:
None
Notes
This method performs several key steps:
Evaluates comparable decision-making solutions from agents in the network.
Selects the agent with the best objective value.
Compares the agent’s original choice with the selected agent’s choice.
Updates the dm_sols attribute based on the comparison.
- make_dm_imitation()
Make decision under the “Imitation” CONSUMAT state.
- Return type:
None
Notes
This method performs the following key steps:
Selects an agent based on memory from previous social comparison from the network for imitation.
Updates the dm_sols attribute by calling the make_dm method with the current state set to “Imitation” and using the selected agent’s solutions.
- class py_champ.components.behavior.Behavior_1f1w_ci(unique_id, model, settings: dict, pars: dict, fields: dict, wells: dict, finance, aquifers: dict, Optimization: object, **kwargs)
Bases:
AgentThis module is a farmer’s behavior simulator.
- Parameters:
unique_id (int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing behavior-related settings, which includes assets, decision-making parameters, and gurobi settings.
’behavior_ids_in_network’: IDs of other behavior agents in the agent’s social network.
’field_ids’: IDs of fields managed by the agent.
’well_ids’: IDs of wells managed by the agent.
’finance_id’: ID of the finance agent associated with this behavior agent.
’decision_making’: Settings and parameters for the decision-making process.
’consumat’: Parameters related to the CONSUMAT model, including sensitivities and scales.
’water_rights’: Information about water rights, including depth [cm] and fields to which the constraint is applied.
’gurobi’: Settings for the Gurobi optimizer, such as logging and output controls.
>>> # A sample settings dictionary >>> settings = { >>> "field_ids": ["f1", "f2"], >>> "well_ids": ["w1"], >>> "finance_id": "finance", >>> "behavior_ids_in_network": ["behavior2", "behavior3"], >>> "decision_making": { >>> "target": "profit", >>> "horizon": 5, # [yr] >>> "n_dwl": 5, >>> "keep_gp_model": False, >>> "keep_gp_output": False, >>> "display_summary": False, >>> "display_report": False >>> }, >>> "water_rights": { >>> "<name>": { >>> "wr_depth": None, >>> "applied_field_ids": ["f1_"], # Will automatically update to "f1_" >>> "time_window": 1, >>> "remaining_tw": None, >>> "remaining_wr": None, >>> "tail_method": "proportion", # tail_method can be "proportion" or "all" or float >>> "status": True >>> } >>> }, >>> "consumat": { >>> "alpha": { # [0-1] Sensitivity factor for the "satisfaction" calculation. >>> "profit": 1, >>> "yield_rate": 1 >>> }, >>> "scale": { # Normalize "need" for "satisfaction" calculation. >>> "profit": 1000, >>> "yield_rate": 1 >>> }, >>> }, >>> "gurobi": { >>> "LogToConsole": 1, # 0: no console output; 1: with console output. >>> "Presolve": -1 # Options are Auto (-1; default), Aggressive (2), Conservative (1), Automatic (-1), or None (0). >>> } >>> }
pars (dict) –
Parameters defining satisfaction and uncertainty thresholds for CONSUMAT and the agent’s perception of risk and trust in forecasts. All four parameters are in the range 0 to 1.
>>> # A sample pars dictionary >>> settings = { >>> 'perceived_risk': 0.5, >>> 'forecast_trust': 0.5, >>> 'sa_thre': 0.5, >>> 'un_thre': 0.5 >>> }
fields (dict) – A dictionary of Field agents with their unique IDs as keys.
wells (dict) – A dictionary of Well agents with their unique IDs as keys.
finance (Finance) – A Finance agent instance associated with the behavior agent.
aquifers (dict) – A dictionary of Aquifer agents with their unique IDs as keys.
**kwargs – Additional keyword arguments that can be dynamically set as agent attributes.
Notes
This method also initializes various attributes related to the agent’s perception of risks, precipitation, profit, yield rate, and decision-making solutions. It calculates initial perceived risks and precipitation availability as well.
- load_settings(settings: dict)
Load the behavior settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings related to the behavior agent. Expected keys include ‘behavior_ids_in_network’, ‘field_ids’, ‘well_ids’, ‘finance_id’, ‘decision_making’, ‘consumat’, ‘water_rights’, and ‘gurobi’.
- process_percieved_risks(par_perceived_risk)
Compute perceived risks for each field and crop.
- Parameters:
par_perceived_risk (float) – The quantile used in an inverse cumulative distribution function.
Notes
This method calculates the perceived risks based on the truncated normal distribution parameters for each crop. The calculated values are stored in the percieved_risks attribute.
- update_perceived_prec_aw(par_forecast_confidence, year=None)
Update the perceived precipitation available water based on forecast trust.
- Parameters:
Notes
This method updates the perceived_prec_aw attribute based on the agent’s trust in the weather forecast and the perceived risks. It adjusts the available precipitation for each crop in each field accordingly.
- step()
Perform a single step of the behavior agent’s actions.
Notes
This method involves several key processes:
Updating agents in the agent’s social network.
Making decisions based on the current CONSUMAT state (Imitation, Social Comparison, Repetition, Deliberation).
Running simulations based on these decisions.
Updating various attributes like profit, yield rate, satisfaction, and uncertainty.
- run_simulation()
Run the simulation for the Behavior agent for one time step.
This method performs several key operations:
Simulates the fields based on decision-making solutions.
Simulates the wells for energy consumption.
Updates the financial status based on the field and well simulations.
Calculates satisfaction and uncertainty based on CONSUMAT theory.
Updates the CONSUMAT state of the agent.
Notes
The method uses the dm_sols attribute, which contains the decision-making solutions, to guide the simulation of fields and wells. It then updates various attributes of the agent, including profit, yield rate, satisfaction, uncertainty, and the CONSUMAT state.
- make_dm(state, dm_sols, neighbor=None, init=False)
Create and solve an optimization model for decision-making based on the agent’s current state.
- Parameters:
state (str or None) – The current CONSUMAT state of the agent, which influences the optimization process.
dm_sols (dict) – The previous decision-making solutions, used as inputs for the optimization model.
neighbor (dict, optional) – A neighboring agent object, used in states, ‘Imitation’ and “Social comparison”.
init (bool, optional) – A flag indicating if it is the initial setup of the optimization model.
- Returns:
Updated decision-making solutions after solving the optimization model.
- Return type:
Notes
This method sets up and solves an optimization model based on various inputs, including field data, well data, water rights, and financial considerations. The type of optimization and constraints applied depend on the agent’s current state, as defined by the CONSUMAT theory. The method returns updated decision-making solutions that guide the agent’s actions in subsequent steps.
- make_dm_deliberation()
Make decision under the “Deliberation” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Deliberation”.
- make_dm_repetition()
Make decision under the “Repetition” CONSUMAT state.
- Return type:
None
Notes
This method updates the dm_sols attribute by calling the make_dm method with the current state set to “Repetition”.
- make_dm_social_comparison()
Make decision under the “Social comparison” CONSUMAT state.
- Return type:
None
Notes
This method performs several key steps:
Evaluates comparable decision-making solutions from agents in the network.
Selects the agent with the best objective value.
Compares the agent’s original choice with the selected agent’s choice.
Updates the dm_sols attribute based on the comparison.
- make_dm_imitation()
Make decision under the “Imitation” CONSUMAT state.
- Return type:
None
Notes
This method performs the following key steps:
Selects an agent based on memory from previous social comparison from the network for imitation.
Updates the dm_sols attribute by calling the make_dm method with the current state set to “Imitation” and using the selected agent’s solutions.
py_champ.components.field module
- class py_champ.components.field.Field(unique_id, model, settings: dict, **kwargs)
Bases:
AgentThis module is a field simulator.
- Parameters:
unique_id (int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing initial settings for the field, which include field area, water yield curves, technology pumping rate coefficients, climate data id, and initial conditions.
’field_area’: The total area of the field [ha].
’water_yield_curves’: Water yield response curves for different crops.
’tech_pumping_rate_coefs’: Coefficients for calculating pumping rates based on irrigation technology. Pumping rate [m-ha/day] = a * annual withdrawal [m-ha] + b
’prec_aw_id’: Identifier for available precipitation data.
’init’: Initial conditions: irrigation technology, crop type, and field type.
>>> # A sample settings dictionary >>> settings = { >>> "field_area": 50., >>> "water_yield_curves": { >>> "corn": [ymax [bu], wmax [cm], a, b, c, min_yield_ratio]}, # Replace variables with actual values >>> "tech_pumping_rate_coefs": { >>> "center pivot LEPA": [a, b, l_pr [m]]}, # Replace variables with actual values >>> "prec_aw_id": None, >>> "init":{ >>> "tech": None, >>> "crop": None, >>> "field_type": None, # "optimize" or "irrigated" or "rainfed" >>> }, >>> }
**kwargs – Additional keyword arguments that can be dynamically set as field agent attributes.
Notes
The yield is measured in bushels [1e4 bu].
The irrigation volume is measured in meter-hectares [m-ha].
Field area should be provided in hectares [ha].
- load_settings(settings: dict)
Load the field settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings for the field, including field area, water yield curves for crops, and technological coefficients.
- update_irr_tech(i_te)
Update the irrigation technology used in the field based on given indicator array. The dimension of the array should be (n_te).
- Parameters:
i_te (1d array or str) – Indicator array or string representing the chosen irrigation technology for the next year. The dimension of the array should be (n_te).
- Return type:
None
- update_crops(i_crop)
Update the crop types for each area split based on the given indicator array. The dimension of the array should be (n_s, n_c, 1).
- Parameters:
i_crop (3d array) – Indicator array representing the chosen crops for the next year for each area split. The dimension of the array should be (n_s, n_c, 1).
- Return type:
None
- step(irr_depth, i_crop, i_te, prec_aw: dict) tuple
Perform a single step of field operation, calculating yields and irrigation volumes.
- Parameters:
irr_depth (3d array) – The depth of irrigation applied [cm]. Dimensions: (n_s, n_c, 1)
i_crop (3d array) – Indicator array representing the chosen crops for each area split. Dimensions: (n_s, n_c, 1).
i_te (1d array or str) – Indicator array or string representing the chosen irrigation technology. Dimensions: (n_te).
prec_aw (dict) – A dictionary of available precipitation for each crop. {“corn”: 27.02, “sorghum”: 22.81}
- Returns:
A tuple containing yield [1e4 bu], average yield rate [-], and total irrigation volume [m-ha].
- Return type:
Notes
This method calculates the yield based on the applied irrigation, chosen crops, install technology, and available precipitation.
- class py_champ.components.field.Field4SingleFieldAndWell(unique_id, model, settings: dict, **kwargs)
Bases:
AgentSimulate a field agent in the model.
- load_settings(settings: dict)
Load the field settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings for the field, including field area, water yield curves for crops, and technological coefficients.
- update_crops(i_crop)
Update the crop types for each area split based on the given indicator array. The dimension of the array should be (n_c, 1).
- Parameters:
i_crop (2d array) – Indicator array representing the chosen crops for the next year. The dimension of the array should be (n_c, 1).
- Return type:
None
- step(irr_depth, i_crop, prec_aw: dict) tuple
Perform a single step of field operation, calculating yields and irrigation volumes.
- Parameters:
irr_depth (3d array) – The depth of irrigation applied [cm]. Dimensions: (n_s, n_c, 1)
i_crop (3d array) – Indicator array representing the chosen crops for each area split. Dimensions: (n_s, n_c, 1).
prec_aw (dict) – A dictionary of available precipitation for each crop. {“corn”: 27.02, “sorghum”: 22.81}
- Returns:
A tuple containing yield [1e4 bu], average yield rate [-], and total irrigation volume [m-ha].
- Return type:
Notes
This method calculates the yield based on the applied irrigation, chosen crops, install technology, and available precipitation.
- class py_champ.components.field.Field_1f1w_ci(unique_id, model, settings: dict, **kwargs)
Bases:
AgentSimulate a field agent in the model.
- load_settings(settings: dict)
Load the field settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing settings for the field, including field area, water yield curves for crops, and technological coefficients.
- update_crops(i_crop)
Update the crop types for each area split based on the given indicator array. The dimension of the array should be (n_c, 1).
- Parameters:
i_crop (2d array) – Indicator array representing the chosen crops for the next year. The dimension of the array should be (n_c, 1).
- Return type:
None
- update_aph_yield(field_type, crop_yield)
Update the aph_yield_records & aph_yield_dict for crop insurance.
Should be triggered after the yield calculation and premium calculation in the finance after everthing is done.
- step(irr_depth, i_crop, prec_aw: dict) tuple
Perform a single step of field operation, calculating yields and irrigation volumes.
- Parameters:
irr_depth (3d array) – The depth of irrigation applied [cm]. Dimensions: (n_s, n_c, 1)
i_crop (3d array) – Indicator array representing the chosen crops for each area split. Dimensions: (n_s, n_c, 1).
prec_aw (dict) – A dictionary of available precipitation for each crop. {“corn”: 27.02, “sorghum”: 22.81}
- Returns:
A tuple containing yield [1e4 bu], average yield rate [-], and total irrigation volume [m-ha].
- Return type:
Notes
This method calculates the yield based on the applied irrigation, chosen crops, install technology, and available precipitation.
py_champ.components.finance module
- class py_champ.components.finance.Finance(unique_id, model, settings: dict)
Bases:
AgentThis module is a finance simulator.
- Parameters:
unique_id (int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing financial settings, which include energy prices, crop price, and crop cost, irrigation operational cost, irr_tech_change_cost, and crop_change_cost.
’energy_price’: The price of energy [1e4 $/PJ].
’crop_price’ and ‘crop_cost’: The price and cost of different crops [$/bu].
’irr_tech_operational_cost’: Operational costs for different irrigation technologies [1e4 $].
’irr_tech_change_cost’: Costs associated with changing irrigation technologies [1e4 $].
’crop_change_cost’: Costs associated with changing crop types [1e4 $].
>>> # A sample settings dictionary >>> settings = { >>> "energy_price": 2777.78, >>> "crop_price": { >>> "corn": 5.39, >>> "sorghum": 6.59, >>> "soybeans": 13.31, >>> "wheat": 8.28, >>> "fallow": 0. >>> }, >>> "crop_cost": { >>> "corn": 0, >>> "sorghum": 0, >>> "soybeans": 0, >>> "wheat": 0, >>> "fallow": 0. >>> }, >>> "irr_tech_operational_cost": { >>> "center pivot": 1.87, >>> "center pivot LEPA": 1.87 >>> }, >>> "irr_tech_change_cost": { # If not specified, 0 is the default. >>> ("center pivot", "center pivot LEPA"): 0 >>> }, >>> "crop_change_cost": { # If not specified, 0 is the default. >>> ("corn", "sorghum"): 0 >>> } >>> }
- load_settings(settings: dict)
Load the financial settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing financial settings. Expected keys include ‘energy_price’, ‘crop_price’, ‘crop_cost’, ‘irr_tech_operational_cost’, ‘irr_tech_change_cost’, and ‘crop_change_cost’.
- step(fields: dict, wells: dict) float
Perform a single step of financial calculations.
- Parameters:
- Returns:
The profit calculated for this step [1e4 $].
- Return type:
Notes
This method calculates the total yield, energy usage, operational costs, technology change costs, crop change costs, energy costs, and the total profit. The profit is calculated as revenue minus all associated costs.
- class py_champ.components.finance.Finance4SingleFieldAndWell(unique_id, model, settings: dict)
Bases:
AgentSimulate the financial aspect of the model.
- load_settings(settings: dict)
Load the financial settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing financial settings. Expected keys include ‘energy_price’, ‘crop_price’, ‘crop_cost’, ‘irr_tech_operational_cost’, ‘irr_tech_change_cost’, and ‘crop_change_cost’.
- step(fields: dict, wells: dict) float
Perform a single step of financial calculations.
- Parameters:
- Returns:
The profit calculated for this step [1e4 $].
- Return type:
Notes
This method calculates the total yield, energy usage, operational costs, technology change costs, crop change costs, energy costs, and the total profit. The profit is calculated as revenue minus all associated costs.
- class py_champ.components.finance.Finance_1f1w_ci(unique_id, model, settings: dict)
Bases:
AgentThis module is a finance simulator.
- Parameters:
unique_id (int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing financial settings, which include energy prices, crop price, and crop cost, irrigation operational cost, irr_tech_change_cost, and crop_change_cost.
’energy_price’: The price of energy [1e4 $/PJ].
’crop_price’ and ‘crop_cost’: The price and cost of different crops [$/bu].
’irr_tech_operational_cost’: Operational costs for different irrigation technologies [1e4 $].
’irr_tech_change_cost’: Costs associated with changing irrigation technologies [1e4 $].
’crop_change_cost’: Costs associated with changing crop types [1e4 $].
>>> # A sample settings dictionary >>> settings = { >>> "energy_price": 2777.78, >>> "crop_price": { >>> "corn": 5.39, >>> "sorghum": 6.59, >>> "soybeans": 13.31, >>> "wheat": 8.28, >>> "fallow": 0. >>> }, >>> "crop_cost": { >>> "corn": 0, >>> "sorghum": 0, >>> "soybeans": 0, >>> "wheat": 0, >>> "fallow": 0. >>> }, >>> "irr_tech_operational_cost": { >>> "center pivot": 1.87, >>> "center pivot LEPA": 1.87 >>> }, >>> "irr_tech_change_cost": { # If not specified, 0 is the default. >>> ("center pivot", "center pivot LEPA"): 0 >>> }, >>> "crop_change_cost": { # If not specified, 0 is the default. >>> ("corn", "sorghum"): 0 >>> } >>> }
- load_settings(settings: dict)
Load the financial settings from a dictionary.
- Parameters:
settings (dict) – A dictionary containing financial settings. Expected keys include ‘energy_price’, ‘crop_price’, ‘crop_cost’, ‘irr_tech_operational_cost’, ‘irr_tech_change_cost’, and ‘crop_change_cost’.
Calculate the premium for a given crop, county, and field type.
- Parameters:
df (pd.DataFrame) – The dataframe containing the crop insurance data.
crop (str) – The crop type.
county (str) – The county name.
field_type (str) – The field type.
aph_yield_dict (dict) – A dictionary of aph yield for each crop.
projected_price (float) – The projected price.
premium_ratio (float, optional) – The premium ratio, by default 1.
coverage_level (float, optional) – The coverage level, by default 0.75.
- Returns:
The premium calculated for this step [1e4 $].
- Return type:
- cal_APH_revenue_based_payout(harvest_price, projected_price, aph_yield, yield_, coverage_level=0.75)
- step(fields: dict, wells: dict) float
Perform a single step of financial calculations.
- Parameters:
- Returns:
The profit calculated for this step [1e4 $].
- Return type:
Notes
This method calculates the total yield, energy usage, operational costs, technology change costs, crop change costs, energy costs, and the total profit. The profit is calculated as revenue minus all associated costs.
py_champ.components.optimization module
- class py_champ.components.optimization.Optimization(unique_id='', log_to_console=1, gpenv=None)
Bases:
objectThis class represents a farmer making decisions on irrigation depth, crop types, the type of field: rainfed or irrigated, and irrigation technologies. The farmer’s objective is to solve a nonlinear mixed integer optimization model that maximizes their satisfaction, which can be measured by metrics like profit or yield percentage. The optimization problem is formulated on an annual scale. Optional decision variables include crop types, rainfed option for the field, and irrigation technologies, which can be provided as inputs to the class.
Specifically, this class is designed to accommodate a farmer with multiple crop fields and groundwater wells. Each field can have multiple area splits, where each split can have its own set of decision variables. Water rights can be incorporated as constraints for all fields or a selected subset of fields with an optional time_window argument, allowing the farmer to allocate their water rights across multiple years. To enforce water rights at the point of diversion, pumping capacity can be assigned to an individual well.
If the ‘horizon’ parameter is set to a value greater than 1, only the irrigation depth is varied each year. Other decision variables such as the crop types, rainfed option, and irrigation technologies remain fixed over the planning horizon. If necessary, the user has the flexibility to rerun the optimization model in the subsequent years to update the decision based on any changes or new information.
This class provides an option to approximate the solving process by setting the “approx_horizon” parameter to True. This approximation assumes a linear decrement in water levels and helps speed up the solving process. However, it’s important to note that if there is a water right constraint with a time_window argument greater than 1, the approximation option is restricted and cannot be used. This ensures accurate handling of water right constraints over multiple time periods.
Notations
n_s: Number of the splits in a field.
n_c: Number of the crop choices.
n_h: Planning horizon or approximated horizon.
n_te: Number of the irrigation technology choices.
Notes
This class utilizes the Gurobi solver to solve the optimization problem. Gurobi is a commercial solver, but it also offers a full-featured solver for academic use at no cost. Users interested in running the code will need to register for an academic license and download the solver. Additionally, they need to install the gurobipy Python package to interface with Gurobi and execute the code successfully.
More information can be found here: https://www.gurobi.com/academia/academic-program-and-licenses/
- depose_gp_env()
Depose the Gurobi environment, ensuring that it is executed only when the instance is no longer needed. It’s important to note that once this method is invoked, a new optimization model (setup_ini_model) cannot be created anymore.
- Return type:
None.
- setup_ini_model(target='profit', horizon=1, area_split=1, crop_options=None, tech_options=None, consumat_dict=None, approx_horizon=False, gurobi_kwargs=None)
Set up the initial settings for an optimization model. The new optimization model will be created within the same Gurobi environment that was initialized when the class instance was created.
- Parameters:
target (str, optional) – The target variable (“profit” or “yield_rate”) for optimization, which can be provided as an input in the decision making dictionary under behavior dictionary. The default is “profit”.
horizon (str, optional) – The planing horizon [yr]. The default is 1 year.
area_split (str, optional) – The number of splits for each field that a farmer agent owns. The default is 1.
crop_options (list, optional) – A list of crop type options available, which can be fed as an input to the model. The default is [“corn”, “sorghum”, “soybeans”, “fallow”].
tech_options (list, optional) – A list of irrigation technologies available. Users have the choice of inputting the list to the model. The default is [“center pivot”, “center pivot LEPA”].
consumat_dict (dict, optional) –
A dictionary containing parameters related to the CONSUMAT model, including sensitivities and scales. The default is
>>> consumat_dict = { >>> "alpha": { >>> "profit": 1, >>> "yield_rate": 1 >>> }, >>> "scale": { >>> "profit": 0.23 * 50, >>> "yield_rate": 1 >>> }, >>> }
approx_horizon (bool, optional) – When set to True, the model will calculate two points (start and end) over the given horizon to determine the objective, which is the average over the horizon. This approach can significantly enhance the solving speed, particularly for long horizons. In most cases, this approximation is equivalent to solving the original problem. It relies on the assumption that the groundwater level will linearly decrease in the projected future. However, it is important to note that if there is a water right constraint with a time_window argument larger than 1, the approximation option is restricted and cannot be used. This ensures accurate handling of water right constraints over multiple time periods. The default is False.
gurobi_kwargs – The gurobi keywords. These will be fed to the solver in solve().
- Return type:
None.
- setup_constr_field(field_id, field_area, prec_aw, water_yield_curves, tech_pumping_rate_coefs, pre_i_crop, pre_i_te, field_type='optimize', i_crop=None, i_rainfed=None, i_te=None, **kwargs)
This method adds constraints for a field. You can assign multiple fields by calling this function repeatedly with different field_id. If i_crop, i_rainfed, and i_te is provided, the model will not optimize different crop type options, field type: rainfed or irrigated, and irrigation technologies, respectively.
- Parameters:
field_id (str or int) – The field id serves as a means to differentiate the equation sets for different fields.
field_area (str or int) – The field area associated with the corresponding field_id.
prec_aw (dict) – Perceived precipitation for each crop’s growing season [cm].
curves (water yield) – A dictionary containing water-yield response curves for different crop types. This has to be given as an input under settings dictionary for a field.
tech_pumping_rate_coefs (dict) – A dictionary containing coefficients for calculating pumping rates based on selected irrigation technology. Pumping rate [m-ha/day] = a * annual withdrawal [m-ha] + b
pre_i_crop (str or 3darray) – Crop name or the i_crop from the previous time step.
pre_i_te (str or 3darray) – Irrigation technology or i_te from the previous time step.
field_type (str or list, optional) – Field type can be “rainfed”, “irrigated”, or “optimize”. A list can be given to define field type for each area split. The default value is “optimize”.
i_crop (3darray, optional) – The crop type for the current time step. The indicator matrix has a dimension of (n_s, n_c, 1). In this matrix, a value of 1 indicates that the corresponding crop type is selected or chosen for the corresponding split. The default is None.
i_rainfed (3darray, optional) – The field type (irrigated or rainfed) for the current time step. The indicator matrix has a dimension of (n_s, n_c, 1). In this matrix, a value of 1 indicates that the unit area in the field is rainfed. Given i_rainfed will force field_type to be “rainfed”; otherwise, the field will be considered to be irrigated. Also, if the i_rainfed is given, make sure 1 exists only where i_crop is also 1. The default is None.
i_te (1darray or str, optional) – The irrigation technology chosen for the current time step. The indicator matrix has a dimension of n_te. A value of 1 indicates that the corresponding irrigation technology is selected. The default is None.
**kwargs – Additional keyword arguments that can be dynamically set as a field parameter.
- Return type:
None.
- setup_constr_well(well_id, dwl, st, l_wt, r, k, sy, eff_pump, eff_well, pumping_days, pumping_capacity=None, rho=1000.0, g=9.8016)
Set up well constraints for the optimization model. You can assign multiple wells by calling this function repeatedly with different well_id.
- Parameters:
well_id (str or int) – The well id serves as a means to differentiate the equation sets for different wells.
dwl (float) – Percieved annual water level change rate [m/yr].
st (float) – Aquifer saturated thickness at the initial time step [m]. Given as an input in the init dicitonary of well settings.
l_wt (float) – The head required to lift water from the water table to the ground surface at the start of the pumping season at the initial time step [m]. Given as an input in the init dicitonary of well settings.
r (float) – Well radius [m]. Given as an input in the well settings.
k (float) – Hydraulic conductivity [m/day]. This will be used to calculate transmissivity [m²/day] by multipling k with the saturated thickness [m]. Given as an input in the well settings.
sy (float) – Specific yield of the aquifer [-]. Given as an input in the well settings.
eff_pump (float) – Pump efficiency as a fraction [-]. Given as an input in the well settings.
eff_well (float) – Well efficiency as a fraction [-]. Given as an input in the well settings.
pumping_days (int) – Number of days the well is operational [day]. Given as an input in the init dictionary of the well settings.
pumping_capacity (float) – Maximum pumping capacity of the well [m-ha/yr]. The default is None. Given as an input in the well settings.
rho (float) – density of water [kg/m3].
g (float) – acceleration due to gravity [m/s²].
- Return type:
None.
- setup_constr_finance(finance_dict)
Set up financial constraints for the optimization model. The output is in 1e4 $.
- Parameters:
finance_dict (dict) – A dictionary containing financial settings, which include energy price, crop price, and crop cost, irrigation operational cost, irr_tech_change_cost, and crop_change_cost. For more detail, refer to the finance module.
- Return type:
None.
- setup_constr_wr(water_right_id, wr_depth, applied_field_ids='all', time_window=1, remaining_tw=None, remaining_wr=None, tail_method='proportion')
Set up water right constraints for the optimization model. You can assign multiple water rights constraints by calling this function repeatedly with different water_right_id. Water rights can constrain all fields or a selected subset of fields with an optional time_window argument, allowing the farmer to allocate their water rights across multiple years. To enforce water rights at the point of diversion, pumping capacity can be assigned to individual wells in setup_constr_well() method.
- Parameters:
water_right_id (str or int) – The water right id serves as a means to differentiate the equation sets for different water rights.
wr_depth (float) – Depth of the water right [cm].
applied_field_ids ("all" or list, optional) – A list of field ids. If given, the water right constraints apply only to the subset of the fields. Note that water rights are applied to constrain the average irrigation depth (cm) over fields. If you want to add the same water rights setting for all individual fields, you can call setup_constr_wr() for all the fields that the farmer owns. The default is “all”.
time_window (int, optional) – If given, the water right constrains the total irrigation depth over the time window [yr]. The default is 1.
remaining_tw (int, optional) – Remaining years of time window that the remaining_wr will be applied to [yr]. The default is None.
remaining_wr (float, optional) – The remaining water rights left unused from the previous time window [cm]. The default is None.
tail_method ("proportion" or "all" or float, optional) –
Method to allocate water rights to the incomplete part of the time window at the end of the planning period.
”proportion” means water equivalent to wr_depth*(tail length/time_window) is applied to the tail part of the planning period.
”all” means water equivalent to wr_depth is applied to the tail part of planning period.
If a float is given, the given value will be applied directly to the tail part of planning period.
The default is “proportion”.
- Return type:
None.
- setup_obj(alpha_dict=None)
This method sets the objective of the optimization model, i.e., to maximize the agent’s expected satisfaction. Note that the satisfaction value is calculated after the optimization process, which significantly speeds up the optimization process. The resulting solution is equivalent to directly using satisfaction as the objective function.
- Parameters:
alpha_dict (dict, optional) – A dictionary containing sensitivity factor for satisfaction calculation, given as an input under the CONSUMAT dictionary. The default value is None.
- Return type:
None.
- finish_setup(display_summary=True)
This method completes the setup for the optimization model.
- Parameters:
display_summary (bool, optional) – Display the model summary. The default is True.
- Return type:
None
- solve(keep_gp_model=False, keep_gp_output=False, display_report=True, **kwargs)
This method solves the optimization problem. Note that, by default, we set the gurobi parameter, NonConvex = 2 for a non-convex model.
- Parameters:
keep_gp_model (bool) – Keep the gurobi model instance for further use. This should be used with caution. The default is False.
keep_gp_output (bool) – If True, the gurobi model output will be stored in “gp_output” in a dictionary format. The default is False.
display_report (bool) – This parameter displays the summary report if set to True. The default is True.
**kwargs (**kwargs) – Pass the gurobi keywords to the gurobi solver.
- Return type:
None.
Notes
- More info on Gurobi MIP Models can be accessed at:
https://www.gurobi.com/documentation/9.5/refman/mip_models.html
- do_IIS_gp(filename=None)
Compute an Irreducible Inconsistent Subsystem (IIS). This function can only be executed if the model is infeasible.
An IIS is a subset of the constraints and variable bounds with the following properties:
It is still infeasible, and
If a single constraint or bound is removed, the subsystem becomes feasible.
Note that an infeasible model may have multiple IISs. The one returned by Gurobi is not necessarily the smallest one; others may exist with a fewer constraints or bounds.
More info: https://www.gurobi.com/documentation/10.0/refman/py_model_computeiis.html
- Parameters:
filename (str) – Output filename. The default is None.
- Return type:
None.
- write_ilp(filename)
This function outputs the information about the results of the IIS computation to .ilp and can only be executed after do_IIS_gp().
- Parameters:
filename (str) – Output filename.
- Return type:
None.
- write_sol(filename)
This function outputs the solution of the model to a .sol file.
- Parameters:
filename (str) – Output filename.
- Return type:
None.
py_champ.components.optimization_1f1w module
- class py_champ.components.optimization_1f1w.Optimization4SingleFieldAndWell
Bases:
objectA class to set up an optimization model for a single field and well.
- setup_ini_model(unique_id, gpenv, horizon=1, crop_options=None)
Set up an optimization model for a single field and well.
- setup_constr_field(field_id, field_area, prec_aw, water_yield_curves, field_type='optimize', i_crop=None, i_rainfed=None, **kwargs)
Set up constraints for a field.
- Parameters:
field_id (str) – Field id.
field_area (float) – Field area [ha].
prec_aw (dict) – Available precipitation [cm].
water_yield_curves (dict) – Water yield curves for different crops.
field_type (str, optional) – Field type. The default is “optimize”.
i_crop (np.array, optional) – Given crop types. The default is None.
i_rainfed (np.array, optional) – Given rainfed options. The default is None.
- Return type:
None.
- setup_constr_well(well_id, dwl, B, l_wt, eff_pump, pumping_capacity=None, rho=1000.0, g=9.8016)
Set up constraints for a well.
- Parameters:
well_id (str) – Well id.
dwl (float) – Drawdown per unit pumping [m].
B (float) – Aquifer storage coefficient.
l_wt (float) – Lift head [m].
eff_pump (float) – Pump efficiency.
pumping_capacity (float, optional) – Pumping capacity [m-ha]. The default is None.
rho (float, optional) – Water density [kg/m^3]. The default is 1000.0.
g (float, optional) – Gravity [m/s^2]. The default is 9.8016.
- Return type:
None.
- setup_constr_finance(finance_dict)
- setup_constr_wr(water_right_id, wr_depth, time_window=1, remaining_tw=None, remaining_wr=None, tail_method='proportion')
Set up water right constraints for the optimization model. You can assign multiple water rights constraints by calling this function repeatedly with different water_right_id. Water rights can constrain all fields or a selected subset of fields with an optional time_window argument, allowing the farmer to allocate their water rights across multiple years. To enforce water rights at the point of diversion, pumping capacity can be assigned to individual wells in setup_constr_well() method.
- Parameters:
water_right_id (str or int) – The water right id serves as a means to differentiate the equation sets for different water rights.
wr_depth (float) – Depth of the water right [cm].
time_window (int, optional) – If given, the water right constrains the total irrigation depth over the time window [yr]. The default is 1.
remaining_tw (int, optional) – Remaining years of time window that the remaining_wr will be applied to [yr]. The default is None.
remaining_wr (float, optional) – The remaining water rights left unused from the previous time window [cm]. The default is None.
tail_method ("proportion" or "all" or float, optional) –
Method to allocate water rights to the incomplete part of the time window at the end of the planning period.
”proportion” means water equivalent to wr_depth*(tail length/time_window) is applied to the tail part of the planning period.
”all” means water equivalent to wr_depth is applied to the tail part of planning period.
If a float is given, the given value will be applied directly to the tail part of planning period.
The default is “proportion”.
- Return type:
None.
- setup_obj(target='profit', consumat_dict=None)
This method sets the objective of the optimization model, i.e., to maximize the agent’s expected satisfaction. Note that the satisfaction value is calculated after the optimization process, which significantly speeds up the optimization process. The resulting solution is equivalent to directly using satisfaction as the objective function.
- Return type:
None.
- finish_setup(display_summary=True)
This method completes the setup for the optimization model.
- Parameters:
display_summary (bool, optional) – Display the model summary. The default is True.
- Return type:
None
- solve(keep_gp_model=False, keep_gp_output=False, display_report=True, **kwargs)
- do_IIS_gp(filename=None)
Compute an Irreducible Inconsistent Subsystem (IIS). This function can only be executed if the model is infeasible.
An IIS is a subset of the constraints and variable bounds with the following properties:
It is still infeasible, and
If a single constraint or bound is removed, the subsystem becomes feasible.
Note that an infeasible model may have multiple IISs. The one returned by Gurobi is not necessarily the smallest one; others may exist with a fewer constraints or bounds.
More info: https://www.gurobi.com/documentation/10.0/refman/py_model_computeiis.html
- Parameters:
filename (str) – Output filename. The default is None.
- Return type:
None.
- write_file(filename, extension)
This function outputs the model to a specified file format based on the extension provided. Supported extensions are .ilp, .sol, .lp, and .mps. The function appends the correct extension to the filename if not already present and writes the model to the file.
- class py_champ.components.optimization_1f1w.Optimization4SingleFieldAndWell_simCJ
Bases:
objectA class to set up an optimization model for a single field and well.
- setup_ini_model(unique_id, gpenv, horizon=1, crop_options=None)
Set up an optimization model for a single field and well.
- setup_constr_field(field_id, field_area, prec_aw, water_yield_curves, field_type='optimize', i_crop=None, i_rainfed=None, **kwargs)
Set up constraints for a field.
- Parameters:
field_id (str) – Field id.
field_area (float) – Field area [ha].
prec_aw (dict) – Available precipitation [cm].
water_yield_curves (dict) – Water yield curves for different crops.
field_type (str, optional) – Field type. The default is “optimize”.
i_crop (np.array, optional) – Given crop types. The default is None.
i_rainfed (np.array, optional) – Given rainfed options. The default is None.
- Return type:
None.
- setup_constr_well(well_id, dwl, B, l_wt, eff_pump, pumping_capacity=None, rho=1000.0, g=9.8016)
Set up constraints for a well.
- Parameters:
well_id (str) – Well id.
dwl (float) – Drawdown per unit pumping [m].
B (float) – Aquifer storage coefficient.
l_wt (float) – Lift head [m].
eff_pump (float) – Pump efficiency.
pumping_capacity (float, optional) – Pumping capacity [m-ha]. The default is None.
rho (float, optional) – Water density [kg/m^3]. The default is 1000.0.
g (float, optional) – Gravity [m/s^2]. The default is 9.8016.
- Return type:
None.
- setup_constr_finance(finance_dict)
- setup_constr_wr(water_right_id, wr_depth, time_window=1, remaining_tw=None, remaining_wr=None, tail_method='proportion')
Set up water right constraints for the optimization model. You can assign multiple water rights constraints by calling this function repeatedly with different water_right_id. Water rights can constrain all fields or a selected subset of fields with an optional time_window argument, allowing the farmer to allocate their water rights across multiple years. To enforce water rights at the point of diversion, pumping capacity can be assigned to individual wells in setup_constr_well() method.
- Parameters:
water_right_id (str or int) – The water right id serves as a means to differentiate the equation sets for different water rights.
wr_depth (float) – Depth of the water right [cm].
time_window (int, optional) – If given, the water right constrains the total irrigation depth over the time window [yr]. The default is 1.
remaining_tw (int, optional) – Remaining years of time window that the remaining_wr will be applied to [yr]. The default is None.
remaining_wr (float, optional) – The remaining water rights left unused from the previous time window [cm]. The default is None.
tail_method ("proportion" or "all" or float, optional) –
Method to allocate water rights to the incomplete part of the time window at the end of the planning period.
”proportion” means water equivalent to wr_depth*(tail length/time_window) is applied to the tail part of the planning period.
”all” means water equivalent to wr_depth is applied to the tail part of planning period.
If a float is given, the given value will be applied directly to the tail part of planning period.
The default is “proportion”.
- Return type:
None.
- setup_obj(target='profit', consumat_dict=None)
This method sets the objective of the optimization model, i.e., to maximize the agent’s expected satisfaction. Note that the satisfaction value is calculated after the optimization process, which significantly speeds up the optimization process. The resulting solution is equivalent to directly using satisfaction as the objective function.
- Return type:
None.
- finish_setup(display_summary=True)
This method completes the setup for the optimization model.
- Parameters:
display_summary (bool, optional) – Display the model summary. The default is True.
- Return type:
None
- solve(keep_gp_model=False, keep_gp_output=False, display_report=True, **kwargs)
- do_IIS_gp(filename=None)
Compute an Irreducible Inconsistent Subsystem (IIS). This function can only be executed if the model is infeasible.
An IIS is a subset of the constraints and variable bounds with the following properties:
It is still infeasible, and
If a single constraint or bound is removed, the subsystem becomes feasible.
Note that an infeasible model may have multiple IISs. The one returned by Gurobi is not necessarily the smallest one; others may exist with a fewer constraints or bounds.
More info: https://www.gurobi.com/documentation/10.0/refman/py_model_computeiis.html
- Parameters:
filename (str) – Output filename. The default is None.
- Return type:
None.
- write_file(filename, extension)
This function outputs the model to a specified file format based on the extension provided. Supported extensions are .ilp, .sol, .lp, and .mps. The function appends the correct extension to the filename if not already present and writes the model to the file.
- class py_champ.components.optimization_1f1w.Optimization4SingleFieldAndWell_ogCJ
Bases:
objectA class to set up an optimization model for a single field and well.
- setup_ini_model(unique_id, gpenv, horizon=1, crop_options=None)
Set up an optimization model for a single field and well.
- setup_constr_field(field_id, field_area, prec_aw, water_yield_curves, field_type='optimize', i_crop=None, i_rainfed=None, **kwargs)
Set up constraints for a field.
- Parameters:
field_id (str) – Field id.
field_area (float) – Field area [ha].
prec_aw (dict) – Available precipitation [cm].
water_yield_curves (dict) – Water yield curves for different crops.
field_type (str, optional) – Field type. The default is “optimize”.
i_crop (np.array, optional) – Given crop types. The default is None.
i_rainfed (np.array, optional) – Given rainfed options. The default is None.
- Return type:
None.
- setup_constr_well(well_id, dwl, st, l_wt, r, k, sy, eff_pump, eff_well, pumping_days, pumping_capacity=None, rho=1000.0, g=9.8016)
Set up constraints for a well.
- Parameters:
well_id (str or int) – The well id serves as a means to differentiate the equation sets for different wells.
dwl (float) – Percieved annual water level change rate [m/yr].
st (float) – Aquifer saturated thickness at the initial time step [m]. Given as an input in the init dicitonary of well settings.
l_wt (float) – The head required to lift water from the water table to the ground surface at the start of the pumping season at the initial time step [m]. Given as an input in the init dicitonary of well settings.
r (float) – Well radius [m]. Given as an input in the well settings.
k (float) – Hydraulic conductivity [m/day]. This will be used to calculate transmissivity [m²/day] by multipling k with the saturated thickness [m]. Given as an input in the well settings.
sy (float) – Specific yield of the aquifer [-]. Given as an input in the well settings.
eff_pump (float) – Pump efficiency as a fraction [-]. Given as an input in the well settings.
eff_well (float) – Well efficiency as a fraction [-]. Given as an input in the well settings.
pumping_days (int) – Number of days the well is operational [day]. Given as an input in the init dictionary of the well settings.
pumping_capacity (float) – Maximum pumping capacity of the well [m-ha/yr]. The default is None. Given as an input in the well settings.
rho (float) – density of water [kg/m3].
g (float) – acceleration due to gravity [m/s²].
- Return type:
None.
- setup_constr_finance(finance_dict)
- setup_constr_wr(water_right_id, wr_depth, time_window=1, remaining_tw=None, remaining_wr=None, tail_method='proportion')
Set up water right constraints for the optimization model. You can assign multiple water rights constraints by calling this function repeatedly with different water_right_id. Water rights can constrain all fields or a selected subset of fields with an optional time_window argument, allowing the farmer to allocate their water rights across multiple years. To enforce water rights at the point of diversion, pumping capacity can be assigned to individual wells in setup_constr_well() method.
- Parameters:
water_right_id (str or int) – The water right id serves as a means to differentiate the equation sets for different water rights.
wr_depth (float) – Depth of the water right [cm].
time_window (int, optional) – If given, the water right constrains the total irrigation depth over the time window [yr]. The default is 1.
remaining_tw (int, optional) – Remaining years of time window that the remaining_wr will be applied to [yr]. The default is None.
remaining_wr (float, optional) – The remaining water rights left unused from the previous time window [cm]. The default is None.
tail_method ("proportion" or "all" or float, optional) –
Method to allocate water rights to the incomplete part of the time window at the end of the planning period.
”proportion” means water equivalent to wr_depth*(tail length/time_window) is applied to the tail part of the planning period.
”all” means water equivalent to wr_depth is applied to the tail part of planning period.
If a float is given, the given value will be applied directly to the tail part of planning period.
The default is “proportion”.
- Return type:
None.
- setup_obj(target='profit', consumat_dict=None)
This method sets the objective of the optimization model, i.e., to maximize the agent’s expected satisfaction. Note that the satisfaction value is calculated after the optimization process, which significantly speeds up the optimization process. The resulting solution is equivalent to directly using satisfaction as the objective function.
- Return type:
None.
- finish_setup(display_summary=True)
This method completes the setup for the optimization model.
- Parameters:
display_summary (bool, optional) – Display the model summary. The default is True.
- Return type:
None
- solve(keep_gp_model=False, keep_gp_output=False, display_report=True, **kwargs)
- do_IIS_gp(filename=None)
Compute an Irreducible Inconsistent Subsystem (IIS). This function can only be executed if the model is infeasible.
An IIS is a subset of the constraints and variable bounds with the following properties:
It is still infeasible, and
If a single constraint or bound is removed, the subsystem becomes feasible.
Note that an infeasible model may have multiple IISs. The one returned by Gurobi is not necessarily the smallest one; others may exist with a fewer constraints or bounds.
More info: https://www.gurobi.com/documentation/10.0/refman/py_model_computeiis.html
- Parameters:
filename (str) – Output filename. The default is None.
- Return type:
None.
- write_file(filename, extension)
This function outputs the model to a specified file format based on the extension provided. Supported extensions are .ilp, .sol, .lp, and .mps. The function appends the correct extension to the filename if not already present and writes the model to the file.
py_champ.components.optimization_1f1w_ci module
- class py_champ.components.optimization_1f1w_ci.Optimization_1f1w_ci
Bases:
objectThis class is specifically designed for 1 field and 1 well with fixed irrigation technology to facilitate the solving speed.
- setup_ini_model(unique_id, gpenv, activate_ci, horizon=1, crop_options=None)
- setup_constr_field(field_id, field_area, prec_aw, water_yield_curves, field_type='optimize', i_crop=None, i_rainfed=None, premium_dict=None, aph_yield_dict=None, **kwargs)
- setup_constr_well(well_id, dwl, B, l_wt, eff_pump, pumping_capacity=None, rho=1000.0, g=9.8016)
- setup_constr_finance(finance_dict, payout_ratio=1, premium_ratio=1)
- setup_constr_wr(water_right_id, wr_depth, time_window=1, remaining_tw=None, remaining_wr=None, tail_method='proportion')
Set up water right constraints for the optimization model. You can assign multiple water rights constraints by calling this function repeatedly with different water_right_id. Water rights can constrain all fields or a selected subset of fields with an optional time_window argument, allowing the farmer to allocate their water rights across multiple years. To enforce water rights at the point of diversion, pumping capacity can be assigned to individual wells in setup_constr_well() method.
- Parameters:
water_right_id (str or int) – The water right id serves as a means to differentiate the equation sets for different water rights.
wr_depth (float) – Depth of the water right [cm].
time_window (int, optional) – If given, the water right constrains the total irrigation depth over the time window [yr]. The default is 1.
remaining_tw (int, optional) – Remaining years of time window that the remaining_wr will be applied to [yr]. The default is None.
remaining_wr (float, optional) – The remaining water rights left unused from the previous time window [cm]. The default is None.
tail_method ("proportion" or "all" or float, optional) –
Method to allocate water rights to the incomplete part of the time window at the end of the planning period.
”proportion” means water equivalent to wr_depth*(tail length/time_window) is applied to the tail part of the planning period.
”all” means water equivalent to wr_depth is applied to the tail part of planning period.
If a float is given, the given value will be applied directly to the tail part of planning period.
The default is “proportion”.
- Return type:
None.
- setup_obj(target='profit', consumat_dict=None)
This method sets the objective of the optimization model, i.e., to maximize the agent’s expected satisfaction. Note that the satisfaction value is calculated after the optimization process, which significantly speeds up the optimization process. The resulting solution is equivalent to directly using satisfaction as the objective function.
- Return type:
None.
- finish_setup(display_summary=True)
This method completes the setup for the optimization model.
- Parameters:
display_summary (bool, optional) – Display the model summary. The default is True.
- Return type:
None
- solve(keep_gp_model=False, keep_gp_output=False, display_report=True, **kwargs)
- do_IIS_gp(filename=None)
Compute an Irreducible Inconsistent Subsystem (IIS). This function can only be executed if the model is infeasible.
An IIS is a subset of the constraints and variable bounds with the following properties:
It is still infeasible, and
If a single constraint or bound is removed, the subsystem becomes feasible.
Note that an infeasible model may have multiple IISs. The one returned by Gurobi is not necessarily the smallest one; others may exist with a fewer constraints or bounds.
More info: https://www.gurobi.com/documentation/10.0/refman/py_model_computeiis.html
- Parameters:
filename (str) – Output filename. The default is None.
- Return type:
None.
- write_ilp(filename)
This function outputs the information about the results of the IIS computation to .ilp and can only be executed after do_IIS_gp().
- Parameters:
filename (str) – Output filename.
- Return type:
None.
- write_sol(filename)
This function outputs the solution of the model to a .sol file.
- Parameters:
filename (str) – Output filename.
- Return type:
None.
- write_lp(filename)
This function outputs the model to a .lp file.
- Parameters:
filename (str) – Output filename.
- Return type:
None.
- write_mps(filename)
This funtion outputs the model to an .mps file.
- Parameters:
filename (str) – Output filename.
- Return type:
None.
- depose_gp_env()
- py_champ.components.optimization_1f1w_ci.dict_to_string(dictionary, prefix='', indentor=' ', level=2, roun=None)
Ture a dictionary into a printable string.
py_champ.components.well module
- class py_champ.components.well.Well(unique_id, model, settings: dict, **kwargs)
Bases:
AgentThis module is a well simulator.
- Parameters:
unique_id (int) – A unique identifier for this agent.
model – The model instance to which this agent belongs.
settings (dict) –
A dictionary containing settings specific to a well, such as hydraulic properties and initial conditions.
’r’: Radius of the well [m].
’k’: Hydraulic conductivity of the aquifer [m/day].
’sy’: Specific yield of the aquifer [-].
’rho’: Density of water [kg/m³].
’g’: Acceleration due to gravity [m/s²].
’eff_pump’: Pump efficiency as a fraction [-].
’eff_well’: Well efficiency as a fraction [-].
’pumping_capacity’: Maximum pumping capacity of the well [m-ha/year].
’init’: Initial conditions, which include water table lift (l_wt [m]), saturated thickness (st [m]) and pumping_days (days).
>>> # A sample settings dictionary >>> settings = { >>> "r": None, >>> "k": None, >>> "sy": None, >>> "rho": None, >>> "g": None, >>> "eff_pump": None, >>> "eff_well": None, >>> "aquifer_id": None, >>> "pumping_capacity": None, >>> "init":{ >>> "l_wt": None, >>> "st": None, >>> "pumping_days": None >>> }, >>> }
**kwargs – Additional keyword arguments that can be dynamically set as well agent attributes.
Notes
Transmissivity ‘tr’ is calculated as the product of saturated thickness and hydraulic conductivity.
- load_settings(settings: dict)
Load the well settings from the dictionary.
- Parameters:
settings (dict) – A dictionary containing well settings. Expected keys include ‘r’, ‘k’, ‘sy’, ‘rho’, ‘g’, ‘eff_pump’, ‘eff_well’, ‘aquifer_id’, ‘pumping_capacity’, and ‘init’.
- step(withdrawal: float, dwl: float, pumping_rate: float, l_pr: float, pumping_days: int | None = None) float
Perform a single step of well simulation, calculating the energy consumption.
- Parameters:
withdrawal (float) – The amount of water withdrawn in this step [m-ha].
dwl (float) – The change in the water level due to withdrawal [m].
pumping_rate (float) – The rate at which water is being pumped [m-ha/day].
l_pr (float) – effective loss due to pressurization of water and losses in the piping, dependent on the type of the irrigation system [m].
pumping_days (int, optional) – Number of days the well is operational. If not specified, previous value is used.
- Returns:
The energy consumption for this step [Petajoules, PJ].
- Return type:
Notes
The method calculates energy consumption based on several factors including withdrawal volume, water table lift, well and pump efficiency, and hydraulic properties of the aquifer.
- class py_champ.components.well.Well4SingleFieldAndWell(unique_id, model, settings: dict, **kwargs)
Bases:
AgentA well simulator for single field and well.
- load_settings(settings: dict)
Load the well settings from the dictionary.
- Parameters:
settings (dict) – A dictionary containing well settings. Expected keys include ‘r’, ‘k’, ‘sy’, ‘rho’, ‘g’, ‘eff_pump’, ‘eff_well’, ‘aquifer_id’, ‘pumping_capacity’, and ‘init’.
- class py_champ.components.well.Well4SingleFieldAndWell_simCJ(unique_id, model, settings: dict, **kwargs)
Bases:
AgentA well simulator for single field and well.
- load_settings(settings: dict)
Load the well settings from the dictionary.
- Parameters:
settings (dict) – A dictionary containing well settings. Expected keys include ‘r’, ‘k’, ‘sy’, ‘rho’, ‘g’, ‘eff_pump’, ‘eff_well’, ‘aquifer_id’, ‘pumping_capacity’, and ‘init’.
- class py_champ.components.well.Well4SingleFieldAndWell_ogCJ(unique_id, model, settings: dict, **kwargs)
Bases:
AgentA well simulator for single field and well.
- load_settings(settings: dict)
Load the well settings from the dictionary.
- Parameters:
settings (dict) – A dictionary containing well settings. Expected keys include ‘r’, ‘k’, ‘sy’, ‘rho’, ‘g’, ‘eff_pump’, ‘eff_well’, ‘aquifer_id’, ‘pumping_capacity’, and ‘init’.
Module contents
Store the components (modules) of PyCHAMP.