Farmers

class CropFarmers(model, agents, reduncancy)[source]

The agent class for the farmers. Contains all data and behaviourial methods. The __init__ function only gets the model as arguments, the agent parent class and the redundancy. All other variables are loaded at later stages.

Parameters:
  • model – The GEB model.

  • agents – The class that includes all agent types (allowing easier communication between agents).

  • redundancy – a lot of data is saved in pre-allocated NumPy arrays. While this allows much faster operation, it does mean that the number of agents cannot grow beyond the size of the pre-allocated arrays. This parameter allows you to specify how much redundancy should be used. A lower redundancy means less memory is used, but the model crashes if the redundancy is insufficient.

abstract_water(gross_irrigation_demand_m3_per_field, available_channel_storage_m3, available_groundwater_m3, groundwater_depth, available_reservoir_storage_m3)[source]

This function allows the abstraction of water by farmers for irrigation purposes. It’s main purpose is to call the relevant numba function to do the actual abstraction. In addition, the function saves the abstraction from the various sources by farmer.

Parameters:
  • cell_area – the area of each subcell in m2.

  • HRU_to_grid – array to map the index of each subcell to the corresponding cell.

  • totalPotIrrConsumption – potential irrigation consumption.

  • available_channel_storage_m3 (ndarray) – water available for irrigation from channels.

  • groundwater_head – groundwater head.

  • available_groundwater_m3 (ndarray) – water available for irrigation from groundwater.

  • available_reservoir_storage_m3 (ndarray) – water available for irrigation from reservoirs.

  • command_areas – command areas associated with reservoirs (i.e., which areas can access water from which reservoir.)

Returns:
  • water_withdrawal_m – water withdrawal in meters

  • water_consumption_m – water consumption in meters

  • returnFlowIrr_m – return flow in meters

  • addtoevapotrans_m – evaporated irrigation water in meters

Return type:

tuple[ndarray, ndarray, ndarray, ndarray]

property activation_order_by_elevation

Activation order is determined by the agent elevation, starting from the highest. Agents with the same elevation are randomly shuffled.

adapt_irrigation_efficiency(energy_cost, water_cost)[source]

Handle the adaptation of farmers to irrigation wells.

This function checks which farmers will adopt irrigation wells based on their expected utility and the provided constraints. It calculates the costs and the benefits for each farmer and updates their statuses (e.g., irrigation source, adaptation costs) accordingly.

Note: :rtype: None

adapt_irrigation_well(average_extraction_speed, energy_cost, water_cost)[source]

Handle the adaptation of farmers to irrigation wells.

This function checks which farmers will adopt irrigation wells based on their expected utility and the provided constraints. It calculates the costs and the benefits for each farmer and updates their statuses (e.g., irrigation source, adaptation costs) accordingly.

Note: :rtype: None

adaptation_water_cost_difference(adapted, energy_cost, water_cost)[source]

Calculate the relative yield ratio improvement for farmers adopting a certain adaptation.

This function determines how much better farmers that have adopted a particular adaptation are doing in terms of their yield ratio as compared to those who haven’t.

Parameters:
  • adapted (np.ndarray) – Array indicating adaptation status (0 or 1) for each agent.

  • energy_cost (np.ndarray) – Array of energy costs for each agent.

  • water_cost (np.ndarray) – Array of water costs for each agent.

Returns:

Tuple[np.ndarray, np.ndarray] – Arrays representing the relative energy cost and water cost improvements for each agent.

Return type:

Tuple[ndarray, ndarray]

adaptation_yield_ratio_difference(adapted, yield_ratios)[source]

Calculate the relative yield ratio improvement for farmers adopting a certain adaptation.

This function determines how much better farmers that have adopted a particular adaptation are doing in terms of their yield ratio as compared to those who haven’t.

Parameters:

adaptation_type – The type of adaptation being considered.

Returns:

An array representing the relative yield ratio improvement for each agent.

Return type:

ndarray

TO DO: vectorize

add_agent(indices, values={'EUT_no_adapt': 1, 'GEV_parameters': 1, 'SEUT_no_adapt': 1, 'adapted': False, 'annual_costs_all_adaptations': 1, 'base_management_yield_ratio': 1, 'channel_abstraction_m3_by_farmer': 0, 'crops': -1, 'decision_horizon': 1, 'discount_rate': 1, 'disposable_income': 0, 'drought_timer': 1, 'farmer_class': 1, 'farmer_yield_probability_relation': 1, 'groundwater_abstraction_m3_by_farmer': 0, 'household_size': 2, 'interest_rate': 1, 'irrigation_efficiency': 0.9, 'irrigation_source': -1, 'monthly_SPEI': 0, 'per_harvest_SPEI': 0, 'per_harvest_yield_ratio': 0, 'reservoir_abstraction_m3_by_farmer': 0, 'risk_aversion': 1, 'risk_decr': 1, 'risk_perc_max': 1, 'risk_perc_min': 1, 'risk_perception': 1, 'time_adapted': False, 'total_crop_age': 0, 'water_use': 1, 'well_depth': -1, 'yearly_SPEI_probability': 1, 'yearly_abstraction_m3_by_farmer': 0, 'yearly_potential_profits': 1, 'yearly_profits': 1, 'yearly_yield_ratio': 1, 'yield_ratio_management': 1, 'yield_ratios_drought_event': 1})[source]

This function can be used to add new farmers.

calculate_water_costs()[source]

Calculate the water and energy costs per agent and the average extraction speed.

This method computes the energy costs for agents using groundwater, the water costs for all agents depending on their water source, and the average extraction speed per agent. It also updates the loans and annual costs associated with water and energy use.

Returns:

Tuple[np.ndarray, np.ndarray, np.ndarray] – A tuple containing: - energy_costs (np.ndarray): Energy costs per agent (LCU/year). - water_costs (np.ndarray): Water costs per agent (LCU/year). - average_extraction_speed (np.ndarray): Average water extraction speed per agent (m³/s).

Return type:

Tuple[ndarray, ndarray, ndarray]

calculate_well_costs_global(groundwater_depth, average_extraction_speed)[source]

Calculate the annual costs associated with well installation and operation globally.

This function computes the annual costs for installing wells, maintaining them, and the energy costs associated with pumping groundwater for each agent (farmer). It takes into account regional variations in costs and agent-specific parameters such as groundwater depth and extraction speed.

Parameters:
  • groundwater_depth (np.ndarray) – Array of groundwater depths per agent (in meters).

  • average_extraction_speed (np.ndarray) – Array of average water extraction speeds per agent (m³/s).

Returns:

Tuple[np.ndarray, np.ndarray]

  • annual_cost (np.ndarray): Annual cost per agent (local currency units per year).

  • potential_well_length (np.ndarray): Potential well length per agent (in meters).

Return type:

Tuple[ndarray, ndarray]

compute_total_profits(yield_ratios, crops_mask, nan_array)[source]

Compute total profits for all agents across different drought scenarios.

Parameters:
  • yield_ratios (np.ndarray) – Yield ratios for agents under different drought scenarios.

  • crops_mask (np.ndarray) – Mask indicating valid crop entries.

  • nan_array (np.ndarray) – Array filled with NaNs for reference.

Returns:

np.ndarray – Total profits for agents under each drought scenario.

Return type:

ndarray

convert_probability_to_yield_ratio()[source]

Convert drought probabilities to yield ratios based on the given polynomial relationship.

For each farmer’s yield-probability relationship (represented as a polynomial), this function calculates the inverse of the relationship and then applies the inverted polynomial to a set of given probabilities to obtain yield ratios. The resulting yield ratios are then adjusted to lie between 0 and 1. The final results are stored in self.var.yield_ratios_drought_event. :rtype: ndarray

Note

  • It assumes that the polynomial relationship is invertible.

  • Adjusts yield ratios to be non-negative and capped at 1.0.

create_unique_groups(*additional_diffentiators)[source]

Create unique groups based on elevation data and merge with crop calendar.

Parameters: N (int): Number of groups to divide the elevation data into.

Returns: numpy.ndarray: Merged array with crop calendar and elevation distribution groups.

drought_risk_perception(harvesting_farmers, total_crop_age)[source]

Calculate and update the drought risk perception for harvesting farmers.

Parameters:

harvesting_farmers (ndarray) – Index array of farmers that are currently harvesting.

Return type:

None

This function computes the risk perception of farmers based on the difference between their latest profits and potential profits. The perception is influenced by the historical losses and time since the last drought event. Farmers who have experienced a drought event will have their drought timer reset.

TODO: Perhaps move the constant to the model.yml

property field_size_per_farmer: ndarray

Gets the field size for each farmer.

Returns:

field_size_per_farmer – Field size for each farmer in m2.

static field_size_per_farmer_numba(field_indices_by_farmer, field_indices, cell_area)[source]

Gets the field size for each farmer.

Parameters:
  • field_indices_by_farmer (ndarray) – This array contains the indices where the fields of a farmer are stored in field_indices.

  • field_indices (ndarray) – This array contains the indices of all fields, ordered by farmer. In other words, if a farmer owns multiple fields, the indices of the fields are indices.

  • cell_area (ndarray) – Subarray of cell_area.

Returns:

field_size_per_farmer – Field size for each farmer in m2.

Return type:

ndarray

format_results(total_profits)[source]

Transpose and slice the total profits matrix, and extract the ‘no drought’ scenario profits.

Parameters:

total_profits (np.ndarray) – Total profits matrix.

Returns:

Tuple[np.ndarray, np.ndarray] – Transposed profits and ‘no drought’ scenario profits.

Return type:

Tuple[ndarray, ndarray]

get_yield_ratio(harvest, actual_transpiration, potential_transpiration, crop_map)[source]

Gets yield ratio for each crop given the ratio between actual and potential evapostranspiration during growth.

Parameters:
  • harvest (ndarray) – Map of crops that are harvested.

  • actual_transpiration (ndarray) – Actual evapotranspiration during crop growth period.

  • potential_transpiration (ndarray) – Potential evapotranspiration during crop growth period.

  • crop_map (ndarray) – Subarray of type of crop grown.

Returns:

yield_ratio – Map of yield ratio.

Return type:

ndarray

TODO: Implement GAEZ crop stage function

static get_yield_ratio_numba_GAEZ(crop_map, evap_ratios, KyT)[source]

Calculate yield ratio based on https://doi.org/10.1016/j.jhydrol.2009.07.031

Parameters:
  • crop_map (ndarray) – array of currently harvested crops.

  • evap_ratios (ndarray) – ratio of actual to potential evapotranspiration of harvested crops.

  • KyT – Water stress reduction factor from GAEZ.

Returns:

yield_ratios – yield ratio (as ratio of maximum obtainable yield) per harvested crop.

Return type:

float

static get_yield_ratio_numba_MIRCA2000(crop_map, evap_ratios, alpha, beta, P0, P1)[source]

Calculate yield ratio based on https://doi.org/10.1016/j.jhydrol.2009.07.031

Parameters:
  • crop_map (ndarray) – array of currently harvested crops.

  • evap_ratios (ndarray) – ratio of actual to potential evapotranspiration of harvested crops.

  • alpha (ndarray) – alpha value per crop used in MIRCA2000.

  • beta (ndarray) – beta value per crop used in MIRCA2000.

  • P0 (ndarray) – P0 value per crop used in MIRCA2000.

  • P1 (ndarray) – P1 value per crop used in MIRCA2000.

Returns:

yield_ratios – yield ratio (as ratio of maximum obtainable yield) per harvested crop.

Return type:

float

harvest()[source]

Determine which crops need to be harvested based on their current age and their harvest age. Once harvested, compute various metrics related to the harvest including potential profit, actual profit, crop age, drought perception, and update corresponding attributes of the model. Save the corresponding SPEI over the last harvest.

harvest_numba[source]

A helper function to obtain the harvest map.

get_yield_ratio[source]

A function to calculate yield ratio based on the ratio of actual to potential evapotranspiration.

Note

The function also updates the drought risk perception and tracks disposable income.

static harvest_numba(n, field_indices_by_farmer, field_indices, crop_map, crop_age_days, crop_harvest_age_days)[source]

This function determines whether crops are ready to be harvested by comparing the crop harvest age to the current age of the crop. If the crop is harvested, the crops next multicrop index and next plant day are determined.

Parameters:
  • n (ndarray) – Number of farmers.

  • start_day_per_month – Array containing the starting day of each month.

  • field_indices_by_farmer (ndarray) – This array contains the indices where the fields of a farmer are stored in field_indices.

  • field_indices (ndarray) – This array contains the indices of all fields, ordered by farmer. In other words, if a farmer owns multiple fields, the indices of the fields are indices.

  • crop_map (ndarray) – Subarray map of crops.

  • crop_age_days (ndarray) – Subarray map of current crop age in days.

  • crop – Crops grown by each farmer.

  • switch_crops – Whether to switch crops or not.

Returns:

harvest – Boolean subarray map of fields to be harvested.

Return type:

ndarray

property irrigated_fields: ndarray

Gets the indices of fields that are irrigated.

Returns:

irrigated_fields – Indices of fields that are irrigated.

microcredit(loaning_farmers, drought_loss_current, total_crop_age)[source]

Compute the microcredit for farmers based on their average profits, drought losses, and the age of their crops with respect to their total cropping time.

Parameters: - loaning_farmers: Boolean mask of farmers looking to obtain a loan, based on drought loss of harvesting farmers. - drought_loss_current: Array of drought losses of the most recent harvest for each farmer. - total_crop_age: Array of total age for crops of each farmer.

Return type:

None

plant()[source]

Determines when and what crop should be planted, mainly through calling the agents.farmers.Farmers.plant_numba(). Then converts the array to cupy array if model is running with GPU.

Return type:

None

profits_SEUT(adapted=None)[source]

Calculate total profits under different drought probability scenarios, with and without adaptation measures for adaptation types 0 and 1.

Parameters:
  • adaptation_type (int) – The type of adaptation to consider. - 0: No adaptation. - 1: Adaptation Type 1 (e.g., installing wells).

  • adapted (np.ndarray, optional) – An array indicating which agents have adapted (relevant for adaptation_type == 1).

Returns:
  • Depending on adaptation_type, returns a tuple containing total profits and profits under ‘no drought’ scenario,

  • possibly including adaptation profits.

Return type:

Union[Tuple[ndarray, ndarray], Tuple[ndarray, ndarray, ndarray, ndarray]]

profits_SEUT_crops(unique_crop_calendars)[source]

Calculate total profits under different drought probability scenarios with crop adaptation measures (Adaptation Type 2).

Returns:

Tuple containing profits without adaptation, profits with adaptation options, and additional data.

Return type:

Tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray]

save_harvest_spei(harvesting_farmers)[source]

Update the monthly Standardized Precipitation Evapotranspiration Index (SPEI) array by shifting past records and adding the SPEI for the current month. :rtype: None

Note

This method updates the monthly_SPEI attribute in place.

save_yearly_profits(profit, potential_profit)[source]

Saves the latest profit and potential profit values for harvesting farmers to determine yearly profits, considering inflation and field size.

Parameters:
  • harvesting_farmers – Array of farmers who are currently harvesting.

  • profit (ndarray) – Array representing the profit value for each farmer per season.

  • potential_profit (ndarray) – Array representing the potential profit value for each farmer per season.

Return type:

None

Note

This function performs the following operations:
  1. Asserts that all profit and potential profit values are non-negative.

2. Updates the latest profits and potential profits matrices by shifting all columns one column further. The last column value is dropped. 3. Adjusts the yearly profits by accounting for the latest profit, field size, and inflation.

set_social_network()[source]

Determines for each farmer a group of neighbors which constitutes their social network

Return type:

None

step()[source]

This function is called at the beginning of each timestep.

Then, farmers harvest and plant crops.

Return type:

None

update_field_indices()[source]

Creates field_indices_by_farmer and field_indices. These indices are used to quickly find the fields for a specific farmer.

Return type:

None

static update_field_indices_numba(land_owners)[source]

Creates field_indices_by_farmer and field_indices. These indices are used to quickly find the fields for a specific farmer.

Parameters:

land_owners (ndarray) – Array of the land owners. Each unique ID is a different land owner. -1 means the land is not owned by anyone.

Returns:
  • field_indices_by_farmer – This array contains the indices where the fields of a farmer are stored in field_indices.

  • field_indices – This array contains the indices of all fields, ordered by farmer. In other words, if a farmer owns multiple fields, the indices of the fields are indices.

Return type:

tuple[ndarray, ndarray]

water_abstraction_sum()[source]

Aggregates yearly water abstraction from different sources (channel, reservoir, groundwater) for each farmer and also computes the total abstraction per farmer. :rtype: None

Note

This function performs the following steps:
  1. Updates the yearly channel water abstraction for each farmer.

  2. Updates the yearly reservoir water abstraction for each farmer.

  3. Updates the yearly groundwater water abstraction for each farmer.

  4. Computes and updates the total water abstraction for each farmer.

yield_ratio_to_profit(yield_ratios, crops_mask, nan_array)[source]

Convert yield ratios to monetary profit values.

This function computes the profit values for each crop based on given yield ratios. The profit is calculated by multiplying the crop yield in kilograms per sqr. meter with the average crop price. The function leverages various data inputs, such as current crop prices and reference yields.

Parameters:
  • yield_ratios (ndarray) – The array of yield ratios for the crops.

  • crops_mask (ndarray) – A mask that denotes valid crops, based on certain conditions.

  • array_with_reference – An array initialized with NaNs, later used to store reference yields and crop prices.

Returns:

An array representing the profit values for each crop based on the given yield ratios.

Return type:

ndarray

Note

  • It assumes that the crop prices are non-NaN for the current model time.

  • The function asserts that crop yields in kg are always non-negative.

TODO: Take the average crop prices over the last x years.

advance_crop_rotation_year(current_crop_calendar_rotation_year_index, crop_calendar_rotation_years)[source]

Update the crop rotation year for each farmer. This function is used to update the crop rotation year for each farmer at the end of the year.

Parameters:
  • current_crop_calendar_rotation_year_index (ndarray) – The current crop rotation year for each farmer.

  • crop_calendar_rotation_years (ndarray) – The number of years in the crop rotation cycle for each farmer.

cumulative_mean(mean, counter, update, mask=None)[source]

Calculates the cumulative mean of a series of numbers. This function operates in place.

Parameters:
  • mean – The cumulative mean.

  • counter – The number of elements that have been added to the mean.

  • update – The new elements that needs to be added to the mean.

shift_and_reset_matrix(matrix)[source]

Shifts columns to the right in the matrix and sets the first column to zero.

Return type:

None

shift_and_update(array, update)[source]

Shifts the array and updates the first element with the update value.

Parameters:
  • array – The array that needs to be shifted.

  • update – The value that needs to be added to the first element of the array.